Mybatis review (including basic applications, Mapper dynamic proxy, multiple query conditions, dynamic SQL, relationship query, cache)

1. Basic application

1.1 Import related jar packages or Maven imports

Note that the version of MySQL needs to correspond to the jar package.
mysql-connector-java-8.0.17.jar corresponds to MySQL8.0 and above, and 5.7 corresponds to 5.7.
At the same time, 8.0.17 needs to pay attention to driver and serverTimezone

 jdbc.driver=com.mysql.cj.jdbc.Driver 
 ?serverTimezone=UTC

insert image description here

1.2 Define Entity Classes

@Data
public class Student {
    
    
	private Integer id;
	private String name;
	private int age;
	private double score;
	private String time;
}

1.3 Database

DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `age` int(3) DEFAULT NULL,
  `score` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

1.4 Define interface and mapping file

public interface IStudentDao {
    
    
	void insertStu(Student student);
}
<?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="test">
	<!-- parameterType属性可以省略 -->
	<insert id="insertStudent" parameterType="Student">
		insert into student(name,age,score,time) values(#{name}, #{age}, #{score},#{time,jdbcType=DATE})
	</insert>
</mapper>

1.5 Define the configuration file

<?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>
	<!-- 注册DB连接四要素属性文件 -->
	<properties resource="jdbc_mysql.properties"/>
	<!-- 定义类型别名 -->
	<typeAliases>
		<!-- <typeAlias type="com.rose.beans.Student" alias="Student"/> -->
		<!-- 将指定包中所有类的简单类名当作其别名 -->
		<package name="com.rose.beans"/>
	</typeAliases>
	
	<!-- 配置运行环境 -->
	<environments default="testEM">
		<environment id="testEM">
			<transactionManager type="JDBC"/>
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driver}"/>
				<property name="url" value="${jdbc.url}"/>
				<property name="username" value="${jdbc.user}"/>
				<property name="password" value="${jdbc.password}"/>
			</dataSource>
		</environment>
	</environments>
	
	<!-- 注册映射文件 -->
	<mappers>
		<mapper resource="com/rose/dao/mapper.xml"/>
	</mappers>
	
</configuration>

1.6 Define Dao's implementation class and test

public class StudentDaoImpl implements IStudentDao {
    
    

	private SqlSession sqlSession;

	@Override
	public void insertStu(Student student) {
    
    
		try {
    
    
			sqlSession = MyBatisUtils.getSqlSession();
			sqlSession.insert("insertStudent", student);
			sqlSession.commit();
		} finally {
    
    
			if(sqlSession != null) {
    
    
				sqlSession.close();
			}
		}
	}
}
public class MyTest {
    
    
	private IStudentDao dao;

	@Before
	public void before() {
    
    
		dao = new StudentDaoImpl();
	}
	
	@Test
	public void testInsert() {
    
    
		Student student = new Student("rose3", 23, 93.5);
		dao.insertStu(student);
	}
	
}

2. The difference between $ and #

# is a placeholder, and $ is a string splicing character.
String splicing is to directly splice the parameter value into the SQL statement in a hard-coded manner. String splicing will cause two problems: SQL injection and low execution efficiency caused by not using precompilation

3. Mapper dynamic proxy

In the previous example, a problem was discovered when implementing the Dao interface class: the implementation class of Dao did not do any substantive work. It only locates the SQL statement corresponding to the id in the mapping file mapper through the relevant API of SqlSession. Operations are done through Mapper's SQL.
So Mybatis can abandon Dao's implementation class and use dynamic proxy directly without writing Dao's implementation class.
Simply put, locate the mapping file by the interface name

<mapper namespace="com.rose.dao.IStudentDao">
</mapper>
	

4. Multiple query conditions

4.1 Encapsulate multiple parameters into a Map

List<Student> selectStudentByMap(Map<String,object> map);

4.2 Multiple parameters are accepted one by one

List<Student> selectStudentByConditions(String name,int age);

5. Dynamic SQL

Dynamic sql is used to solve the situation where the query is difficult or uncertain; during the running of the program, the query is performed according to the query conditions submitted by the user. The submitted query conditions are different, and the executed SQL statements are different. If you write sql for each case separately, the workload will be heavy. Dynamic sql can be used.
Common dynamic sql tags are

public interface IStudentDao {
    
    
	List<Student> selectStudentsByIf(Student student);
	List<Student> selectStudentsByWhere(Student student);
	List<Student> selectStudentsByChoose(Student student);
	List<Student> selectStudentsByForeach(int[] ids);
	List<Student> selectStudentsByForeach2(List<Integer> ids);
	List<Student> selectStudentsByForeach3(List<Student> ids);
	List<Student> selectStudentsBySqlFragment(List<Student> ids);
}
<mapper namespace="com.rose.dao.IStudentDao">
	
	<select id="selectStudentsByIf" resultType="Student">
		select id,name,age,score 
		from student 
		where 1 = 1
		<if test="name != null and name != ''">
			and name like '%' #{name} '%'
		</if>
		<if test="age > 0">
			and age > #{age}
		</if>
	</select>
	
	<select id="selectStudentsByWhere" resultType="Student">
		select id,name,age,score 
		from student 
		<where>
			<if test="name != null and name != ''">
				and name like '%' #{name} '%'
			</if>
			<if test="age > 0">
				and age > #{age}
			</if>
		</where>
	</select>
	
	<select id="selectStudentsByChoose" resultType="Student">
		select id,name,age,score 
		from student 
		<where>
			<choose>
				<when test="name != null and name !=''">
					and name like '%' #{name} '%'
				</when>
				<when test="age > 0">
					and age > #{age}
				</when>
				<otherwise>
					1 = 2
				</otherwise>
			</choose>
		</where>
	</select>
	
	<select id="selectStudentsByForeach" resultType="Student">
		<!-- select id,name,age,score from student where id in (1,3,5) -->
		select id,name,age,score 
		from student 
		<if test="array.length > 0">
			where id in 
			<foreach collection="array" item="myid" open="(" close=")" separator=",">
				#{myid}
			</foreach>
		</if>
	</select>
	
	<select id="selectStudentsByForeach2" resultType="Student">
		<!-- select id,name,age,score from student where id in (1,3,5) -->
		select id,name,age,score 
		from student 
		<if test="list.size > 0">
			where id in 
			<foreach collection="list" item="myid" open="(" close=")" separator=",">
				#{myid}
			</foreach>
		</if>
	</select>
	
	<select id="selectStudentsByForeach3" resultType="Student">
		<!-- select id,name,age,score from student where id in (1,3,5) -->
		select id,name,age,score 
		from student 
		<if test="list.size > 0">
			where id in 
			<foreach collection="list" item="stu" open="(" close=")" separator=",">
				#{stu.id}
			</foreach>
		</if>
	</select>
	
	<select id="selectStudentsBySqlFragment" resultType="Student">
		<!-- select id,name,age,score from student where id in (1,3,5) -->
		select <include refid="selectColumns"/>
		from student 
		<if test="list.size > 0">
			where id in 
			<foreach collection="list" item="stu" open="(" close=")" separator=",">
				#{stu.id}
			</foreach>
		</if>
	</select>
	
	<sql id="selectColumns">
		id,name,age,score 
	</sql>
	
</mapper>

6. Relationship query

6.1 One-to-many

One-to-many association query is worth querying one party, and at the same time query all the multi-party objects associated with it. The following is a one-to-many demonstration between Country and Minister.

public class Country {
    
    
	private Integer cid;
	private String cname;
	// 关联属性
	private Set<Minister> ministers;
}
public class Minister {
    
    
	private Integer mid;
	private String mname;
}

Use the resultMap collection to put multiple parties into the collection

<mapper namespace="com.rose.dao.ICountryDao">
	
	<resultMap type="Country" id="countryMapper">
		<id column="cid" property="cid"/>
		<result column="cname" property="cname"/>
		<collection property="ministers" ofType="Minister">
			<id column="mid" property="mid"/>
			<result column="mname" property="mname"/>
		</collection>
	</resultMap>
	
	<select id="selectCountryById" resultMap="countryMapper">
		select cid,cname,mid,mname
		from country,minister
		where countryId=cid and cid=#{xxx} 
	</select>
	
</mapper>

6.2 Many to one

public class Minister {
    
    
	private Integer mid;
	private String mname;
	// 关联属性
	private Country country;
}

use association

<mapper namespace="com.rose.dao.IMinisterDao">
	
	<resultMap type="Minister" id="ministerMapper">
		<id column="mid" property="mid"/>
		<result column="mname" property="mname"/>
		<association property="country" javaType="Country">
			<id column="cid" property="cid"/>
			<result column="cname" property="cname"/>
		</association>
	</resultMap>
	
	<select id="selectMinisterById" resultMap="ministerMapper">
		select mid,mname,cid,cname
		from minister, country
		where countryId=cid and mid=#{xxx}
	</select>
	
</mapper>

7. Cache

7.1 Level 1 cache

Mybatis level-1 query cache is essentially a local cache based on HashMap, and its scope is SqlSession. Execute the same sql query statement twice in the same SqlSession. After the first execution, the query result will be written into the cache, and the data will be directly obtained from the cache for the second time. not query the database.

When a sqlsession ends, the first-level query in the sqlsession does not exist anymore. The first-level cache of mybatis is turned on by default and cannot be turned off.

Add, delete, and modify operations, regardless of whether sqlSession.commit() is submitted, will clear the first-level query cache and make the query select from the DB again.

7.2 L2 cache

(1) The entity classes involved are required to implement the java.io.Serializable interface
(2) Add labels to the mapper map

<cache/>  

Guess you like

Origin blog.csdn.net/qq_21561833/article/details/124767454