sql mapping file - advanced mapping
2.1sql mapping file
1. Common formats
<?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="cn.smbms.dao.StudentMapper">
......
</mapper>
2. Benefits
- In interface-oriented programming, methods are defined in interfaces. The method of implementation is in xml.
3.mapper
- Which interface is specified by namespace
- The name of the interface is the same as the name of the xml and the method needs to use id to specify which method it is
4. Single condition query
- id
- parameterType, the type of the incoming value
- resultType result type
<!--单条件查询-->
<select id="getStudentListByName" parameterType="string" resultType="Student">
select *
from student
where name like concat('%', #{name}, '%')
</select>
test code
//模糊查询
@Test
public void testListVague() {
SqlSession sqlSession = null;
int count = 0;
try {
sqlSession = MyBatisUtil.createSqlSession();
List<Student> list = sqlSession.getMapper(StudentMapper.class).getStudentListByName("张");
System.out.println(list.toString());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
count = 0;
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
}
5. Multi-condition query
- Just change the sql statement
- The incoming parameter can be (id, name) can be a (map)
The following is the form of the map used
method
// 根据id和name精确查询
Student getStudentByIdAndName(Map map);
sql
- # get the value of the key
<!-- 多条件查询-->
<select id="getStudentByIdAndName" resultType="cn.smbms.pojo.Student" parameterType="map">
select *
from student
where name = #{name} and id=#{id}
</select>
yinsg
test code
sqlSession = MyBatisUtil.createSqlSession();
Map map=new LinkedHashMap();
map.put("id",2);
map.put("name","李四");
Student student = sqlSession.getMapper(StudentMapper.class). getStudentByIdAndName(map);
System.out.println(student.toString());
6. Customized result mapping buzzi
- In order to display the query results
- When the resultType is automatically mapped, if the names are inconsistent, you need to specify an alias
- resulteMap
The case connects table query to course and student
The following are the course and student tables
Resolving inconsistencies between the name to map and the name of the class'
- Assuming that the student class is called studentname, and the database is name, you need to do mapping
- Use resultMap to set the mapping
- result can only set some simple properties
<!-- 设置映射-->
<resultMap id="student" type="Student">
<result property="id" column="id"/>
<result property="student_name" column="name"/>
</resultMap>
<!-- 多条件查询-->
<select id="getStudentByIdAndName" resultMap="student" parameterType="map">
select *
from student
where name = #{name} and id=#{id}
</select>
7. Cancel automatic mapping
<resultMap id="student" type="Student">
<!-- <result property="id" column="id"/>-->
<result property="student_name" column="name"/>
</resultMap>
The result is an automatic mapping.
How to cancel? ? ? It is specified in the configuration file in myabtis. At this time, whether the query result is automatically mapped, or it will not be displayed if it is not set.
<settings>
<setting name="autoMappingBehavior" value="NONE"/>
</settings>
2.2 Add operation + transaction
The value returned by default is the number of rows of the affected result, int, without resultMap and Type
- id
- parameterType, the qualified name or alias of the data type to be added
<!-- 添加信息-->
<insert id="addStudent" parameterType="student" >
insert into student (name)
values(#{student_name} )
</insert>
Test code, using transaction
sqlSession = MyBatisUtil.createSqlSession();
Integer u = sqlSession.getMapper(StudentMapper.class).addStudent(new Student(null,"张三"));
//事务
sqlSession.commit();
- modify the code
<update id="updateStudent" parameterType="student" >
update student set name=
#{student_name} where id=#{id}
</update>
- test code
sqlSession = MyBatisUtil.createSqlSession();
Integer line = sqlSession.getMapper(StudentMapper.class).updateStudent(new Student(3,"张三"));
System.out.println("修改的用户的信息");
System.out.println(line.toString());
sqlSession.commit();
3. Pass in multiple parameters in the form of annotations
In fact, the function is to change the name of the key in the map
- @Param annotation, incoming parameters
- In some scenarios, the value of the input parameter is not very suitable for the type of object. It is necessary to specify the type that needs to be passed in to improve the readability of the code.
The code for the interface. Change the value of student_name to name
int updateStudentBiming(@Param("id") Integer id,@Param("name") String student_name);
- sql code. The value of name at this time is the name passed in @Param, changing the original student_name into name.
<!-- 采用传入参数的方式-->
<update id="updateStudentBiming" parameterType="student">
update student
set name=
#{name}
where id = #{id}
</update>
test code
sqlSession = MyBatisUtil.createSqlSession();
Integer line = sqlSession.getMapper(StudentMapper.class).updateStudentBiming(3,"张三嘻嘻嘻");
System.out.println("修改的用户的信息");
System.out.println(line.toString());
sqlSession.commit();
in the same way
2.3 Advanced result mapping (difficult)
2.3.1 resultMap configuration
- id, unique
- type, the result type of the mapping
- child node
- id, the identifier of the result set
- result, simple attribute
- association, complex type
- collection
<resultMap id="student" type="Student">
<result property="id" column="id"/>
<result property="student_name" column="name"/>
</resultMap>
2.3.2 Association of resultMap
Based on the relationship between student and id
public class Student {
private Integer id;
private String student_name;
private Card card;
}
interface
List<Student> getStudentAndCardList();
sql code
<resultMap id="studentlist" type="Student">
<result property="id" column="id"/>
<result property="student_name" column="name"/>
<!--association映射的复杂类型-->
<association property="card">
<result property="id" column="id"/>
<result property="cardNum" column="cardNum"/>
<result property="sid" column="sid"/>
</association>
</resultMap>
<!-- getStudentAndCardList-->
<select id="getStudentAndCardList" resultMap="studentlist">
select s.*,c.* from student s join card c on s.id=c.sid;
</select>
search result
2.3.3 collection of resultMap
It involves a one-to-many relationship
1. Query statement
<resultMap id="studentCourse" type="Student">
<result property="id" column="id"/>
<result property="student_name" column="name"/>
<collection property="courses" ofType="course" resultMap="courseList"/>
</resultMap>
<resultMap id="courseList" type="course">
<!--就是为了方便维护-->
<id property="sid" column="sid"/>
<result property="name" column="cname"/>
<result property="id" column="cid"/>
</resultMap>
<!-- 返回一个学生选的所有课程-->
<select id="getStudentAndCourseList" resultMap="studentCourse" parameterType="int">
select s.*,c.id as cid ,c.name as cname ,c.sid as sid from student s join course c on s.id = c.sid where s.id=#{id}
</select>
Below is the corrected code
<resultMap id="studentCourse" type="Student">
<result property="id" column="id"/>
<result property="student_name" column="name"/>
<collection property="courses" ofType="course" resultMap="courseList"/>
</resultMap>
<resultMap id="courseList" type="course">
<!--就是为了方便维护-->
<id property="cid" column="cid"/>
<result property="cname" column="cname"/>
<result property="csid" column="sid"/>
</resultMap>
<!-- 返回一个学生选的所有课程-->
<select id="getStudentAndCourseList" resultMap="studentCourse" parameterType="int">
select s.*,c.id as cid ,c.name as cname ,c.sid as sid from student s join course c on s.id = c.sid where s.id=#{id}
</select>
Note: There may be only one reason for the result data queried in a relatively error-prone place, which is the name conflict between the two classes to be queried.
- The solution is to set an attribute that does not have the same name
- Mybatis Collection query collection only appears one data solution address
2.3.4 Automatic mapping level of resultMap and MyBtais cache
- How to configure the level of automatic mapping
- Learn how to set up caching
three ways
- FULL, whether it is nested or not, it will automatically match
- NONE defaults to no matching
- PARTIAL, the default method, if there is nesting, no default matching will be performed
<settings>
<setting name="autoMappingBehavior" value="NONE"/>
</settings>
2.3.5 mybatis cache
There is a level 1 and level 2 cache
1. Level 1 cache
- Comes with a HASHMAP-based cache. The scope is session, and when the session is flushed or closed, it will be gone.
2. Second level cache
- Based on the global cache, those that are not in the session can be shared by all sqlSessions. If it is enabled, the configuration file of mybatis must be set. That is, mybatis-config.xml is fine.
First configure the secondary cache in the global file, that is, open the cache
<setting name="cacheEnabled" value="true"/>
Set the configuration of mapper's cache
<!-- 设置全局的缓存-->
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
When querying, you can use the cache
- Just set a UserCache to true
useCache="true"
Note that this is simply a specific need for other cache servers to provide cache services.