MyBatis学习(七)

MyBatis映射

1
2
3
4
5
6
7
8
9
10
package com.xiaoguan.mapper;

import com.xiaoguan.pojo.Class;

public interface ClassMapper {
Class selectByIdStep2(Integer cid);
Class selectByCollection(Integer cid);
Class selectByStep1(Integer cid);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.xiaoguan.mapper;

import com.xiaoguan.pojo.Student;

import java.util.List;

public interface StudentMapper {
Student selectByIdStep1(Integer id);
Student selectByIdAssociation(Integer id);
Student selectById(Integer id);
List<Student> selectByCidStep2(Integer id);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.xiaoguan.pojo;

import java.util.List;
import java.util.Objects;

public class Class {
private Integer cid;
private String cname;
private List<Student> stus;

@Override
public String toString() {
return "Class{" +
"cid=" + cid +
", cname='" + cname + '\'' +
", stus=" + stus +
'}';
}

public List<Student> getStus() {
return stus;
}

public void setStus(List<Student> stus) {
this.stus = stus;
}

public Class() {
}

public Class(Integer cid, String cname) {
this.cid = cid;
this.cname = cname;
}

public Integer getCid() {
return cid;
}

public void setCid(Integer cid) {
this.cid = cid;
}

public String getCname() {
return cname;
}

public void setCname(String cname) {
this.cname = cname;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Class aClass = (Class) o;
return Objects.equals(getCid(), aClass.getCid()) && Objects.equals(getCname(), aClass.getCname());
}

@Override
public int hashCode() {
return Objects.hash(getCid(), getCname());
}

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.xiaoguan.pojo;

import java.util.Objects;

public class Student {
private Integer sid;
private String sname;
private Class clazz;

@Override
public String toString() {
return "Student{" +
"sid=" + sid +
", sname='" + sname + '\'' +
", clazz=" + clazz +
'}';
}

public Class getClazz() {
return clazz;
}

public void setClazz(Class clazz) {
this.clazz = clazz;
}

public Student() {
}

public Student(Integer sid, String sname) {
this.sid = sid;
this.sname = sname;
}

public Integer getSid() {
return sid;
}

public void setSid(Integer sid) {
this.sid = sid;
}

public String getSname() {
return sname;
}

public void setSname(String sname) {
this.sname = sname;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return Objects.equals(getSid(), student.getSid()) && Objects.equals(getSname(), student.getSname());
}

@Override
public int hashCode() {
return Objects.hash(getSid(), getSname());
}

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.xiaoguan.utils;

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;

/**
* MyBatis工具类
*/
public class SqlSessionUtils {
private static SqlSessionFactory sqlSessionFactory;
private SqlSessionUtils() {}
static {
try {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
} catch (IOException e) {
e.printStackTrace();
}
}
private static ThreadLocal<SqlSession> local=new ThreadLocal<>();
/**
* 获取会话对象
* @return 会话对象
*/
public static SqlSession openSession(){
SqlSession sqlSession = local.get();
if (sqlSession==null) {
sqlSession=sqlSessionFactory.openSession();
local.set(sqlSession);
}
return sqlSession;

}

/**
* 关闭sqlSession对象
* @param sqlSession
*/
public static void close(SqlSession sqlSession){
if (sqlSession != null) {
sqlSession.close();
//移除sqlSession对象和当前线程绑定关系
local.remove();
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="UTF-8"?>

<configuration debug="false">
<!-- 控制台输出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!-- 按照每天生成日志文件 -->
<!--mybatis log configure-->
<logger name="com.apache.ibatis" level="TRACE"/>
<logger name="java.sql.Connection" level="DEBUG"/>
<logger name="java.sql.Statement" level="DEBUG"/>
<logger name="java.sql.PreparedStatement" level="DEBUG"/>

<!-- 日志输出级别,logback日志级别包括五个:TRACE < DEBUG < INFO < WARN < ERROR -->
<root level="DEBUG">
<appender-ref ref="STDOUT"/>
<appender-ref ref="FILE"/>
</root>

</configuration>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?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>
<properties resource="jdbc.properties"/>
<settings>
<!--开启驼峰映射-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="com.xiaoguan.pojo"/>
</typeAliases>
<environments default="mybatis">
<environment id="mybatis">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.xiaoguan.mapper"/>
</mappers>
</configuration>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.xiaoguan.test;

import com.xiaoguan.mapper.ClassMapper;
import com.xiaoguan.pojo.Class;
import com.xiaoguan.utils.SqlSessionUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

public class ClassMapperTest {
@Test
public void testSelectByCollection(){
SqlSession sqlSession = SqlSessionUtils.openSession();
ClassMapper mapper = sqlSession.getMapper(ClassMapper.class);
Class clazz = mapper.selectByCollection(1000);
System.out.println(clazz);
sqlSession.close();
}
@Test
public void testSelectByStep1() {
SqlSession sqlSession = SqlSessionUtils.openSession();
ClassMapper mapper = sqlSession.getMapper(ClassMapper.class);
Class clazz = mapper.selectByStep1(1001);
System.out.println(clazz);
sqlSession.close();

}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.xiaoguan.test;

import com.xiaoguan.mapper.StudentMapper;
import com.xiaoguan.pojo.Student;
import com.xiaoguan.utils.SqlSessionUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.lang.annotation.Repeatable;

public class StudentMapperTest {
@Test
public void testSelectByIdStep1(){
SqlSession sqlSession = SqlSessionUtils.openSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
Student student = mapper.selectByIdStep1(1);
System.out.println(student.getSname());
sqlSession.close();
}
@Test
public void testSelectByIdAssociation(){
SqlSession sqlSession = SqlSessionUtils.openSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
Student student = mapper.selectByIdAssociation(1);
System.out.println(student);
sqlSession.close();
}
@Test
public void testSelectById(){
SqlSession sqlSession = SqlSessionUtils.openSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
Student student = mapper.selectById(1);
System.out.println(student);
sqlSession.close();
}

}

MyBatis缓存

1
2
3
4
5
6
7
8
9
10
11
12
package com.xiaoguan.mapper;


import com.xiaoguan.pojo.Car;

public interface CarMapper {
//测试二级缓存
Car selectById3(Long id);
Car selectById(Long id);

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package com.xiaoguan.pojo;

import java.io.Serializable;
import java.util.Objects;

/**
* 封装汽车相关信息的普通java类
*/
public class Car implements Serializable {
//建议使用包装类
private Long id;
private String carNum;
private String brand;
private Double guidePrice;
private String produceTime;
private String carType;

public Car() {
}

public Car(Long id, String carNum, String brand, Double guidePrice, String produceTime, String carType) {
this.id = id;
this.carNum = carNum;
this.brand = brand;
this.guidePrice = guidePrice;
this.produceTime = produceTime;
this.carType = carType;
}

@Override
public String toString() {
return "Car{" +
"id=" + id +
", carNum='" + carNum + '\'' +
", brand='" + brand + '\'' +
", guidePrice=" + guidePrice +
", produceTime='" + produceTime + '\'' +
", carType='" + carType + '\'' +
'}';
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Car car = (Car) o;
return Objects.equals(getId(), car.getId()) && Objects.equals(getCarNum(), car.getCarNum()) && Objects.equals(getBrand(), car.getBrand()) && Objects.equals(getGuidePrice(), car.getGuidePrice()) && Objects.equals(getProduceTime(), car.getProduceTime()) && Objects.equals(getCarType(), car.getCarType());
}

@Override
public int hashCode() {
return Objects.hash(getId(), getCarNum(), getBrand(), getGuidePrice(), getProduceTime(), getCarType());
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getCarNum() {
return carNum;
}

public void setCarNum(String carNum) {
this.carNum = carNum;
}

public String getBrand() {
return brand;
}

public void setBrand(String brand) {
this.brand = brand;
}

public Double getGuidePrice() {
return guidePrice;
}

public void setGuidePrice(Double guidePrice) {
this.guidePrice = guidePrice;
}

public String getProduceTime() {
return produceTime;
}

public void setProduceTime(String produceTime) {
this.produceTime = produceTime;
}

public String getCarType() {
return carType;
}

public void setCarType(String carType) {
this.carType = carType;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.xiaoguan.utils;

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;

/**
* MyBatis工具类
*/
public class SqlSessionUtils {
private static SqlSessionFactory sqlSessionFactory;
private SqlSessionUtils() {}
static {
try {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
} catch (IOException e) {
e.printStackTrace();
}
}
private static ThreadLocal<SqlSession> local=new ThreadLocal<>();
/**
* 获取会话对象
* @return 会话对象
*/
public static SqlSession openSession(){
SqlSession sqlSession = local.get();
if (sqlSession==null) {
sqlSession=sqlSessionFactory.openSession();
local.set(sqlSession);
}
return sqlSession;

}

/**
* 关闭sqlSession对象
* @param sqlSession
*/
public static void close(SqlSession sqlSession){
if (sqlSession != null) {
sqlSession.close();
//移除sqlSession对象和当前线程绑定关系
local.remove();
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<!--磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存-->
<diskStore path="e:/ehcache"/>

<!--defaultCache:默认的管理策略-->
<!--eternal:设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断-->
<!--maxElementsInMemory:在内存中缓存的element的最大数目-->
<!--overflowToDisk:如果内存中数据超过内存限制,是否要缓存到磁盘上-->
<!--diskPersistent:是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false-->
<!--timeToIdleSeconds:对象空闲时间(单位:秒),指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问-->
<!--timeToLiveSeconds:对象存活时间(单位:秒),指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问-->
<!--memoryStoreEvictionPolicy:缓存的3 种清空策略-->
<!--FIFO:first in first out (先进先出)-->
<!--LFU:Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存-->
<!--LRU:Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存-->
<defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>

</ehcache>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="UTF-8"?>

<configuration debug="false">
<!-- 控制台输出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!-- 按照每天生成日志文件 -->
<!--mybatis log configure-->
<logger name="com.apache.ibatis" level="TRACE"/>
<logger name="java.sql.Connection" level="DEBUG"/>
<logger name="java.sql.Statement" level="DEBUG"/>
<logger name="java.sql.PreparedStatement" level="DEBUG"/>

<!-- 日志输出级别,logback日志级别包括五个:TRACE < DEBUG < INFO < WARN < ERROR -->
<root level="DEBUG">
<appender-ref ref="STDOUT"/>
<appender-ref ref="FILE"/>
</root>

</configuration>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?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>
<properties resource="jdbc.properties"/>
<settings>
<!--开启驼峰映射-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="com.xiaoguan.pojo"/>
</typeAliases>
<environments default="mybatis">
<environment id="mybatis">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.xiaoguan.mapper"/>
</mappers>
</configuration>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.xiaoguan.test;

import com.xiaoguan.mapper.CarMapper;
import com.xiaoguan.pojo.Car;
import com.xiaoguan.utils.SqlSessionUtils;
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 org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
//文档rs4n
public class CarTest {
//要用二级缓存pojo类必须实现序列化接口
@Test
public void testSelectById2() throws IOException {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
CarMapper mapper = sqlSession.getMapper(CarMapper.class);
Car car = mapper.selectById(34L);
System.out.println(car);
SqlSession sqlSession1 = sqlSessionFactory.openSession();
CarMapper mapper1 = sqlSession1.getMapper(CarMapper.class);
Car car1 = mapper1.selectById(34L);
System.out.println(car1);
sqlSession.close();
sqlSession1.close();
}
@Test
public void testSelectById(){
SqlSession sqlSession = SqlSessionUtils.openSession();
CarMapper mapper = sqlSession.getMapper(CarMapper.class);
Car car = mapper.selectById(34L);
System.out.println(car);
//执行sqlSession的clearCache方法可以让sqlSession的一级缓存清空或者执行了其他修改表的语句会自动清空
sqlSession.clearCache();
Car car1 = mapper.selectById(34L);
System.out.println(car1);
sqlSession.close();
}
@Test
public void testcomSelectById3() throws IOException {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession1 = sqlSessionFactory.openSession();
SqlSession sqlSession2 = sqlSessionFactory.openSession();
CarMapper mapper1 = sqlSession1.getMapper(CarMapper.class);
CarMapper mapper2 = sqlSession2.getMapper(CarMapper.class);
Car car1=mapper1.selectById3(34L);
System.out.println(car1);
sqlSession1.close();
Car car2=mapper2.selectById3(34L);
System.out.println(car2);
sqlSession2.close();
}

}