33.Spring和MyBatis集成(没有mybatis.cfg.xml配置文件)

 

工程目录结构:

项目依赖包:

Vo: User

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
package com.course.vo;

import java.util.Date;

public class User {
private Integer id;

private String name;

private Integer age;

private String address;

private Date hireDate;

public User() {
super();
}

public User(String name, Integer age, String address, Date hireDate) {
super();
this.name = name;
this.age = age;
this.address = address;
this.hireDate = hireDate;
}

public User(Integer id, String name, Integer age, String address, Date hireDate) {
super();
this.id = id;
this.name = name;
this.age = age;
this.address = address;
this.hireDate = hireDate;
}

public Integer getId() {
return id;
}

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

public String getName() {
return name;
}

public void setName(String name) {
this.name = name == null ? null : name.trim();
}

public Integer getAge() {
return age;
}

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

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address == null ? null : address.trim();
}

public Date getHireDate() {
return hireDate;
}

public void setHireDate(Date hireDate) {
this.hireDate = hireDate;
}

@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + ", hireDate=" + hireDate
+ "]";
}
}

Dao: UserMapper.java

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

import java.util.List;

import com.course.vo.User;

public interface UserMapper {
int deleteByPrimaryKey(Integer id);

int insert(User record);

int insertSelective(User record);

User selectByPrimaryKey(Integer id);

List<User> getAllUser();

int updateByPrimaryKeySelective(User record);

int updateByPrimaryKey(User record);
}

UserMapper.xml

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
<?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.course.dao.UserMapper">
<resultMap id="BaseResultMap" type="com.course.vo.User">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="age" jdbcType="INTEGER" property="age" />
<result column="address" jdbcType="VARCHAR" property="address" />
<result column="hire_date" jdbcType="TIMESTAMP" property="hireDate" />
</resultMap>
<sql id="Base_Column_List">
id, name, age, address, hire_date
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.course.vo.User">
insert into user (id, name, age,
address, hire_date)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER},
#{address,jdbcType=VARCHAR}, #{hireDate,jdbcType=TIMESTAMP})
</insert>
<insert id="insertSelective" parameterType="com.course.vo.User">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
<if test="age != null">
age,
</if>
<if test="address != null">
address,
</if>
<if test="hireDate != null">
hire_date,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="age != null">
#{age,jdbcType=INTEGER},
</if>
<if test="address != null">
#{address,jdbcType=VARCHAR},
</if>
<if test="hireDate != null">
#{hireDate,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.course.vo.User">
update user
<set>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="age != null">
age = #{age,jdbcType=INTEGER},
</if>
<if test="address != null">
address = #{address,jdbcType=VARCHAR},
</if>
<if test="hireDate != null">
hire_date = #{hireDate,jdbcType=TIMESTAMP},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.course.vo.User">
update user
set name = #{name,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER},
address = #{address,jdbcType=VARCHAR},
hire_date = #{hireDate,jdbcType=TIMESTAMP}
where id = #{id,jdbcType=INTEGER}
</update>

<select id="getAllUser" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
</select>
</mapper>

Service

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

import java.util.List;

import com.course.vo.User;

public interface UserService {

public void addUser(User user);
public void updateUser(User user);
public void deleteUser(User user);

public User queryUserById(Integer id);

public List<User> queryAllUser();

public List<User> queryUserByPage(int pageIndex, int pageSize);
}
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
package com.course.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.course.dao.UserMapper;
import com.course.service.UserService;
import com.course.vo.User;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@Service
public class UserServiceImpl implements UserService {

@Autowired
private UserMapper userMapper;

@Override
public void addUser(User user) {
userMapper.insertSelective(user);
}

@Override
public void updateUser(User user) {
userMapper.updateByPrimaryKey(user);
}

@Override
public void deleteUser(User user) {
userMapper.deleteByPrimaryKey(user.getId());
}

@Override
public User queryUserById(Integer id) {
User user = userMapper.selectByPrimaryKey(id);
return user;
}

@Override
public List<User> queryAllUser() {
List<User> userList = userMapper.getAllUser();
return userList;
}

@Override
public List<User> queryUserByPage(int pageIndex, int pageSize) {
Page<User> page = PageHelper.startPage(pageIndex, pageSize);
List<User> userList = userMapper.getAllUser();
System.out.println("数量:" + page.getTotal());
return userList;
}
}

Controller

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
package com.course.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.course.service.UserService;
import com.course.vo.User;

@Controller
public class UserController {

@Autowired
private UserService userService;

public void addUser() {
Date hireDate = new Date();
for (int i = 0; i < 20; i++) {
User user = new User("name2"+i, 2, "address2"+i, hireDate);
userService.addUser(user);
}
}

public void updateUser() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date hireDate = null;
try {
hireDate = simpleDateFormat.parse("2022-01-01 08:30:20");
} catch (ParseException e) {
e.printStackTrace();
}
User user = new User(168, "name2", 12, "address2", hireDate);
userService.updateUser(user);
}

public void deleteUser() {
User user = new User();
user.setId(172);
userService.deleteUser(user);
}

public User queryUserById(Integer id) {
return userService.queryUserById(id);
}

public List<User> queryAllUser() {
return userService.queryAllUser();
}

public List<User> queryUserByPage(int pageIndex, int pageSize) {
return userService.queryUserByPage(pageIndex, pageSize);
}
}

测试类

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.test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.course.controller.UserController;
import com.course.vo.User;

public class MybatisXmlTest {

public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
UserController userController = (UserController) applicationContext.getBean("userController");
userController.addUser();
// DEBUG [main] - ==> Preparing: insert into user ( name, age, address, hire_date ) values ( ?, ?, ?, ? )
// DEBUG [main] - ==> Parameters: name2(String), 2(Integer), address2(String), 2022-04-01 12:30:10.066(Timestamp)
// DEBUG [main] - <== Updates: 1

userController.updateUser();
// DEBUG [main] - ==> Preparing: update user set name = ?, age = ?, address = ?, hire_date = ? where id = ?
// DEBUG [main] - ==> Parameters: name2(String), 12(Integer), address2(String), 2022-01-01 08:30:20.0(Timestamp), 168(Integer)
// DEBUG [main] - <== Updates: 1

userController.deleteUser();
// DEBUG [main] - ==> Preparing: delete from user where id = ?
// DEBUG [main] - ==> Parameters: 172(Integer)
// DEBUG [main] - <== Updates: 1

User user = userController.queryUserById(167);
System.out.println(user);
// DEBUG [main] - ==> Preparing: select id, name, age, address, hire_date from user where id = ?
// DEBUG [main] - ==> Parameters: 167(Integer)
// DEBUG [main] - <== Total: 1
// User [id=167, name=name1, age=1, address=address1, hireDate=Fri Mar 18 16:33:44 CST 2022]

List<User> userList = userController.queryAllUser();
System.out.println(userList);
// DEBUG [main] - ==> Preparing: select id, name, age, address, hire_date from user
// DEBUG [main] - ==> Parameters:
// DEBUG [main] - <== Total: 4
// [User [id=167, name=name1, age=1, address=address1, hireDate=Fri Mar 18 16:33:44 CST 2022], User [id=168, name=name1, age=1, address=address1, hireDate=Fri Mar 18 16:33:59 CST 2022], User [id=171, name=name2, age=2, address=address2, hireDate=Mon Mar 21 12:39:59 CST 2022], User [id=172, name=name2, age=2, address=address2, hireDate=Fri Apr 01 12:30:10 CST 2022]]

List<User> userList = userController.queryUserByPage(1, 5);
System.out.println(userList);
// 数量:23
// DEBUG [main] - ==> Preparing: SELECT count(0) FROM user
// DEBUG [main] - ==> Parameters:
// DEBUG [main] - <== Total: 1
// DEBUG [main] - ==> Preparing: select id, name, age, address, hire_date from user LIMIT ?
// DEBUG [main] - ==> Parameters: 5(Integer)
// DEBUG [main] - <== Total: 5
// Page{count=true, pageNum=1, pageSize=5, startRow=0, endRow=5, total=23, pages=5, reasonable=false, pageSizeZero=false}[User [id=167, name=name1, age=1, address=address1, hireDate=Fri Mar 18 16:33:44 CST 2022], User [id=168, name=name2, age=12, address=address2, hireDate=Sat Jan 01 08:30:20 CST 2022], User [id=171, name=name2, age=2, address=address2, hireDate=Mon Mar 21 12:39:59 CST 2022], User [id=173, name=name20, age=2, address=address20, hireDate=Fri Apr 01 17:14:03 CST 2022], User [id=174, name=name21, age=2, address=address21, hireDate=Fri Apr 01 17:14:03 CST 2022]]
}
}

application-dao.xml

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
<?xml version="1.0" encoding="UTF-8"?>
<!-- 头文件 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">


<!-- 解析配置文件 -->
<!--
${username}在Spring里默认取的是当前的主机名,
如果想禁用取主机名可以使用system-properties-mode="FALLBACK"
-->
<context:property-placeholder location="classpath:db.properties" system-properties-mode="FALLBACK"/>

<!-- 声明数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 注入相关属性 -->
<property name="driverClassName" value="${driver}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${username}"></property>
<property name="password" value="${password}"></property>
</bean>

<!-- 声明sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 注入mybatis.cfg.xml -->
<!--
不使用mybatis.cfg.xml配置文件
<property name="configLocation" value="classpath:mybatis.cfg.xml"></property>
-->
<!-- 加载映射文件mapper.xml -->
<property name="mapperLocations">
<array>
<value>classpath:com/course/mapper/*.xml</value>
</array>
</property>
<!-- 加载插件 -->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor"></bean>
</array>
</property>
</bean>

<!--
配置接口扫描
因为UserMapper.java没有实现类,所以必须依靠cglib在内存中构造代理对象
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入mapper接口所在的包 -->
<property name="basePackage" value="com.course.dao"></property>

<!--
如果有多个mapper接口,value可以为数组,用逗号或者换行分割
<property name="basePackage" value="com.course.dao,com.course.dao2"></property>

<property name="basePackage">
<value>
com.course.dao
com.course.dao2
</value>
</property>
-->

<!--
注入sqlSessionFactory
因为是BeanName,所以是value,不是ref
-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
</beans>

application-service.xml

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
<?xml version="1.0" encoding="UTF-8"?>
<!-- 头文件 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">


<!-- 声明式事务的配置开始 -->
<!-- 1.声明事务管理器 -->
<!-- 用Spring自带的事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>

<!-- 2.声明通知方式 -->
<tx:advice id="advice" transaction-manager="transactionManager">
<!-- 配置那些方法要加入事务 -->
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="get*" propagation="REQUIRED"/>
<tx:method name="query*" propagation="REQUIRED" read-only="true"/>
<tx:method name="*" propagation="REQUIRED" read-only="true"/>
</tx:attributes>
</tx:advice>

<!-- 3.进行AOP配置 -->
<aop:config>
<!-- 声明切面 -->
<!-- 事务应该加在service层,不应该加在dao层 -->
<aop:pointcut id="pc" expression="execution(* com.course.service.impl.*.*(..))"/>
<!-- 织入 -->
<aop:advisor advice-ref="advice" pointcut-ref="pc"/>
</aop:config>
<!-- 声明式事务的配置结束 -->

<!-- 配置包扫描 -->
<context:component-scan base-package="com.course.service.impl"></context:component-scan>
</beans>

application-controller.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
<!-- 头文件 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">


<!-- 配置包扫描 -->
<context:component-scan base-package="com.course.controller"></context:component-scan>
</beans>

applicationContext.xml

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"?>
<!-- 头文件 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">


<import resource="classpath:application-dao.xml"/>
<import resource="classpath:application-service.xml"/>
<import resource="classpath:application-controller.xml"/>
</beans>

db.properties

1
2
3
4
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/spring_test
username=root
password=123456

log4j.properties

1
2
3
4
5
6
7
8
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n