生活随笔
收集整理的这篇文章主要介绍了
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整合的全部内容,希望文章能够帮你解决所遇到的问题。
如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。