This is the first day of my participation in the August Text Challenge.More challenges in August

1 Background: Used to replace traditional JDBC 2 Original JDBC development problems are as follows: ①. The frequent creation and release of database connections waste system resources and affect system performance. ②. SQL statements are hard coded in the code, resulting in code is not easy to maintain, the actual application of SQL changes may be large, SQL changes need to change the Java code. ③ During the query operation, you need to manually encapsulate the data in the result set into entities. When inserting, you need to manually set the entity’s data to the placeholder position of the SQL statement. The solution to the above problem is as follows: ①. Initialize connection resources with database connection pool. ②. Extract SQL statements into XML configuration files. ③ Use reflection and other underlying technologies to automatically map attributes and fields between entities and tables. Conclusion: 3 Mybatis framework executes SQL and maps the results to Java objects and returns them. It uses ORM to solve the problem of entity and database mapping, encapsulates JDBC, shields the underlying access details of JDBC API, so that we do not need to deal with JDBC API. You can persist the database. The procedure is as follows: 1 Import dependencies

<! <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <! --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> The < version > 5.1.47 < / version > < / dependency > <! --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <! --> <dependency> <groupId>org.projectlombok</groupId> <artifactId> The < version > 1.16.20 < / version > < / dependency > <! Log4j </artifactId> log4j</artifactId> <version>1.2.17</version> </dependency>Copy the code

2 Prepare the database environment

create database mybatis; use mybatis; CREATE TABLE 'user' (' id 'int(11) NOT NULL AUTO_INCREMENT,' username 'varchar(32) NOT NULL COMMENT' user ', 'sex' char(1) DEFAULT NULL COMMENT 'sex ',' address 'varchar(256) DEFAULT NULL COMMENT' address ', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; Insert into ` user ` (` id `, ` username `, ` sex `, ` address `) values (NULL, 'Tom', 'male', 'Beijing'); Insert into ` user ` (` id `, ` username `, ` sex `, ` address `) values (NULL, 'Jack', 'male', 'Shanghai'); Insert into ` user ` (` id `, ` username `, ` sex `, ` address `) values (NULL, 'Rose', 'female' and 'xian'); Insert into ` user ` (` id `, ` username `, ` sex `, ` address `) values (NULL, 'Poll', 'female' and 'Libya');Copy the code

3 Write the User entity

@Data
public class User {
 private Integer id;
 private String username;
 private String sex;
 private String address; }
Copy the code

4 write the MyBatis core file name: sqlmapconfig.xml

<? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE configuration PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration> <! <environment default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" Value = "JDBC: mysql: / / 127.0.0.1:3306 / mybatis" / > < property name = "username" value = "root" / > < property name = "password" value="root"/> </dataSource> </environment> </environments> <! <mappers> <mapper resource=" usermapper. XML "/> </mappers> </configuration>Copy the code

5 Writing UserMapper Mapping file Name: usermapper.xml

<? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE mapper PUBLIC "- / / mybatis.org//DTD mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > < mapper namespace="userMapper"> <! <select id="findAll" resultType=" com.kb.pojo. User"> select * from User </select> </mapper>Copy the code

6 Query all users

Public class UserTest {@test public void findAllTest() throws IOException {// Load the core configuration file SQLmapconfig.xml InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); SQLSessionFactory SQLSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); / / structure SQLSession objects SQLSession SQLSession = sqlSessionFactory. OpenSession (); List<User> userList = sqlsession.selectList (" usermapper.findAll "); for (User user : userList) { System.out.println("user = " + user); } // Release resources sqlsession.close (); }}Copy the code