Spring與MyBatis集成
- 一、事務
- 二、spring和mybatis的集成(XML方式)
- 1. 項目結構
- 2. 導包
- 3. 創建db.properties
- 4. 創建log4j.properties
- 5. 通過MyBatis逆向工程生成User、UserMapper、UserMapper.xml
- 6. 創建mybatis.cfg.xml
- 7. 創建application-dao.xml
- 8. 創建UserService
- 9. 創建UserserviceImpl
- 10. 創建application-service.xml
- 11. 創建UserController
- 12. 創建application-action.xml
- 13. 創建applicationContext.xml
- 14. 測試
- 三、 spring與mybatis集成(註解方式)
- 四、註解方式去掉mybatis.cfg.xml
- 五、在註解方式上新增分頁查詢
一、事務
1. 事務的分類
- 編程式事務
將事務控制的代碼入侵到我們核心對象代碼中,如在hibernate 裏面配置session beginTreanaction() session.commit() - 聲明式事務
只需要在spring 的配置文件中,進行事務聲明,聲明將哪些方法加入事務環境進行執行。
2. 爲什麼要使用聲明式事務
大多數Spring 用戶選擇聲明式事務管理的原因是,這個是對應用代碼影響最小的選擇,使用aop特點在某個方法執行前開啓事務,結束時提交事務,因此也最符合 非侵入式 輕量級容器的理念
- Spring 聲明式事務管理可以在任何環境下使用,只需要更改配置文件,他就可以和JDBC、JDO、Hibernate 或其他的事務機制一起工作。
- Spring 的聲明式事務管理可以被應用到任何類(以及那個類的實例)上。
- Spring 提供聲明式的回滾規則。
- Spring 允許你通過AOP 定製事務行爲。(例如,如果需要,你可以在事務回滾中插入定製行爲。你也可以增加任意的通知,就像事務通知一樣)。
- Spring 不提供高端應用服務器提供的跨越遠程調用的事務上下文傳播。如果你需要這些特性,推薦使用EJB。然而,不要輕易使用這些特性,因爲通常我們並不希望跨越遠程調用。
3. Spring是如何實現聲明式事務的
Spring 的事務管理是通過AOP 代理實現的。其中的事務通知由元數據(目前基於XML 或註解)驅動
代理對象與事務元數據結合產生一個AOP代理,它使用一個PlatformTransactionManager 接口配合事務攔截器,在方法調用過後實施事務。
二、spring和mybatis的集成(XML方式)
1. 項目結構
2. 導包
1). spring
2). mybatis
3). mysql
4). pagehelper
5). log4j
3. 創建db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/springdemo
username=root
password=123456
4. 創建log4j.properties
# 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
5. 通過MyBatis逆向工程生成User、UserMapper、UserMapper.xml
1). User
/**
* User
*/
package com.lasing.domain;
import java.util.Date;
public class User {
private Integer id;
private String name;
private String address;
private Date birthday;
public User() {
super();
}
public User(String name, String address, Date birthday) {
super();
this.name = name;
this.address = address;
this.birthday = birthday;
}
public User(Integer id, String name, String address, Date birthday) {
super();
this.id = id;
this.name = name;
this.address = address;
this.birthday = birthday;
}
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address == null ? null : address.trim();
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String toString() {
return "User [id=" + id + ", name=" + name + ", address=" + address + ", birthday=" + birthday + "]";
}
}
2). UserMapper
/**
* UserMapper
*/
package com.lasing.mapper;
import java.util.List;
import com.lasing.domain.User;
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
List<User> selectAll();
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
3). UserMapper.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.lasing.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="com.lasing.domain.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="address" property="address" jdbcType="VARCHAR" />
<result column="birthday" property="birthday" jdbcType="TIMESTAMP" />
</resultMap>
<sql id="Base_Column_List" >
id, name, address, birthday
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
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.lasing.domain.User" >
insert into user (id, name, address,
birthday)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR},
#{birthday,jdbcType=TIMESTAMP})
</insert>
<insert id="insertSelective" parameterType="com.lasing.domain.User" >
insert into user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="name != null" >
name,
</if>
<if test="address != null" >
address,
</if>
<if test="birthday != null" >
birthday,
</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="address != null" >
#{address,jdbcType=VARCHAR},
</if>
<if test="birthday != null" >
#{birthday,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.lasing.domain.User" >
update user
<set >
<if test="name != null" >
name = #{name,jdbcType=VARCHAR},
</if>
<if test="address != null" >
address = #{address,jdbcType=VARCHAR},
</if>
<if test="birthday != null" >
birthday = #{birthday,jdbcType=TIMESTAMP},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.lasing.domain.User" >
update user
set name = #{name,jdbcType=VARCHAR},
address = #{address,jdbcType=VARCHAR},
birthday = #{birthday,jdbcType=TIMESTAMP}
where id = #{id,jdbcType=INTEGER}
</update>
<select id="selectAll" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
</select>
</mapper>
6. 創建mybatis.cfg.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">
<!-- 整個mybtais的配置中心 -->
<configuration>
<settings>
<!-- 讓log4j去記錄sql日誌 -->
<setting name="logImpl" value="LOG4J"/>
</settings>
<!-- 配置別名 -->
<typeAliases>
<package name="com.lasing.damain"/>
</typeAliases>
<!-- 注入pagehelper -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
<!-- 配置映射 -->
<mappers>
<mapper resource="com/lasing/mapping/UserMapper.xml"/>
</mappers>
</configuration>
7. 創建application-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- 導入頭文件 -->
<beans
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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">
<!-- 解析db.properties -->
<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 name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
<!-- 聲明sqlSessionFactory -->
<bean id="sqlSessionFactory" name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入數據源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 注入mybatis.cfg.xml -->
<property name="configLocation" value="classpath:mybatis.cfg.xml"/>
</bean>
<!-- 配置接口掃描
因爲UserMapper.java沒有實現類,所以必須依靠cglib在內存裏構造代理對象
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入mapper接口所在的包 -->
<property name="basePackage" value="com.lasing.mapper"></property>
<!-- 注入sqlSessionFactory
這裏要求是sqlSessionFactoryBeanName也就是IoC容器裏面的sqlSessionFactory對象
-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
</beans>
8. 創建UserService
/**
* UserService
*/
package com.lasing.service;
import java.util.List;
import com.lasing.domain.User;
public interface UserService {
public void add(User user);
public void deleteUserById(Integer id);
public void update(User user);
public User queryById(Integer id);
public List<User> queryAll();
}
9. 創建UserserviceImpl
/**
* UserServiceImpl
*/
package com.lasing.service.impl;
import java.util.List;
import com.lasing.domain.User;
import com.lasing.mapper.UserMapper;
import com.lasing.service.UserService;
public class UserServiceImpl implements UserService{
private UserMapper userMapper;
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Override
public void add(User user) {
this.userMapper.insert(user);
}
@Override
public void deleteUserById(Integer id) {
this.userMapper.deleteByPrimaryKey(id);
}
@Override
public void update(User user) {
this.userMapper.updateByPrimaryKey(user);
}
@Override
public User queryById(Integer id) {
return this.userMapper.selectByPrimaryKey(id);
}
@Override
public List<User> queryAll() {
return this.userMapper.selectAll();
}
}
10. 創建application-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- 導入頭文件 -->
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
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 ">
<!-- 聲明式事務的配置開始 -->
<!-- 聲明事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入數據源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 聲明通知方式
id:通知在IoC容器裏面的key
transaction-manager:使用事務管理器
-->
<tx:advice id="advise" transaction-manager="transactionManager">
<!-- 配置哪些方法要加入事務 -->
<tx:attributes>
<!-- name="add*" 代表切面裏面的類的所有方法如果爲add開頭就是用事務 -->
<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="del*" propagation="REQUIRED"/>
<tx:method name="load*" propagation="REQUIRED"/>
<tx:method name="get*" propagation="REQUIRED"/>
<tx:method name="query*" read-only="true"/>
<!-- 如果以上方法名都不能匹配就是用斜面這個* -->
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 進行AOP配置 -->
<aop:config>
<!-- 聲明切面 -->
<aop:pointcut expression="execution(* com.lasing.service.impl.*.*(..))" id="pc"/>
<!-- 織入 -->
<aop:advisor advice-ref="advise" pointcut-ref="pc"/>
</aop:config>
<!-- 聲明式事務的配置結束 -->
<!-- 聲明UserService -->
<bean id="userService" class="com.lasing.service.impl.UserServiceImpl" autowire="byType"></bean>
</beans>
11. 創建UserController
/**
* UserController
*/
package com.lasing.controller;
import java.util.Date;
import java.util.List;
import com.lasing.domain.User;
import com.lasing.service.UserService;
public class UserController {
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public void add() {
User user = new User("lasing","清遠",new Date());
this.userService.add(user);
}
public void deleteUserById() {
Integer id = 52;
this.userService.deleteUserById(id);
}
public void update() {
User user = new User(1,"lasing改","清遠gai",new Date());
this.userService.update(user);
}
public void queryById() {
Integer id = 1;
User user = this.userService.queryById(id);
System.out.println(user.toString());
}
public void queryAll() {
List<User> list = this.userService.queryAll();
for (User user : list) {
System.out.println(user.toString());
}
}
}
12. 創建application-action.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- 導入頭文件 -->
<beans
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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">
<bean id="userController" class="com.lasing.controller.UserController" autowire="byType"></bean>
</beans>
13. 創建applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- 導入頭文件 -->
<beans
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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">
<import resource="classpath:application-dao.xml"/>
<import resource="classpath:application-service.xml"/>
<import resource="classpath:application-action.xml"/>
</beans>
14. 測試
/**
* Test
*/
package com.lasing.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.lasing.controller.UserController;
public class MybatisTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"classpath:applicationContext.xml");
UserController userController = (UserController) applicationContext.getBean("userController");
// userController.queryById();
// System.out.println(userController);
userController.queryAll();
}
}
三、 spring與mybatis集成(註解方式)
在xml方式的基礎下修改以下代碼