生活随笔
收集整理的這篇文章主要介紹了
Spring+Mybatis整合
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 創建復雜對象
復雜對象: 類中沒有構造方法,或者構造方法不能調用如接口類型或抽象類實例
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"><!--管理 核心業務對象 目標對象
--><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框架 項目管理框架 主要負責項目中組件對象的創建。
2.2 Mybatis框架的作用
Mybatis框架 持久層框架 主要用來簡化數據庫訪問的操作。
2.3 整合思路
整合思路: 兩個框架作用不同,貌似沒有什么聯系,更深入看才能看出所謂Spring整合Mybatis,其實就是通過spring框架接管mybatis框架中核心對象的創建。
2.4 mybatis中的核心對象有哪些
Mybatis的核心對象為: SqlSessionFactory 整合就是通過Spring管理SqlSessionFactory對象的創建。
2.5 整合思路圖示
3 SM整合DAO編程步驟
1.引入相關的依賴的代碼如下:
<?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
><!--依賴坐標
--><dependencies><!--mybatis
--><dependency><groupId>org
.mybatis
</groupId
><artifactId>mybatis
</artifactId
><version>3.2.8</version
></dependency
><!--spring
4.3.2相關依賴
--><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
><!--數據庫驅動
--><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.創建數據庫及表結構的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"><!--創建數據源
--><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
><!--創建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
><!--創建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
><!--創建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
><!--創建DAO
--><bean id
="userDAO" class="org.mybatis.spring.mapper.MapperFactoryBean"><property name
="sqlSessionFactory" ref
="sqlSessionFactory"/><property name
="mapperInterface" value
="com.txw.dao.UserDAO"/></bean
><!--創建事務管理器
--><bean id
="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name
="dataSource" ref
="dataSource"/></bean
><!--配置事務屬性
--><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
><!--配置事務切面
--><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 事務屬性
5.1 事務傳播屬性
propagation
: 傳播REQUIRED
: 需要事務
,外部存在事務融入當前事務
,外部沒有事務
,開啟新的事務。SUPPORTS
: 支持事務
,外部存在事務融入當前事務
,外部沒有事務
,不開啟新的事務。REQUIRES_NEW
: 每次開啟新的事務
,如果外部存在事務外部事務掛起
,開啟新的事務運行
,運行結束后回復外部事務。NOT_SUPPORTED
: 不支持事務
,如果外部存在事務外部事務掛起
,已非事務方式運行。NEVER
: 不支持事務
,存在事務報錯。MANDATORY
: 強制事務沒有事務報錯。NESTED
: 嵌套事務
,數據庫不支持。
5.2 事務的隔離級別
isolation 隔離級別DEFAULT
: 采用數據庫默認隔離級別。READ_UNCOMMITTED
: 讀未提交。READ_COMMITTED
: 讀提交 用來避免臟讀現象出現的 oracle默認隔離級別。REPEATABLE_READ
: 可重復讀主要是用來避免不可重復讀現象出現的
(在一次事務中一方更新
,導致兩次查詢結果不一致這種情況叫不可重復讀
) mysql默認隔離級別。SERIALIZABLE
: 序列化讀 用來避免幻影讀現象出現
(在一次事務中一方插入
,導致兩次查詢結果不一致這種情況叫幻影讀
)。
5.3 讀寫和異常性
readonly `
true: 本次事務只讀。`
false: 本次事務非只讀。
<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 超時性timeout
: -1 永不超時。
總結
以上是生活随笔為你收集整理的Spring+Mybatis整合的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。