<dependencies>
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
<!-- junit测试包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--日志包-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
<!--spring数据库-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>
<!--aop-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>
<!--spring-mybatis整合包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!--spring相关包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>
</dependencies>
<!--配置资源文件扫描,否则Mapper-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml
true
src/main/resources
**/ *.xml</include>
<include>**/*.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/databasename?characterEncoding=utf-8
jdbc.username=
jdbc.password=
# For all other servers: Comment out the Log4J listener in web.xml to activate Log4J.
log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
#begin
#for normal test,delete when online
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
public class Dept implements Serializable {
private Integer id;
private String name;
@Override
public String toString() {
return "Dept{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
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;
}
}
<?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.dao.DeptDAO">
<select id="getDeptById" resultType="Dept">
SELECT
id,
name
FROM dept
WHERE id = #{
id}
</select>
<insert id="addDept" parameterType="Dept" keyProperty="id" useGeneratedKeys="true">
insert into DEPT(name) VALUES (#{
name})
</insert>
</mapper>
Spring负责管理数据源,加载Mybatis配置文件,Mybatis的session和事务
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:property-placeholder location="jdbc.properties" ignore-unresolvable="true"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>
注意:mybatis配置文件中不需再写mapper映射文件的配置
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation"value="classpath:mybatis-config.xml"/>
<property name="typeAliasesPackage" value="com.pojo"/>
<property name="mapperLocations" value="classpath:com/dao/mapper/*.xml"/>
</bean>
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.pojo"/>
<property name="mapperLocations" value="classpath:com/dao/mapper/*.xml"/>
</bean>
package com.dao;
import com.pojo.Dept;
public interface DeptDAO {
Dept getDeptById(Integer id);
void addDept(Dept dept);
}
package com.dao;
import com.pojo.Dept;
import org.mybatis.spring.support.SqlSessionDaoSupport;
public class DeptDAOImpl extends SqlSessionDaoSupport implements DeptDAO {
@Override
public Dept getDeptById(Integer id) {
//
return super.getSqlSession().selectOne("DEPT.getDeptById", id);
}
@Override
public void addDept(Dept dept) {
super.getSqlSession().insert("com.dao.DeptDAO.addDept",dept);
}
}
<!-- <bean id="deptDAO" class="com.dao.impl.DeptDAOImpl">-->
<!-- <property name="sqlSessionFactory" ref="sessionFactory"/>-->
<!-- </bean>-->
测试代码
public class SpringMybatisTest {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
@Test
public void testSelect() {
DeptDAO deptDAO = (DeptDAO) applicationContext.getBean("deptDAO");
Dept dept=new Dept();
dept.setName("aaa");
deptDAO.addDept(dept);
}
}
mybatis可以没有实现类,但mapper映射文件的namespace必须是接口的全路径。接口中方法名与sql语句的id必须一致。
spring配置如下:
<!-- <bean id="DeptDAO" class="org.mybatis.spring.mapper.MapperFactoryBean">-->
<!-- <property name="mapperInterface" value="com.dao.DeptDAO"/>-->
<!-- <property name="sqlSessionFactory" ref="sessionFactory"/>-->
<!-- </bean>-->
测试代码如下:
@Test
public void testDeptDAO(){
DeptDAO dao= (DeptDAO) applicationContext.getBean("DeptDAO");
Dept dept=dao.getDeptById(1);
System.out.println(dept);
}
当存在多个接口时,可以统一扫描,不需要为每一个接口声明一个Bean
spring配置
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.dao"/>
</bean>
spring在扫描后会自动生成接口对应的Bean(接口名字的首字母小写),在具体代码中,通过mapper文件的namespace来确定调用哪个mapper
@Test
public void testSelect() {
DeptDAO deptDAO = (DeptDAO) applicationContext.getBean("deptDAO");
Dept dept=new Dept();
dept.setName("aaa");
deptDAO.addDept(dept);
}
spring中事务的管理都是由切面来完成的,未设置事务管理时,每一个crud都是独自提交,无法完成业务需求的
在service包中建立相应的类:
@Service
public class DeptService {
@Autowired
private DeptDAO deptDAO;//此处的DAO不能自己去new
public void add(Dept dept) throws Exception {
deptDAO.addDept(dept);
deptDAO.addDept(dept);
throw new Exception("我是测试的异常");
}
}
我手动抛出异常,在设置事务管理后,数据并不会插入到数据库中,但是未设置事务管理时,即使有异常抛出,数据仍然会插入数据库中
speing的配置
<!--扫描service包下的service注解,自动生成相应的Bean-->
<context:component-scan base-package="com.service">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>
<!--配置事务管理器,指定数据源-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--对add开头的方法,有异常则回滚-->
<tx:method name="add*" rollback-for="Exception" isolation="SERIALIZABLE"/>
<tx:method name="update*" rollback-for="Exception"/>
<tx:method name="delete*" rollback-for="Exception"/>
<!--对get开头的方法设置只读-->
<tx:method name="get*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!--配置切面,指定要事务管理的方法-->
<aop:config >
<aop:pointcut id="point" expression="execution(* com.service..*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="point"/>
</aop:config>