生活随笔
收集整理的這篇文章主要介紹了
Spring+Mybatis整合
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1 創(chuàng)建復(fù)雜對象
復(fù)雜對象: 類中沒有構(gòu)造方法,或者構(gòu)造方法不能調(diào)用如接口類型或抽象類實(shí)例
1.編寫ConnectionFactoryBean的代碼如下:
package com.txw.factory;import org.springframework.beans.factory.FactoryBean;
import java.sql.Connection;
import java.sql.DriverManager;
public class ConnectionFactoryBean implements FactoryBean<Connection> {@Overridepublic Connection getObject() throws Exception {Class.forName("com.mysql.jdbc.Driver");return DriverManager.getConnection("jdbc:mysql://192.168.64.128:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai","root","123456");}@Overridepublic Class<?> getObjectType() {return Connection.class;}@Overridepublic boolean isSingleton() {return false;}
}
如圖所示:
2.配置工廠管理的代碼如下:
<?xml version
="1.0" encoding
="UTF-8"?>
<beans xmlns
="http://www.springframework.org/schema/beans"xmlns
:xsi
="http://www.w3.org/2001/XMLSchema-instance"xsi
:schemaLocation
="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--管理 核心業(yè)務(wù)對象 目標(biāo)對象
--><bean id
="connectionFactoryBean" class="com.txw.factory.ConnectionFactoryBean"></bean
>
</beans
>
如圖所示:
3.編寫SpringTest的代碼如下:
package com.txw.factory;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {public static void main(String[] args
) {ApplicationContext context
= new ClassPathXmlApplicationContext("factory/spring.xml");ConnectionFactoryBean connectionFactoryBean
= (ConnectionFactoryBean) context
.getBean("connectionFactoryBean");System.out
.println(connectionFactoryBean
);}
}
如圖所示:
2 SM整合思路
2.1 spring框架的作用
spring框架 項(xiàng)目管理框架 主要負(fù)責(zé)項(xiàng)目中組件對象的創(chuàng)建。
2.2 Mybatis框架的作用
Mybatis框架 持久層框架 主要用來簡化數(shù)據(jù)庫訪問的操作。
2.3 整合思路
整合思路: 兩個(gè)框架作用不同,貌似沒有什么聯(lián)系,更深入看才能看出所謂Spring整合Mybatis,其實(shí)就是通過spring框架接管mybatis框架中核心對象的創(chuàng)建。
2.4 mybatis中的核心對象有哪些
Mybatis的核心對象為: SqlSessionFactory 整合就是通過Spring管理SqlSessionFactory對象的創(chuàng)建。
2.5 整合思路圖示
3 SM整合DAO編程步驟
1.引入相關(guān)的依賴的代碼如下:
<?xml version
="1.0" encoding
="UTF-8"?>
<project xmlns
="http://maven.apache.org/POM/4.0.0" xmlns
:xsi
="http://www.w3.org/2001/XMLSchema-instance"xsi
:schemaLocation
="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion
><groupId>com
.txw
</groupId
><artifactId>spring
-03</artifactId
><version>1.0-SNAPSHOT
</version
><packaging>war
</packaging
><properties><project.build.sourceEncoding>UTF
-8</project
.build
.sourceEncoding
><maven.compiler.source>1.8</maven
.compiler
.source
><maven.compiler.target>1.8</maven
.compiler
.target
></properties
><!--依賴坐標(biāo)
--><dependencies><!--mybatis
--><dependency><groupId>org
.mybatis
</groupId
><artifactId>mybatis
</artifactId
><version>3.2.8</version
></dependency
><!--spring
4.3.2相關(guān)依賴
--><dependency><groupId>org
.springframework
</groupId
><artifactId>spring
-core
</artifactId
><version>4.3.2.RELEASE
</version
></dependency
><dependency><groupId>org
.springframework
</groupId
><artifactId>spring
-context
</artifactId
><version>4.3.2.RELEASE
</version
></dependency
><dependency><groupId>org
.springframework
</groupId
><artifactId>spring
-context
-support
</artifactId
><version>4.3.2.RELEASE
</version
></dependency
><dependency><groupId>org
.springframework
</groupId
><artifactId>spring
-jdbc
</artifactId
><version>4.3.2.RELEASE
</version
></dependency
><dependency><groupId>org
.springframework
</groupId
><artifactId>spring
-aop
</artifactId
><version>4.3.2.RELEASE
</version
></dependency
><dependency><groupId>org
.springframework
</groupId
><artifactId>spring
-beans
</artifactId
><version>4.3.2.RELEASE
</version
></dependency
><dependency><groupId>org
.springframework
</groupId
><artifactId>spring
-expression
</artifactId
><version>4.3.2.RELEASE
</version
></dependency
><dependency><groupId>org
.springframework
</groupId
><artifactId>spring
-aspects
</artifactId
><version>4.3.2.RELEASE
</version
></dependency
><dependency><groupId>org
.springframework
</groupId
><artifactId>spring
-tx
</artifactId
><version>4.3.2.RELEASE
</version
></dependency
><dependency><groupId>org
.springframework
</groupId
><artifactId>spring
-web
</artifactId
><version>4.3.2.RELEASE
</version
></dependency
><!--mybatis
-spring整合jar
--><dependency><groupId>org
.mybatis
</groupId
><artifactId>mybatis
-spring
</artifactId
><version>1.3.1</version
></dependency
><!--數(shù)據(jù)庫驅(qū)動(dòng)
--><dependency><groupId>mysql
</groupId
><artifactId>mysql
-connector
-java
</artifactId
><version>5.1.40</version
></dependency
><dependency><groupId>com
.alibaba
</groupId
><artifactId>druid
</artifactId
><version>1.1.12</version
></dependency
><!--單元測試
--><dependency><groupId>junit
</groupId
><artifactId>junit
</artifactId
><version>4.11</version
><scope>test
</scope
></dependency
></dependencies
><build><finalName>spring
-03</finalName
></build
>
</project
>
如圖所示:
2.創(chuàng)建數(shù)據(jù)庫及表結(jié)構(gòu)的SQL語句如下:
drop table t_user
;
CREATE TABLE `t_user
` (`id
` varchar(40) NOT NULL,`name
` varchar(40) DEFAULT NULL,`age
` int(3) DEFAULT NULL,`birthday
` timestamp NULL DEFAULT NULL,PRIMARY KEY (`id
`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
;
如圖所示:
3.編寫的User的代碼如下:
package com.txw.entity;import java.io.Serializable;
import java.util.Date;
@SuppressWarnings("all")
public class User implements Serializable {private int id
;private String name
; private int age
; private Date birthday
; public User() {}public User(int id
, String name
, int age
, Date birthday
) {this.id
= id
;this.name
= name
;this.age
= age
;this.birthday
= birthday
;}public int getId() {return id
;}public void setId(int id
) {this.id
= id
;}public String getName() {return name
;}public void setName(String name
) {this.name
= name
;}public int getAge() {return age
;}public void setAge(int age
) {this.age
= age
;}public Date getBirthday() {return birthday
;}public void setBirthday(Date birthday
) {this.birthday
= birthday
;}@Overridepublic String toString() {return "User{" +"id=" + id
+", name='" + name
+ '\'' +", age=" + age
+", birthday=" + birthday
+'}';}
}
如圖所示:
4.編寫UserDAO的代碼如下:
package com
.txw
.dao
;import com
.txw
.entity
.User;
import java
.util
.List
;
@SuppressWarnings("all")
public interface UserDAO {
public List
<User> findAll
();
}
如圖所示:
5.編寫UserDaoMapper.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.txw.dao.UserDAO"><!<select id
="findAll" resultType
="com.txw.entity.User">select * from t_user
</select>
</mapper
>
如圖所示:
6.編寫Spring-myabtis.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"xsi
:schemaLocation
="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--創(chuàng)建數(shù)據(jù)源
--><bean id
="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name
="driverClassName" value
="com.mysql.jdbc.Driver"/><property name
="url" value
="jdbc:mysql://192.168.64.128:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai"/><property name
="username" value
="root"/><property name
="password" value
="123456"/></bean
><!--創(chuàng)建sqlSessionFactory
--><bean id
="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name
="dataSource" ref
="dataSource"/><property name
="mapperLocations" ><array><value>classpath
:com
/txw
/mapper
/UserDAOMapper.xml
</value
></array
></property
></bean
><!--創(chuàng)建DAO
--><bean id
="userDAO" class="org.mybatis.spring.mapper.MapperFactoryBean"><property name
="sqlSessionFactory" ref
="sqlSessionFactory"/><property name
="mapperInterface" value
="com.txw.dao.UserDAO"/></bean
>
</beans
>
如圖所示:
7.編寫SpringTest的代碼如下:
package com.txw.test;import com.txw.dao.UserDAO;
import com.txw.entity.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class SpringTest {@Testpublic void testFindAll(){ApplicationContext context
= new ClassPathXmlApplicationContext("Spring-myabtis.xml");UserDAO userDAO
= (UserDAO) context
.getBean("userDAO");List<User> users
= userDAO
.findAll();for (User user
: users
) {System.out
.println(user
);}}
}
如圖所示:
4 SM整合Service編程步驟
如圖所示:
1.編寫的UserService的代碼如下:
package com.txw.service;import com.txw.entity.User;
import java.util.List;
@SuppressWarnings("all")
public interface UserService {public List<User> findAll();
}
如圖所示:
2.編寫的UserServiceImpl的代碼如下:
package com.txw.service.impl;import com.txw.dao.UserDAO;
import com.txw.entity.User;
import com.txw.service.UserService;
import java.util.List;
@SuppressWarnings("all")
public class UserServiceImpl implements UserService {private UserDAO userDAO
;public void setUserDAO(UserDAO userDAO
) {this.userDAO
= userDAO
;}@Overridepublic List<User> findAll() {return userDAO
.findAll();}
}
如圖所示:
3.在Spring-myabtis.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"xsi
:schemaLocation
="http
://www
.springframework
.org
/schema
/beanshttp
://www
.springframework
.org
/schema
/beans
/spring
-beans
-3.0.xsdhttp
://www
.springframework
.org
/schema
/aop http
://www
.springframework
.org
/schema
/aop
/spring
-aop
-3.0.xsd http
://www
.springframework
.org
/schema
/tx http
://www
.springframework
.org
/schema
/tx
/spring
-tx
.xsd"
><bean id
="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name
="driverClassName" value
="com.mysql.jdbc.Driver"/><property name
="url" value
="jdbc:mysql://192.168.64.128:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai"/><property name
="username" value
="root"/><property name
="password" value
="123456"/></bean
><!--創(chuàng)建sqlSessionFactory
--><bean id
="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name
="dataSource" ref
="dataSource"/><property name
="mapperLocations" ><array><value>classpath
:com
/txw
/mapper
/UserDAOMapper.xml
</value
></array
></property
></bean
><!--創(chuàng)建DAO
--><bean id
="userDAO" class="org.mybatis.spring.mapper.MapperFactoryBean"><property name
="sqlSessionFactory" ref
="sqlSessionFactory"/><property name
="mapperInterface" value
="com.txw.dao.UserDAO"/></bean
><!--創(chuàng)建事務(wù)管理器
--><bean id
="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name
="dataSource" ref
="dataSource"/></bean
><!--配置事務(wù)屬性
--><tx
:advice id
="txAdvice" transaction
-manager
="transactionManager"><tx
:attributes
><tx
:method name
="save*"/><tx
:method name
="update*"/><tx
:method name
="delete*"/><tx
:method name
="find*"/></tx
:attributes
></tx
:advice
><!--配置事務(wù)切面
--><aop
:config
><aop
:pointcut id
="pc" expression
="within(com.txw.service.*)"/><aop
:advisor advice
-ref
="txAdvice" pointcut
-ref
="pc"/></aop
:config
><!--配置
Service組件
--><bean id
="userService" class="com.txw.service.impl.UserServiceImpl"><property name
="userDAO" ref
="userDAO"/></bean
>
</beans
>
如圖所示:
5 事務(wù)屬性
5.1 事務(wù)傳播屬性
propagation
: 傳播REQUIRED
: 需要事務(wù)
,外部存在事務(wù)融入當(dāng)前事務(wù)
,外部沒有事務(wù)
,開啟新的事務(wù)。SUPPORTS
: 支持事務(wù)
,外部存在事務(wù)融入當(dāng)前事務(wù)
,外部沒有事務(wù)
,不開啟新的事務(wù)。REQUIRES_NEW
: 每次開啟新的事務(wù)
,如果外部存在事務(wù)外部事務(wù)掛起
,開啟新的事務(wù)運(yùn)行
,運(yùn)行結(jié)束后回復(fù)外部事務(wù)。NOT_SUPPORTED
: 不支持事務(wù)
,如果外部存在事務(wù)外部事務(wù)掛起
,已非事務(wù)方式運(yùn)行。NEVER
: 不支持事務(wù)
,存在事務(wù)報(bào)錯(cuò)。MANDATORY
: 強(qiáng)制事務(wù)沒有事務(wù)報(bào)錯(cuò)。NESTED
: 嵌套事務(wù)
,數(shù)據(jù)庫不支持。
5.2 事務(wù)的隔離級(jí)別
isolation 隔離級(jí)別DEFAULT
: 采用數(shù)據(jù)庫默認(rèn)隔離級(jí)別。READ_UNCOMMITTED
: 讀未提交。READ_COMMITTED
: 讀提交 用來避免臟讀現(xiàn)象出現(xiàn)的 oracle默認(rèn)隔離級(jí)別。REPEATABLE_READ
: 可重復(fù)讀主要是用來避免不可重復(fù)讀現(xiàn)象出現(xiàn)的
(在一次事務(wù)中一方更新
,導(dǎo)致兩次查詢結(jié)果不一致這種情況叫不可重復(fù)讀
) mysql默認(rèn)隔離級(jí)別。SERIALIZABLE
: 序列化讀 用來避免幻影讀現(xiàn)象出現(xiàn)
(在一次事務(wù)中一方插入
,導(dǎo)致兩次查詢結(jié)果不一致這種情況叫幻影讀
)。
5.3 讀寫和異常性
readonly `
true: 本次事務(wù)只讀。`
false: 本次事務(wù)非只讀。
<tx
:method name
="save*" propagation
="REQUIRES_NEW" read
-only
="true|false" isolation
="SERIALIZABLE"/>rollback
-for && no
-rollback
-for=""rollback
-for: 遇到什么類異常回滾。no
-rollback
-for: 遇到什么類異常不回滾。
<tx
:method name
="save*" rollback
-for="" no
-rollback
-for="" propagation
="REQUIRES_NEW" read
-only
="true" isolation
="SERIALIZABLE"/>timeout 超時(shí)性timeout
: -1 永不超時(shí)。
總結(jié)
以上是生活随笔為你收集整理的Spring+Mybatis整合的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。