1. Introduction to Mybatis
Mybatis is an excellent persistence framework, which encapsulates the process of jdbc operating database, so that we only need to pay attention to the SQL itself in the development process, and do not need to spend a lot of energy to deal with the complicated jdbc such as registration driver, connection creation, statement creation, manual parameter setting, result set retrieval, etc. Procedure code.
When using Mybatis, we configure various statements (statement, preparedStatement, CallableStatement) to be executed by xml or annotation, and map the final sql statements to the java objects and sql in the state. Finally, the mybatis framework executes sql and maps the results to java objects. And return.
2.Mybatis Architecture
1. mybatis configuration
SqlMapConfig.xml, as the global configuration file of mybatis, configures the running environment of mybatis and other information.
A mapper.xml file, namely sql mapping file, is configured with sql statements to operate the database. This file needs to be loaded in SqlMapConfig.xml.
2. Constructing SqlSession Factory by configuring information such as mybatis environment
3. Creating sqlSession by session factory is a session. Operating database needs to be done through sqlSession.
4. At the bottom of mybatis, the Executor interface operation database is customized. Executor interface has two implementations, one is the basic executor and the other is the cache executor.
5. Mapped Statement is also an underlying encapsulation object of mybatis, which packages mybatis configuration information and sql mapping information. A sql in the mapper.xml file corresponds to a Mapped Statement object. The id of sql is the id of Mapped State.
6. Mapped Statement defines input parameters of SQL execution, including HashMap, basic type and pojo. Executor maps input java objects to SQL through Mapped Statement before executing sql. The input parameter mapping is to set parameters of preparedStatement in jdbc programming.
7. Mapped Statement defines the output result of sql execution, including HashMap, basic type, pojo. Executor maps the output result to java object after executing sql through Mapped Statement. The output result mapping process is equivalent to the parsing process of the result in jdbc programming.
3. Introduction to Mybatis (five steps)
1) Importing jar packages
- I used to create a web project first, then write the entity class Person and create the database table person;
- Create projects and import jar packages: mybatis-3.2.7.jar and mysql-connector-java-8.0.16.jar build path to create bottles;
2) Write master configuration file (database connection, configuration transaction, loading mapping file) _SqlMapConfig.xml
- Create the configuration file SqlMapConfig.xml path to create directly under src.
1 <! - XML header block (deleted when replicating, because header code has to be set to the top) --> 2 3 <?xml version="1.0" encoding="UTF-8" ?> 4 <!DOCTYPE configuration 5 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 6 "http://mybatis.org/dtd/mybatis-3-config.dtd">
1 <configuration> 2 3 <!-- and spring After integration environments Configuration will be abolished --> 4 <environments default="development"> 5 <!-- Label the current label --> 6 <environment id="development"> 7 <!-- Use jdbc Transaction Manager --> 8 <transactionManager type="JDBC" /> 9 <!-- Database connection pool --> 10 <dataSource type="POOLED"> 11 <property name="driver" value="com.mysql.cj.jdbc.Driver" /> 12 <property name="url" 13 value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC" /> 14 <property name="username" value="root" /> 15 <property name="password" value="root" /> 16 </dataSource> 17 </environment> 18 </environments> 19 20 <mappers> 21 <mapper resource="sqlmap/User.xml"/> 22 </mappers> 23 </configuration>
3) Building an interface (calling CRUD method) __PersonMapper.java
1 /** 2 * 3. Building interfaces to invoke CRUD methods 3 * @author Administrator 4 * 5 */ 6 public interface PersonMapper { 7 public int savePerson(Person person); 8 9 public List<Person> selectPersons(); 10 11 public void updatePersons(Person person); 12 13 public void deletePersons(int i); 14 15 public List<Person> namePersons(@Param("name") String string); 16 17 public Person getOneByInfo(@Param("x") int i,@Param("y") String string); 18 19 public List<Person> getPersonAndCar(); 20 21 }
4) Constructing an XML file corresponding to a mapper interface under the same package _PersonMapper.xml
1 <!-- xml Headers can be referenced in official documents --> 2 3 <?xml version="1.0" encoding="UTF-8" ?> 4 <!DOCTYPE mapper 5 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 6 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
>> Increase person
1 <!-- 4. The same name of the interface xml1 file Used for writing sql1 instructions--> 2 <mapper namespace="com.muyan.mapper.PersonMapper"> 3 4 <!-- Increase the number of people --> 5 <insert id="savePerson" parameterType="com.muyan.bean.Person"> 6 <selectKey keyProperty="pid" keyColumn="pid" resultType="Integer" order="AFTER"> 7 SELECT LAST_INSERT_ID() 8 </selectKey> 9 insert into person(name,sal,comm,deptno) value(#{name},#{sal},#{comm},#{deptno}) 10 </insert> 11 12 </mapper>
>> Query the person list
1 <select id="selectPersons" resultType="com.muyan.bean.Person"> 2 select pid,name,sal,comm,deptno from person 3 </select>
>> Modify person
1 <update id="updatePersons" parameterType="com.muyan.bean.Person" > 2 update person 3 set name=#{name},sal=#{sal},comm=#{comm},deptno=#{deptno} where pid=#{pid} 4 </update>
>> Delete person
1 <delete id="deletePersons" parameterType="int"> 2 delete from person where pid=#{pid} 3 </delete>
>> multi-condition person search
1 <select id="getOneByInfo" resultType="com.muyan.bean.Person"> 2 select pid,name,sal,comm,deptno from person where sal=#{x} and name=#{y} 3 </select>
5) Read configuration file operation database _MybatisTest.java
>> Increase person
1 /** 2 * 5. Read configuration files and operate databases 3 * @author Seventy-five azure blue 4 */ 5 public class MybatisTest { 6 /** 7 * Increase the number of people 8 * @throws Exception 9 */ 10 @Test 11 public void savePerson() throws Exception { 12 //adopt Mybatis Tool class read configuration,And build an input stream 13 InputStream stream = Resources.getResourceAsStream("SqlMapConfig.xml"); 14 //Create by input stream session factory 15 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(stream); 16 //factory openSession 17 SqlSession sqlSession = factory.openSession(); 18 //adopt session Get the interface object(reflex) 19 PersonMapper mapper = sqlSession.getMapper(PersonMapper.class); 20 21 Person person = new Person(); 22 person.setName("Big Purple"); 23 person.setSal(1.0); 24 person.setComm(2.0); 25 person.setDeptno(30); 26 //Acquisition method 27 int i = mapper.savePerson(person); 28 System.out.println(i);//Number of influencing items 29 System.out.println(person.getPid());//Display the added id 30 //Submission 31 sqlSession.commit(); 32 //Shut off flow 33 sqlSession.close(); 34 } 35 }
>> Query person
1 List<Person> list = mapper.selectPersons(); 2 for(Person p:list) { 3 System.out.println(p); 4 }
>> Modify person
1 Person person = new Person(); 2 person.setPid(12); 3 person.setName("Xiao Bai"); 4 person.setSal(1.0); 5 person.setComm(2.0); 6 person.setDeptno(30); 7 8 mapper.updatePersons(person);
>> Delete person
1 mapper.deletePersons(9);
>> Multi-condition Query person
1 Person newPerson = mapper.getOneByInfo(1,"Big black"); 2 System.out.println(newPerson);