项目列表
整合环境搭建
- 准备所需JAR包
- 编写配置文件
db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
jdbc.maxTotal=30
jdbc.maxIdle=10
jdbc.initialSize=5
applicationContext.xml
<?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">
<!--读取db.properties -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源 -->
<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工厂 -->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据源 -->
<property name="dataSource" ref="dataSource" />
<!--指定核心配置文件位置 -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--实例化Dao -->
<bean id="customerDao" class="com.itheima.dao.impl.CustomerDaoImpl">
<!-- 注入SqlSessionFactory对象实例-->
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<!-- 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> -->
<!-- Mapper代理开发(基于MapperScannerConfigurer) -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.itheima.mapper" />
</bean>
<!-- 开启扫描 -->
<context:component-scan base-package="com.itheima.service" />
</beans>
mybatis-config.xml
<?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>
<package name="com.itheima.po" />
</typeAliases>
<!--配置Mapper的位置 -->
<mappers>
<mapper resource="com/itheima/po/CustomerMapper.xml" />
<!-- Mapper接口开发方式 -->
<mapper resource="com/itheima/mapper/CustomerMapper.xml" />
</mappers>
</configuration>
log4j.properties
# 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
传统DAO方式的开发整合
1.实现持久层
Customer.java
package com.itheima.po;
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.xml
<?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.itheima.po.CustomerMapper">
<!--根据id查询客户信息 -->
<select id="findCustomerById" parameterType="Integer"
resultType="customer">
select * from t_customer where id = #{id}
</select>
</mapper>
2、实现DAO层
Customer.java
package com.itheima.dao;
import com.itheima.po.Customer;
public interface CustomerDao {
// 通过id查询客户
public Customer findCustomerById(Integer id);
}
CustomerDaolmpl.java
package com.itheima.dao.impl;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import com.itheima.dao.CustomerDao;
import com.itheima.po.Customer;
public class CustomerDaoImpl
extends SqlSessionDaoSupport implements CustomerDao {
// 通过id查询客户
public Customer findCustomerById(Integer id) {
return this.getSqlSession().selectOne("com.itheima.po"
+ ".CustomerMapper.findCustomerById", id);
}
}
3.整合测试
DaoTest.java
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.mapper.CustomerMapper;
import com.itheima.po.Customer;
/**
* DAO测试类
*/
public class DaoTest {
@Test
public void findCustomerByIdDaoTest(){
@SuppressWarnings("resource")
ApplicationContext act =
new ClassPathXmlApplicationContext("applicationContext.xml");
// 根据容器中Bean的id来获取指定的Bean
CustomerDao customerDao =
(CustomerDao) act.getBean("customerDao");
// CustomerDao customerDao = act.getBean(CustomerDao.class);
Customer customer = customerDao.findCustomerById(1);
System.out.println(customer);
}
@Test
public void findCustomerByIdMapperTest(){
@SuppressWarnings("resource")
ApplicationContext act =
new ClassPathXmlApplicationContext("applicationContext.xml");
CustomerMapper customerMapper = act.getBean(CustomerMapper.class);
Customer customer = customerMapper.findCustomerById(1);
System.out.println(customer);
}
}
Mapper接口方式的开发整合
1、基于MapperFactoryBean的整合
CustomerMapper.java
package com.itheima.mapper;
import com.itheima.po.Customer;
public interface CustomerMapper {
// 通过id查询客户
public Customer findCustomerById(Integer id);
// 添加客户
public void addCustomer(Customer customer);
}
CustomerMapper.xml
<?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.itheima.mapper.CustomerMapper">
<!--根据id查询客户信息 -->
<select id="findCustomerById" parameterType="Integer"
resultType="customer">
select * from t_customer where id = #{id}
</select>
<!--添加客户信息 -->
<insert id="addCustomer" parameterType="customer">
insert into t_customer(username,jobs,phone)
values(#{username},#{jobs},#{phone})
</insert>
</mapper>
测试事务
CustomerService.java
package com.itheima.service;
import com.itheima.po.Customer;
public interface CustomerService {
public void addCustomer(Customer customer);
}
CustomerServicelmpl.java
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;
@Service
//@Transactional
public class CustomerServiceImpl implements CustomerService {
//注解注入CustomerMapper
@Autowired
private CustomerMapper customerMapper;
//添加客户
public void addCustomer(Customer customer) {
this.customerMapper.addCustomer(customer);
@SuppressWarnings("unused")
int i=1/0; //模拟添加操作后系统突然出现的异常问题
}
}
TransactionTest.java
package com.itheima.test;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import com.itheima.po.Customer;
import com.itheima.service.CustomerService;
/**
* 测试事务
*/
public class TransactionTest {
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext act =
new ClassPathXmlApplicationContext("applicationContext.xml");
CustomerService customerService =
act.getBean(CustomerService.class);
Customer customer = new Customer();
customer.setUsername("郭佳峰");
customer.setJobs("老董");
customer.setPhone("1388888888");
customerService.addCustomer(customer);
}
}