(1) Read the configuration file of MyBatis. mybatis-config.xml is the global configuration file of MyBatis, which is used to configure database connection information.
(2) Load mapping file. The mapping file is the SQL mapping file, in which the SQL statements for operating the database are configured, which needs to be in the MyBatis configuration file MyBatis config Load in XML. mybatis-config.xml file can load multiple mapping files, and each file corresponds to a table in the database.
(3) Construct a session factory. Build the session factory SqlSessionFactory through the environment configuration information of MyBatis.
(4) Create a session object. A SqlSession object is created by the session factory, which contains all methods for executing SQL statements.
(5) Executor. MyBatis defines an executor interface at the bottom to operate the database. It will dynamically generate SQL statements to be executed according to the parameters passed by SqlSession, and is responsible for the maintenance of query cache.
(6) MappedStatement object. In the execution method of the Executor interface, there is a parameter of MappedStatement type. This parameter encapsulates the mapping information and is used to store the id, parameters and other information of the SQL statement to be mapped.
(7) Input parameter mapping. Input parameter types can be set types such as Map and List, basic data types and POJO types. The input parameter mapping process is similar to the process of JDBC setting parameters on the preparedStatement object.
(8) Output result mapping. The output result type can be set types such as Map and List, basic data type and POJO type. The output result mapping process is similar to the JDBC parsing process of the result set.
MyBatis starter
1. Query user
Query customer information with customer number.
CREATE DATABASE mybatis;//Create a database named mybatis use mybatis;//Using mybatis //Create a data table CREATE TABLE t_customer( id int(32) primary key auto_increment, username varchar(50), jobs varchar(50), phone varchar(16) );
2. Create project
Create a java project and import the package of mybatis. Using the mybatis framework, you only need to import the core package of mybatis and the dependent package in the lib directory into the application.
Since mybatis uses log4j to output log information by default, you should check the output SQL statement of the console. Create log4j under project src Properties file. Edited as follows:
# Global logging configuration log4j.rootLogger=ERROR, stdout # MyBatis logging configuration... log4j.logger.org.mybatis.example.BlogMapper=TRACE # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
Create package com itheima. po. Create a persistent class Customer under this package
package com.itheima.po; public class Customer { private Integer id; private String username; private String jobs; private String phone; @Override public String toString() { return "Customer{" + "id=" + id + ", username='" + username + '\'' + ", jobs='" + jobs + '\'' + ", phone='" + phone + '\'' + '}'; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getJobs() { return jobs; } public void setJobs(String jobs) { this.jobs = jobs; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
Under src directory, create com itheima. Mapper package, create the mapping file customermapper xml
<?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="com.itheima.mapper.CustomerMapper"> <select id="findCustomerById" parameterType="Integer" resultType="com.itheima.po.Customer"> select * from t_customer where id = #{id} </select> <select id="findCustomerByName" parameterType="String" resultType="com.itheima.po.Customer"> select * from t_customer where username like '%${value}%' </select> <insert id="addCustomer" parameterType="com.itheima.po.Customer"> insert into t_customer(username,jobs,phone) values(#{username},#{jobs},#{phone}) </insert> <update id="updateCustomer" parameterType="com.itheima.po.Customer"> update t_customer set username=#{username},jobs=#{jobs},phone=#{phone} where id=#{id} </update> <delete id="deleteCustomer" parameterType="Integer"> delete from t_customer where id=#{id} </delete> </mapper>
In the src directory, create the core file MyBatis config XML of MyBatis
<?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> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/> <property name="username" value="user"/> <property name="password" value="password"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/itheima/mapper/CustomerMapper.xml"/> </mappers> </configuration>
In the ssrc directory, create com itheima. Test package, under which the test class MybatisTest is created
package com.itheima.test; import com.itheima.po.Customer; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.junit.Test; public class MybatisTest { @Test public void findCustomerByIdTest() throws Exception{ String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); Customer customer = sqlSession.selectOne("com.itheima.mapper"+".CustomerMapper.findCustomerById",1); System.out.println(customer.toString()); sqlSession.close(); } /* *Simulate query of user information list according to user name */ @Test public void findCustomerByNameTest() throws Exception { //1. Read the configuration file String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); //2. Build SqlSessionfactory according to the configuration file SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //3. Create SqlSession through sqlSessionFactory SqlSession sqlSession = sqlSessionFactory.openSession(); //4.SqlSession executes the SQL defined in the mapping file and returns the mapping result List<Customer> customers = sqlSession.selectList("com.itheima.mapper" + ".CustomerMapper.findCustomerByName", "j"); for (Customer customer : customers) { System.out.println(customer); } //5. Close SqlSession sqlSession.close(); } /* *Add user */ @Test public void addCustomerTest () throws Exception{ //1. Read the configuration file String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); //2. Build SqlSessionfactory according to the configuration file SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //3. Create SqlSession through sqlSessionFactory SqlSession sqlSession = sqlSessionFactory.openSession(); //4. Customer customer = new Customer(); customer.setUsername("rose"); customer.setJobs("teacher"); customer.setPhone("1222737282"); int rows = sqlSession.insert("com.itheima.mapper"+".CustomerMapper.addCustomer",customer); if(rows > 0) { System.out.println("Insert operation succeeded!"); } else { System.out.println("Insert operation failed!!"); } sqlSession.commit(); sqlSession.close(); } /* *Update account */ @Test public void updateCustomerTest() throws Exception{ //1. Read the configuration file String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); //2. Build SqlSessionfactory according to the configuration file SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //3. Create SqlSession through sqlSessionFactory SqlSession sqlSession = sqlSessionFactory.openSession(); //4. Customer customer = new Customer(); customer.setId(4); customer.setUsername("joy"); customer.setJobs("programmer"); customer.setPhone("112222222222"); int rows = sqlSession.update("com.itheima.mapper"+".CustomerMapper.addCustomer",customer); if(rows > 0) { System.out.println("Update operation executed successfully!"); } else { System.out.println("Update operation failed!!"); } sqlSession.commit(); sqlSession.close(); } /* *Delete customer */ @Test public void deleteCustomerTest() throws IOException { //1. Read the configuration file String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); //2. Build SqlSessionfactory according to the configuration file SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //3. Create SqlSession through sqlSessionFactory SqlSession sqlSession = sqlSessionFactory.openSession(); //4. Delete sqlsession //4.1 delete SqlSession int rows = sqlSession.delete("com.itheima.mapper" + ".CustomerMapper.deleteCustomer", 10); if (rows > 0) { System.out.println("Delete operation succeeded!"); } else { System.out.println("Delete operation failed!!"); } //4.3 commit transactions sqlSession.commit(); //5. Close SqlSession sqlSession.close(); } } .CustomerMapper.deleteCustomer", 10); if (rows > 0) { System.out.println("Delete operation succeeded!"); } else { System.out.println("Delete operation failed!!"); } //4.3 commit transactions sqlSession.commit(); //5. Close SqlSession sqlSession.close(); } }