MyBatis学习(五)

MyBatis小技巧

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.xiaoguan.mapper;

import com.xiaoguan.pojo.Car;

import java.util.List;

public interface CarMapper {
//增
int insert(Car car);
//删
int deleteById(Long id);
//改
int update(Car car);
//查
Car selectById(Long id);
List<Car> selectAll();
}

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
package com.xiaoguan.pojo;

import java.util.Objects;

/**
* 封装汽车相关信息的普通java类
*/
public class Car {
//建议使用包装类
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
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?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.xiaoguan.mapper.CarMapper">
<insert id="insert">
insert into t_car values (null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType});
</insert>
<delete id="deleteById">
delete from t_car where id=#{id};
</delete>
<update id="update">
update t_car set car_num=#{carNum},brand=#{brand},guide_price=#{guidePrice},produce_time=#{produceTime},car_type=#{carType}
where id=#{id};
</update>
<select id="selectById" resultType="com.xiaoguan.pojo.Car">
select
id,
car_num as carNum,
brand,
guide_price as guidePrice,
produce_time as produceTime,
car_type as carType
from
t_car
where
id=#{id};
</select>
<select id="selectAll" resultType="com.xiaoguan.pojo.Car">
select
id,
car_num as carNum,
brand,
guide_price as guidePrice,
produce_time as produceTime,
car_type as carType
from
t_car
</select>
</mapper>
1
2
3
4
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=68963120g
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
<?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"/>
<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>
<mapper resource="CarMapper.xml"/>
</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
package com.xiaoguan.test;

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

import java.util.List;

public class CarMapperTest {
@Test
public void testInsert(){
SqlSession sqlSession = SqlSessionUtils.openSession();
CarMapper mapper = sqlSession.getMapper(CarMapper.class);
Car car = new Car(null, "6813", "奔驰", 60.0, "2023-07-16", "新能源");
int count = mapper.insert(car);
System.out.println(count);
sqlSession.commit();
sqlSession.close();

}
@Test
public void testDelete(){
SqlSession sqlSession = SqlSessionUtils.openSession();
CarMapper mapper = sqlSession.getMapper(CarMapper.class);
mapper.deleteById(2L);
sqlSession.commit();
sqlSession.close();
}
@Test
public void testUpdate(){
SqlSession sqlSession = SqlSessionUtils.openSession();
CarMapper mapper = sqlSession.getMapper(CarMapper.class);
Car car = new Car(1L, "6813", "特斯拉", 60.0, "2023-07-16", "新能源");
int count = mapper.update(car);
System.out.println(count);
sqlSession.commit();
sqlSession.close();
}
@Test
public void testSelectOne(){
SqlSession sqlSession = SqlSessionUtils.openSession();
CarMapper mapper = sqlSession.getMapper(CarMapper.class);
Car car = mapper.selectById(1L);
System.out.println(car);
sqlSession.close();
}
@Test
public void testSelectAll(){
SqlSession sqlSession = SqlSessionUtils.openSession();
CarMapper mapper = sqlSession.getMapper(CarMapper.class);
List<Car> cars = mapper.selectAll();
for (Car car:cars) {
System.out.println(car);
}
}
}

MyBatis参数处理

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

import com.xiaoguan.pojo.Car;

import java.util.List;

public interface CarMapper {
//插入car并且使用生成主键值
int insertCarUseGeneratedKeys(Car car);
List<Car> selectByBrandLike(String brand);
int deleteBatch(String ids);
//根据汽车类型获取汽车信息
List<Car> selectByCarType(String carType);
//升序或降序查询所有的信息
List<Car> selectAllbyAscOrDesc(String ascOrDesc);
}

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

import com.xiaoguan.pojo.Log;

import java.util.List;

public interface LogMapper {
List<Log> selectAllByTable(String date);
}

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
package com.xiaoguan.pojo;

import java.util.Objects;

/**
* 封装汽车相关信息的普通java类
*/
public class Car {
//建议使用包装类
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
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 Log {
private Long id;
private String log;
private String time;

@Override
public String toString() {
return "Log{" +
"id=" + id +
", log='" + log + '\'' +
", time='" + time + '\'' +
'}';
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Log log1 = (Log) o;
return Objects.equals(getId(), log1.getId()) && Objects.equals(getLog(), log1.getLog()) && Objects.equals(getTime(), log1.getTime());
}

@Override
public int hashCode() {
return Objects.hash(getId(), getLog(), getTime());
}

public Long getId() {
return id;
}

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

public String getLog() {
return log;
}

public void setLog(String log) {
this.log = log;
}

public String getTime() {
return time;
}

public void setTime(String time) {
this.time = time;
}

public Log(Long id, String log, String time) {
this.id = id;
this.log = log;
this.time = time;
}

public Log() {
}
}

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
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
<?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">
<!--什么时候要用${}?
1.表明升序或者降序时
2.向Sql语句中需要拼接表名时,比如查日志文件
3.批量删除
4.模糊查询
-->
<!--namespace没有别名机制-->
<mapper namespace="com.xiaoguan.mapper.CarMapper">
<insert id="insertCarUseGeneratedKeys" useGeneratedKeys="true" keyProperty="id">
insert into t_car values(null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType});
</insert>
<select id="selectByBrandLike" resultType="car">
select
id,
car_num as carNum,
brand,
guide_price as guidePrice,
produce_time as produceTime,
car_type as carType
from
t_car
where
<!-- 下面四种都可以
# brand like '%${brand}%';
# brand like concat('%',#{brand},'%');
# brand like concat('%','${brand}','%');-->
brand like "%"#{brand}"%";

</select>
<delete id="deleteBatch">
delete from t_car where id in(${ids});
</delete>
<select id="selectAllbyAscOrDesc" resultType="car">
select
id,
car_num as carNum,
brand,
guide_price as guidePrice,
produce_time as produceTime,
car_type as carType
from
t_car
order by
produce_time ${ascOrDesc};
</select>
<select id="selectByCarType" resultType="car">
select
id,
car_num as carNum,
brand,
guide_price as guidePrice,
produce_time as produceTime,
car_type as carType
from
t_car
where
car_type=${carType};
</select>
</mapper>
1
2
3
4
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=68963120g
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
<?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">
<!--什么时候要用${}?
1.表明升序或者降序时
2.向Sql语句中拼接表名时
-->
<mapper namespace="com.xiaoguan.mapper.LogMapper">
<select id="selectAllByTable" resultType="log">
select * from t_log_${date};
</select>

</mapper>
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
<?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>
<!--省略alias后别名就是简写,比如下面的就是Car-->
<!-- <typeAlias type="com.xiaoguan.pojo.Car" alias="aaa"/>-->
<!-- <typeAlias type="com.xiaoguan.pojo.Log" />-->
<!--也可以指定包名-->
<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>
<!--resourve还可以换成class,里面写带有包名的全限定接口名,必须保证mapper文件和它的接口在同一个目录下
用class时可以用package标签来指定所有的在相同的目录-->
<mapper resource="CarMapper.xml"/>
<mapper resource="LogMapper.xml"/>
</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
package com.xiaoguan.test;

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

import java.util.List;

public class CarMapperTest {
@Test
public void insertCarUseGeneratedKeys(){
SqlSession sqlSession = SqlSessionUtils.openSession();
CarMapper mapper = sqlSession.getMapper(CarMapper.class);
Car car = new Car(null, "9999", "凯美瑞", 888.0, "2023-07-17", "燃油车");
mapper.insertCarUseGeneratedKeys(car);
System.out.println(car);
sqlSession.commit();
sqlSession.close();
}
@Test
public void testselectByBrandLike(){
SqlSession sqlSession = SqlSessionUtils.openSession();
CarMapper mapper = sqlSession.getMapper(CarMapper.class);
List<Car> cars=mapper.selectByBrandLike("奔驰");
cars.forEach(car -> System.out.println(car));
sqlSession.close();

}
@Test
public void testDeleteBatch(){
SqlSession sqlSession = SqlSessionUtils.openSession();
CarMapper mapper = sqlSession.getMapper(CarMapper.class);
int count=mapper.deleteBatch("1,28");
System.out.println(count);
sqlSession.commit();
sqlSession.close();
}
@Test
public void testSelectDescOrAsc(){
//#{}用的是PrepareStatement,${}用的是Statement,存在sql注入风险
SqlSession sqlSession = SqlSessionUtils.openSession();
CarMapper mapper = sqlSession.getMapper(CarMapper.class);
List<Car> cars=mapper.selectAllbyAscOrDesc("desc");
cars.forEach(car -> System.out.println(car));
sqlSession.close();
}
@Test
public void testSelectByCarType(){
//#{}用的是PrepareStatement,${}用的是Statement,存在sql注入风险
SqlSession sqlSession = SqlSessionUtils.openSession();
CarMapper mapper = sqlSession.getMapper(CarMapper.class);
List<Car> cars=mapper.selectByCarType("'新能源'");
cars.forEach(car -> System.out.println(car));
sqlSession.close();
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.xiaoguan.test;

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

import java.util.List;

public class LogMapperTest {
@Test
public void testSelectLogByDate(){
SqlSession sqlSession = SqlSessionUtils.openSession();
LogMapper mapper = sqlSession.getMapper(LogMapper.class);
List<Log> logs = mapper.selectAllByTable("20220901");
logs.forEach(log -> System.out.println(log));
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
package com.xiaoguan.mybatis.mapper;

import com.xiaoguan.mybatis.pojo.Student;
import org.apache.ibatis.annotations.Param;

import java.util.Date;
import java.util.List;
import java.util.Map;


public interface StudentsMapper {
List<Student> selectByNameAndSex2(@Param("name") String name, @Param("sex") Character sex);
List<Student> selectByNameAndSex(String name,Character sex);
int insertStudentBypojo(Student student);
int insertStudentByMap(Map<String,Object > map);
List<Student> selectById(Long id);
List<Student> selectByName(String name);
List<Student> selectByBirth(Date birth);
List<Student> selectByHigtht(Double higtht);
List<Student> selectByAge(Integer age);
List<Student> selectBySex(Character sex);
}

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
package com.xiaoguan.mybatis.pojo;

import java.util.Date;
import java.util.Objects;

public class Student {
private Long id;
private String name;
private Integer age;
private Double height;
private Date birth;
private Character sex;

public Student() {
}

public Student(Long id, String name, Integer age, Double height, Date birth, Character sex) {
this.id = id;
this.name = name;
this.age = age;
this.height = height;
this.birth = birth;
this.sex = sex;
}

public Long getId() {
return id;
}

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

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public Double getHeight() {
return height;
}

public void setHeight(Double height) {
this.height = height;
}

public Date getBirth() {
return birth;
}

public void setBirth(Date birth) {
this.birth = birth;
}

public Character getSex() {
return sex;
}

public void setSex(Character sex) {
this.sex = sex;
}

@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(getId(), student.getId()) && Objects.equals(getName(), student.getName()) && Objects.equals(getAge(), student.getAge()) && Objects.equals(getHeight(), student.getHeight()) && Objects.equals(getBirth(), student.getBirth()) && Objects.equals(getSex(), student.getSex());
}

@Override
public int hashCode() {
return Objects.hash(getId(), getName(), getAge(), getHeight(), getBirth(), getSex());
}

@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", height=" + height +
", birth=" + birth +
", sex=" + sex +
'}';
}
}

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.mybatis.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
<?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"/>
<typeAliases>
<package name="com.xiaoguan.mybatis.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.mybatis.mapper"/>
</mappers>
</configuration>