0%

SSM-8-整合MyBatis和Spring

SSM-8-整合MyBatis和Spring

准备工作

  1. 准备jar包
  2. 编写配置文件
    • db.properties
    • applicationContext
    • mybatis-config
    • log4j.properties

jar包

ant-1.9.6.jar
ant-launcher-1.9.6.jar
asm-5.1.jar
aspectjweaver-1.8.10.jar
cglib-3.2.4.jar
commons-dbcp2-2.1.1.jar
commons-logging-1.2.jar
commons-pool2-2.4.2.jar
javassist-3.21.0-GA.jar
log4j-1.2.17.jar
log4j-api-2.3.jar
log4j-core-2.3.jar
mybatis-3.4.2.jar
mybatis-spring-1.3.1.jar
mysql-connector-java-5.1.40-bin.jar
mysql-connector-java-5.1.8.jar
ognl-3.1.12.jar
slf4j-api-1.7.22.jar
slf4j-log4j12-1.7.22.jar
spring-aop-4.3.6.RELEASE.jar
spring-aspects-4.3.6.RELEASE.jar
spring-beans-4.3.6.RELEASE.jar
spring-context-4.3.6.RELEASE.jar
spring-core-4.3.6.RELEASE.jar
spring-expression-4.3.6.RELEASE.jar
spring-jdbc-4.3.6.RELEASE.jar
spring-tx-4.3.6.RELEASE.jar

配置文件

db.properities

1
2
3
4
5
6
7
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.134.128:3306/mybatis
jdbc.username=root
jdbc.password=root
jdbc.maxTotal=30
jdbc.maxIdle=10
jdbc.initialSize=5

applicationContext

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
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">

<context:property-placeholder
location="classpath:db.properties" />
<!-- 1.配置数据源 -->
<bean id="dataSource"
class="org.apache.commons.dbcp2.BasicDataSource">
<!--数据库驱动 -->
<property name="driverClassName" value="${jdbc.driver}" />
<!--连接数据库的url -->
<property name="url" value="${jdbc.url}" />
<!--连接数据库的用户名 -->
<property name="username" value="${jdbc.username}" />
<!--连接数据库的密码 -->
<property name="password" value="${jdbc.password}" />
<!-- 最大连接数 -->
<property name="maxTotal" value="${jdbc.maxTotal}" />
<!-- 最大空闲连接 -->
<property name="maxIdle" value="${jdbc.maxIdle}" />
<!-- 初始化连接数 -->
<property name="initialSize" value="${jdbc.InitialSize}" />
</bean>

<!-- 事务管理器,依赖于数据源 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 开启事务注解,注册事务管理器驱动 -->
<tx:annotation-driven
transaction-manager="transactionManager" />
<!-- mybatis与spring整合 -->
<!-- 配置MyBatis工厂 -->
<bean id="SqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource" />
<!-- 指定核心配置文件位置 -->
<property name="configLocation"
value="classpath:mybatis-config.xml"></property>
</bean>
</beans>

mybatis-config

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" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

<!-- 定义别名 -->
<typeAliases>
<!-- <typeAlias alias="user" type="com.itheima.po.User" /> -->
<!-- <package name="com.itheima.po" />-->
<package name="com.itheima.po"/>
</typeAliases>

<!--2.配置Mapper的位置 -->
<mappers>
<mapper resource="com/itheima/mapper/IdCardMapper.xml" />
<mapper resource="com/itheima/mapper/PersonMapper.xml" />
<mapper resource="com/itheima/mapper/UserMapper.xml" />
<mapper resource="com/itheima/mapper/OrdersMapper.xml" />
<mapper resource="com/itheima/mapper/ProductMapper.xml" />
</mappers>
</configuration>

log4j.properties

1
2
3
4
5
6
7
8
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.itheima=DEBUG
# 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

新建package

com.itheima

传统Dao方式的开发整合

Customer

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
package com.itheima.po;

/**
* @author NoOne dotaerday@gmail.com:
* @version 创建时间:2020年3月8日 上午8:01:31 类说明
*/
public class Customer {
private Integer id; // 主键id
private String username; // 客户名称
private String jobs; // 职业
private String phone; // 电话

public Integer getId() {
return id;
}

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

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getJobs() {
return jobs;
}

public void setJobs(String jobs) {
this.jobs = jobs;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

@Override
public String toString() {
return "Customer [id=" + id + ", username=" + username + ", jobs=" + jobs + ", phone=" + phone + "]";
}
}

CustomerMapper

1
2
3
4
5
6
7
8
9
10
11
<?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">
<!-- namespace表示命名空间 -->
<mapper namespace="com.itheima.mapper.CustomerMapper">
<!-- 根据id查询客户信息 -->
<select id="findCustomerById" parameterType="Integer" resultType="customer">
select * from t_customer where id = #{id}
</select>
</mapper>

CustomerDao

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

import com.itheima.po.Customer;

/**
* @author NoOne dotaerday@gmail.com:
* @version 创建时间:2020年3月8日 下午5:53:20
* 类说明
*/
public interface CustomerDao {
public Customer findCustomerById(Integer id);
}

CustomerImpl

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

import org.mybatis.spring.support.SqlSessionDaoSupport;

import com.itheima.dao.CustomerDao;
import com.itheima.po.Customer;

/**
* @author NoOne dotaerday@gmail.com:
* @version 创建时间:2020年3月8日 下午5:54:06
* 类说明
*/
public class CustomerDaoImpl extends SqlSessionDaoSupport implements CustomerDao{

//通过id查询客户
@Override
public Customer findCustomerById(Integer id) {
return this.getSqlSession().selectOne("com.itheima.mapper.CustomerMapper.findCustomerById", 1);
}

}

applicationContext需要将customerDao注入SqlSession

1
2
3
<bean id="customerDao" class="com.itheima.dao.impl.CustomerDaoImpl">
<property name="sqlSessionFactory" ref="SqlSessionFactory"></property>
</bean>

测试类

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

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

import com.itheima.dao.CustomerDao;
import com.itheima.po.Customer;

/**
* @author NoOne dotaerday@gmail.com:
* @version 创建时间:2020年3月8日 下午5:57:57
* 类说明
*/
public class DaoTest {
@Test
public void findCustomerByIdDaoTest() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//CustomerDao customerDao = (CustomerDao) applicationContext.getBean("customerDao");
CustomerDao customerDao = applicationContext.getBean(CustomerDao.class);
Customer customer = customerDao.findCustomerById(1);
System.out.println(customer);
}
}

基于Mapper接口方式的开发整合

  1. mapperInterface 用于指定接口
  2. SqlSessionFactory 用于指定SqlSessionFactory
  3. SqlSessionTemplate 用于指定SqlSessionTemplate 如果跟2同时使用,则只用3

配置文件

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"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--
Mapper代理开发规范
1)Mapper接口的名称和对应的Mapper.xml映射文件的名称必须一致
2)Mapper.xml文件的namespace与Mapper接口的类路径相同(即接口文件和映射文件需要放在同一个包中)
3)Mapper接口中的方法名和Mapeer.xml中定义的每个执行语句的id相同
4)Mapper接口中的方法的输入参数类型和Mapeer.xml中定义的每个sql的parameterType类型相同
5)Mapper接口方法的输出参数类型要和Mapper.xml定义的每个sql的resultType的类型相同
-->
<!-- namespace表示命名空间 -->
<mapper namespace="com.itheima.mapper.CustomerMapper">
<!-- 根据id查询客户信息 -->
<select id="findCustomerById" parameterType="Integer" resultType="customer">
select * from t_customer where id = #{id}
</select>
</mapper>

applicationContext

1
2
3
4
5
6
<!-- Mapper代理开发(基于MapperFactoryBean) -->
<bean id="customerMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.itheima.mapper.CustomerMapper"/>
<property name="sqlSessionFactory" ref="SqlSessionFactory"/>

</bean>

基于MapeerScannerConfigurer的开发整合

  1. basePackage 指定映射接口文件所在路径
  2. annotationClass
  3. sqlSessionFactoryBeanName
  4. sqlSessiontemplateBeanName
  5. markerInterface

applicationContext

1
2
3
4
<!-- Mapper代理开发(基于MapeerScannerConfigurer)  -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.itheima.mapper"/>
</bean>

mybatis-config里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
package com.itheima.service.impl;

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

import com.itheima.mapper.CustomerMapper;
import com.itheima.po.Customer;
import com.itheima.service.CustomerService;

/**
* @author NoOne dotaerday@gmail.com:
* @version 创建时间:2020年3月8日 下午10:17:55
* 类说明
*/

@Service
@Transactional
public class CustomerServiceImpl implements CustomerService{

@Autowired
private CustomerMapper customerMapper;
@Override
public void addCustomer(Customer customer) {
this.customerMapper.addCustomer(customer);
//int i = 1/0;//模拟一场
}

}

本文作者:NoOne
本文地址https://noonegroup.xyz/posts/4389218b/
版权声明:转载请注明出处!