目前常见的ORM框架有Hibermate、MyBatis、 JPA等,Spring均提供了集成支持,通过提供相应模板类简化各种持久化技术的使用。Spring还提供一个简化JDBC API操作的SpringJDBC框架。
ORM持久化技术 | 模板类 |
---|---|
Spring JDBC | org.springframework.jdbc.core.JdbcTemplate |
Hibemate X.0 | org.springframework.orm.hibemateX.HibemateTemplate |
JPA | org.springframework.orm.jpa.JpaTemplate |
ibatis | org.springframework.orm.ibatis.SqlMapClientTemplate |
mybatis | org.mybatis.spring.SqlSessionTemplate |
spring4.0发布时mybatis尚未发布,所以mybatis同spring的集成由mybatis团队完成,可以看到包名不同。
可能是由于ibatis停止更新,spring4移除了对ibatis的支持,要在spring4以上使用ibatis,orm必须制定4以下版本。
--教师信息表
CREATE TABLE `teacher` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '教师编号',
`name` varchar(50) NOT NULL COMMENT '教师姓名',
`subject` enum('语文','英语','数学') NOT NULL COMMENT '教学科目',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;
--班级信息表
CREATE TABLE `class` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '班级编号',
`grade` int(2) DEFAULT NULL COMMENT '年级',
`seq_num` int(3) DEFAULT NULL COMMENT '班级号',
`head_tch_id` int(11) DEFAULT NULL COMMENT '班主任',
`ch_tch_id` int(11) DEFAULT NULL COMMENT '语文老师',
`math_tch_id` int(11) DEFAULT NULL COMMENT '数学老师',
`en_tch_id` int(11) DEFAULT NULL COMMENT '英语老师',
PRIMARY KEY (`id`),
UNIQUE KEY `UNIQE_CLASS` (`grade`,`seq_num`) USING BTREE,
KEY `head_teacher` (`head_tch_id`),
KEY `lang_teacher` (`ch_tch_id`),
KEY `math_teacher` (`math_tch_id`),
KEY `engl_teacher` (`en_tch_id`),
CONSTRAINT `class_ibfk_1` FOREIGN KEY (`head_tch_id`) REFERENCES `teacher` (`id`),
CONSTRAINT `class_ibfk_2` FOREIGN KEY (`ch_tch_id`) REFERENCES `teacher` (`id`),
CONSTRAINT `class_ibfk_3` FOREIGN KEY (`math_tch_id`) REFERENCES `teacher` (`id`),
CONSTRAINT `class_ibfk_4` FOREIGN KEY (`en_tch_id`) REFERENCES `teacher` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4;
--学生信息表
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '学生编号',
`name` varchar(50) DEFAULT NULL COMMENT '学生姓名',
`sex` enum('男','女') NOT NULL COMMENT '学生性别',
`age` int(11) DEFAULT NULL COMMENT '学生年龄',
`class_id` int(11) NOT NULL COMMENT '所属班级编号',
PRIMARY KEY (`id`),
KEY `student_ibfk_1` (`class_id`),
CONSTRAINT `student_ibfk_1` FOREIGN KEY (`class_id`) REFERENCES `class` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4;
package com.fxy.spring.entity;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
/**
* 抽象类
*/
public class BaseEntity {
protected Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Map toMap(){
Map map = new HashMap();
Field[] souceFields = this.getClass().getDeclaredFields();
for (Field souceField:souceFields){
souceField.setAccessible(true);
String name = souceField.getName();
Object val = null;
try {
val = souceField.get(this);
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
if (val != null && !Modifier.isFinal(souceField.getModifiers())){
map.put(name, val);
}
}
return map;
}
}
package com.fxy.spring.entity;
/**
* (Teacher)实体类
*/
public class Teacher extends BaseEntity{
private static final long serialVersionUID = -31170970333108858L;
/**
* 教师编号
*/
private Integer id;
/**
* 教师姓名
*/
private String name;
/**
* 教学科目
*/
private Object subject;
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;
}
public Object getSubject() {
return subject;
}
public void setSubject(Object subject) {
this.subject = subject;
}
@Override
public String toString() {
return "Teacher{" +
"id=" + id +
", name='" + name + '\'' +
", subject=" + subject +
'}';
}
}
package com.fxy.spring.entity;
import com.fxy.spring.entity.BaseEntity;
/**
* (Class)实体类
*
* @author fxy
* @since 2020-05-22 16:16:37
*/
public class Clazz extends BaseEntity {
private static final long serialVersionUID = -44200978485443168L;
/**
* 班级编号
*/
private Integer id;
/**
* 年级
*/
private Integer grade;
/**
* 班级号
*/
private Integer seqNum;
/**
* 班主任
*/
private Integer headTchId;
/**
* 语文老师
*/
private Integer chTchId;
/**
* 数学老师
*/
private Integer mathTchId;
/**
* 英语老师
*/
private Integer enTchId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getGrade() {
return grade;
}
public void setGrade(Integer grade) {
this.grade = grade;
}
public Integer getSeqNum() {
return seqNum;
}
public void setSeqNum(Integer seqNum) {
this.seqNum = seqNum;
}
public Integer getHeadTchId() {
return headTchId;
}
public void setHeadTchId(Integer headTchId) {
this.headTchId = headTchId;
}
public Integer getChTchId() {
return chTchId;
}
public void setChTchId(Integer chTchId) {
this.chTchId = chTchId;
}
public Integer getMathTchId() {
return mathTchId;
}
public void setMathTchId(Integer mathTchId) {
this.mathTchId = mathTchId;
}
public Integer getEnTchId() {
return enTchId;
}
public void setEnTchId(Integer enTchId) {
this.enTchId = enTchId;
}
@Override
public String toString() {
return "Clazz{" +
"id=" + id +
", grade=" + grade +
", seqNum=" + seqNum +
", headTchId=" + headTchId +
", chTchId=" + chTchId +
", mathTchId=" + mathTchId +
", enTchId=" + enTchId +
'}';
}
}
package com.fxy.spring.entity;
/**
* (Student)实体类
*/
public class Student extends BaseEntity{
private static final long serialVersionUID = 524746006785474092L;
/**
* 学生编号
*/
private Integer id;
/**
* 学生姓名
*/
private String name;
/**
* 学生性别
*/
private Object sex;
/**
* 学生年龄
*/
private Integer age;
/**
* 所属班级编号
*/
private Integer classId;
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;
}
public Object getSex() {
return sex;
}
public void setSex(Object sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getClassId() {
return classId;
}
public void setClassId(Integer classId) {
this.classId = classId;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", sex=" + sex +
", age=" + age +
", classId=" + classId +
'}';
}
}
<?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.fxy</groupId>
<artifactId>spring</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>spring Maven Webapp</name>
<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>
<spring.version>4.3.14.RELEASE</spring.version>
<asm.version>4.0</asm.version>
<cglib.version>3.0</cglib.version>
<commons-dbcp.version>1.4</commons-dbcp.version>
<logback.version>1.1.7</logback.version>
<slf4j.version>1.7.21</slf4j.version>
<redis.version>2.9.0</redis.version>
<spring.redis.version>1.8.23.RELEASE</spring.redis.version>
</properties>
<!--统一版本-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>${spring.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<!--logback日志-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<!--Spring IoC Start-->
<!-- Spring的核心工具包。-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<!--Spring IOC的基础实现,包含访问配置文件、创建和管理bean等。-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<!--Spring提供在基础IoC功能上的扩展服务,此外还提供许多企业级服务的支持,如邮件服务、任务调度、JNDI定位、EJB集成、远程访问、缓存以及各种视图层框架的封装等. -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<!-- Spring表达式语言. -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
</dependency>
<!--Spring IoC End-->
<!--Spring AOP Start-->
<!-- Spring的面向切面编程,提供AOP(面向切面编程)实现 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<!-- Spring提供的对AspectJ框架的整合 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<!-- aopalliance包是AOP联盟的API包,里面包含了针对面向切面的接口,使项目支持aop。SpringAOP接口是由AOP联盟定义接口拓展而来的 -->
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<!-- cglib依赖(spring依赖) -->
<!--<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>${asm.version}</version>
</dependency>-->
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-util</artifactId>
<version>${asm.version}</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>${cglib.version}</version>
<!--<exclusions>
<exclusion>
<artifactId>asm</artifactId>
<groupId>org.ow2.asm</groupId>
</exclusion>
</exclusions>-->
</dependency>
<!--Spring AOP End-->
<!--Spring 事务管理 Start-->
<!-- 对JDBC 的简单封装以及事务管理-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<!--Spring 事务管理 End-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!--开源数据源连接池c3p0-->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!--依赖common-pool对象池机制的数据库连接池-->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>${commons-dbcp.version}</version>
</dependency>
<!-- Druid是目前最好的数据库连接池,在功能、性能、扩展性方面,都超过其他数据库连接池,包括DBCP、C3P0、BoneCP、Proxool、JBoss DataSource。 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.5</version>
</dependency>
<!--mybatis start-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!--mybatis end-->
<!--ibatis start-->
<dependency>
<groupId>org.apache.ibatis</groupId>
<artifactId>ibatis-sqlmap</artifactId>
<version>2.3.4.726</version>
</dependency>
<!--spring 4以上移除了mybatis及ibatis的支持,mybatis与spring的整合由mybatis团队提供支持,但ibatis已无技术团队更新,所以只能使用spring 3的orm-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.13.RELEASE</version>
</dependency>
<!--ibatis end-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${redis.version}</version>
</dependency>
<!--spring-data-redis 2.0.0版本后spring版本要求5以上,因此此处选择1.x最后一个版本-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>${spring.redis.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.activemq/activemq-all -->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.15.12</version>
</dependency>
</dependencies>
</project>
Spring JDBC使用模板类JdbcTemplate、NamedParameterJdbcTemplate进行数据库操作。
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?serverTimezone=GMT&characterEncoding=utf-8
jdbc.username=root
jdbc.password=password
<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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:property-placeholder location="classpath:data/jdbc.properties"/>
<!--Spring的数据源实现类。仅仅是实现了javax.sql.DataSource,没有提供池技术,每次调用getConnection方法获取新连接时,只是简单地创建一个新连接
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"
/>-->
<!-- c3p0 连接池
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
-->
<!-- dbcp 连接池
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close"
p:driverClass="${jdbc.driverClassName}"
p:jdbcUrl="${jdbc.url}"
p:user="${jdbc.username}"
p:password="${jdbc.password}" />
-->
<!--Druid 连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"/>
</beans>
<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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource"/>
</beans>
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"classpath:data/spring-datasource.xml", "classpath:data/jdbc/spring-dao-origin.xml"});
JdbcTemplate jdbcTemplate = (JdbcTemplate)context.getBean("jdbcTemplate");
List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from Class");
System.out.println(list.toString());
}
[{id=1, grade=7, seq_num=1, head_tch_id=2, ch_tch_id=4, math_tch_id=2, en_tch_id=3}, {id=10, grade=7, seq_num=2, head_tch_id=null, ch_tch_id=null, math_tch_id=null, en_tch_id=null}]
生成StudentDao.java,ClazzDao.java,实现学生表、班级表新增操作,新建ManagerService,调用StudentDao和ClazzDao的新增方法,并纳入事务管理。
package com.fxy.spring.data.jdbc;
import com.fxy.spring.entity.BaseEntity;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*实现基本数据库操作的父类
*/
public class BaseDao {
NamedParameterJdbcTemplate template;
String addSql;
String updateSql;
String deleteSql;
String querySql;
public <T extends BaseEntity> T insert(T t){
// 获取自增主键
KeyHolder keyHolder = new GeneratedKeyHolder();
Map paramMap = getParamMap(t);
template.update(addSql, (SqlParameterSource)(new MapSqlParameterSource(paramMap)),keyHolder);
t.setId(keyHolder.getKey().intValue());
return t;
}
public <T extends BaseEntity> Integer update(T t){
Map paramMap = getParamMap(t);
int updateNum = template.update(updateSql, paramMap);
return updateNum;
}
public <T extends BaseEntity> Integer delete(T t){
Map paramMap = getParamMap(t);
int deleteNum = template.update(deleteSql, paramMap);
return deleteNum;
}
public <T extends BaseEntity> List<Map> query(T t){
Map paramMap = getParamMap(t);
List list = template.queryForList(querySql, paramMap);
return list;
}
public Map getParamMap(Object o){
Map paramMap = new HashMap();
Field[] fields = o.getClass().getDeclaredFields();
for (Field field:fields){
field.setAccessible(true);
try {
paramMap.put(field.getName(), field.get(o));
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
return paramMap;
}
public NamedParameterJdbcTemplate getTemplate() {
return template;
}
public void setTemplate(NamedParameterJdbcTemplate template) {
this.template = template;
}
}
package com.fxy.spring.data.jdbc;
import org.springframework.stereotype.Repository;
@Repository
public class ClazzDao extends BaseDao{
public String addSql = "insert into class(grade,seq_num,head_tch_id,ch_tch_id,math_tch_id,en_tch_id) values (:grade,:seqNum,:headTchId,:chTchId,:mathTchId,:enTchId)";
public String updateSql ="update class set name=:name where id = :id";;
public String deleteSql = "delete from class where id = :id";
public String querySql = "select * from class where (grade = :grade or :grade is null) and (seq_num = :seqNum or :seqNum is null)";
public ClazzDao() {
super.addSql= addSql;
super.updateSql = updateSql;
super.deleteSql = deleteSql;
super.querySql = querySql;
}
}
package com.fxy.spring.data.jdbc;
public class StudentDao extends BaseDao{
String addSql = "insert into student(name,sex,age,class_id) VALUES(:name,:sex,:age,:classId)";
String updateSql ="UPDATE student set name=:name,sex=:sex,age=:age,class_id=:classId where id=:id";;
String deleteSql = "delete from student where id = :id";
String querySql = "select * from student where (id = :id or :id is null)";
public StudentDao() {
super.addSql= addSql;
super.updateSql = updateSql;
super.deleteSql = deleteSql;
super.querySql = querySql;
}
}
package com.fxy.spring.data.jdbc;
import com.fxy.spring.entity.Clazz;
import com.fxy.spring.entity.Student;
import java.util.List;
import java.util.Map;
public class ManagerService {
private StudentDao studentDao;
private ClazzDao clazzDao;
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
public void setClazzDao(ClazzDao clazzDao) {
this.clazzDao = clazzDao;
}
public void add(Clazz clazz, Student student){
List<Map> result = clazzDao.query(clazz);
if (result.size() == 0){
clazzDao.insert(clazz);
}else {
int id = (Integer)result.get(0).get("id");
clazz.setId(id);
}
student.setClassId(clazz.getId());
//外键设置为不存在的值,触发异常来观察事物管理
student.setClassId(1123);
studentDao.insert(student);
}
}
<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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource"/>
<bean id="namedParameterJdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource"/>
</bean>
<bean id="baseDao" class="com.fxy.spring.data.jdbc.BaseDao">
<property name="template" ref="namedParameterJdbcTemplate"/>
</bean>
<bean id="classDao" class="com.fxy.spring.data.jdbc.ClazzDao" parent="baseDao"/>
<bean id="studentDao" class="com.fxy.spring.data.jdbc.StudentDao" parent="baseDao"/>
<bean id="managerService" class="com.fxy.spring.data.jdbc.ManagerService" p:clazzDao-ref="classDao" p:studentDao-ref="studentDao"/>
</beans>
/**
* 无事务管理测试
* 班级信息写入后,学生信息写入发生异常失败,对班级信息写入无影响
*/
@Test
public void testNotInTransaction(){
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"classpath:data/spring-datasource.xml", "classpath:data/jdbc/spring-dao-origin.xml"});
ManagerService managerService = context.getBean(ManagerService.class);
Clazz clazz = new Clazz();
clazz.setGrade(7);
clazz.setSeqNum(2);
Student student = new Student();
student.setName("张三");
student.setAge(7);
student.setSex("男");
managerService.add(clazz,student);
}
StudentDao抛出异常,但查看Class表,数据仍然成功写入。接下来引入事务管理。
方式一:需要为每个类配置代理
方式二:每个类继承TransactionProxyFactoryBean的配置
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<!--对数据源进行代理,使数据源具有感知事务上下文的能力,当某些场景下显示获取数据库连接时,保证获取到的连接是绑定了当前事务的连接(和通过DataSourceUtils.getConnection()获取连接的效果一致)-->
<bean id="dataSourceProxy" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy"
p:targetDataSource-ref="dataSource"/>
<!--声明式事务管理器-->
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSourceProxy"/>
<bean id="namedParameterJdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSourceProxy"/>
</bean>
<bean id="baseDao" class="com.fxy.spring.data.jdbc.BaseDao">
<property name="template" ref="namedParameterJdbcTemplate"/>
</bean>
<bean id="classDao" class="com.fxy.spring.data.jdbc.ClazzDao" parent="baseDao"/>
<bean id="studentDao" class="com.fxy.spring.data.jdbc.StudentDao" parent="baseDao"/>
<!--利用事务代理工厂TransactionProxyFactoryBean进行事务代理1 start-->
<!--需要为每个类进行代理配置,很麻烦-->
<!--
<bean id="managerServiceTarget" class="com.fxy.spring.data.jdbc.ManagerService" p:classDao-ref="classDao" p:studentDao-ref="studentDao"/>
<bean id="managerService"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
p:transactionManager-ref="txManager"
p:target-ref="managerServiceTarget">
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED,-tion</prop>
</props>
</property>
</bean>-->
<!--利用事务代理工厂TransactionProxyFactoryBean进行事务代理1 end-->
<!--利用事务代理工厂TransactionProxyFactoryBean进行事务代理2 start -->
<!--每个bean继承父事务代理工厂的配置即可,简化了配置 -->
<bean id="transactionProxy"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true"
p:transactionManager-ref="txManager">
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED,-tion</prop>
</props>
</property>
</bean>
<bean id="managerService" parent="transactionProxy">
<property name="target">
<bean class="com.fxy.spring.data.jdbc.ManagerService" p:clazzDao-ref="classDao" p:studentDao-ref="studentDao"/>
</property>
</bean>
<!--利用事务代理工厂TransactionProxyFactoryBean进行事务代理2 end -->
</beans>
/**
* 事务管理测试
*/
@Test
public void testInTransaction1(){
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"classpath:data/spring-datasource.xml","classpath:data/spring-transaction-pfb.xml"});
ManagerService managerService = (ManagerService)context.getBean("managerService");
Clazz clazz = new Clazz();
clazz.setGrade(7);
clazz.setSeqNum(2);
Student student = new Student();
student.setName("张三");
student.setAge(7);
student.setSex("男");
managerService.add(clazz,student);
}
StudentDao新增发生异常,ClassDao的写入操作也被回滚
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
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.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!--对数据源进行代理,使数据源具有感知事务上下文的能力,当某些场景下显示获取数据库连接时,保证获取到的连接是绑定了当前事务的连接(和通过DataSourceUtils.getConnection()获取连接的效果一致)-->
<bean id="dataSourceProxy" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy"
p:targetDataSource-ref="dataSource"/>
<!--声明式事务管理器-->
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSourceProxy"/>
<!--基于schema的自动代理-->
<aop:config>
<!--切点 匹配com.fxy.spring.data子包下的所有方法-->
<aop:pointcut id="serviceMethod"
expression="execution(* com.fxy.spring.data..*.*(..))"/>
<!--切面-->
<aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice"/>
</aop:config>
<!--增强 新增变更删除方法 遇到检查型异常和非检查型异常均回滚-->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="query*" read-only="true"/>
<tx:method name="add*" rollback-for="Exception"/>
<tx:method name="update*" rollback-for="Exception"/>
<tx:method name="delete*" rollback-for="Exception"/>
</tx:attributes>
</tx:advice>
</beans>
<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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<bean id="namedParameterJdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSourceProxy"/>
</bean>
<bean id="baseDao" class="com.fxy.spring.data.jdbc.BaseDao">
<property name="template" ref="namedParameterJdbcTemplate"/>
</bean>
<bean id="classDao" class="com.fxy.spring.data.jdbc.ClazzDao" parent="baseDao"/>
<bean id="studentDao" class="com.fxy.spring.data.jdbc.StudentDao" parent="baseDao"/>
<bean id="managerService" class="com.fxy.spring.data.jdbc.ManagerService" p:clazzDao-ref="classDao" p:studentDao-ref="studentDao"/>
</beans>
/**
* 事务管理测试
*/
@Test
public void testInTransaction2(){
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"classpath:data/spring-datasource.xml","classpath:data/spring-transaction.xml","classpath:data/jdbc/spring-dao.xml"});
ManagerService managerService = (ManagerService)context.getBean("managerService");
Clazz clazz = new Clazz();
clazz.setGrade(7);
clazz.setSeqNum(2);
Student student = new Student();
student.setName("张三");
student.setAge(7);
student.setSex("男");
managerService.add(clazz,student);
}
StudentDao新增发生异常,ClassDao的写入操作也被回滚
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map-2.dtd">
<sqlMap namespace="Clazz">
<typeAlias alias="Clazz" type="com.fxy.spring.entity.Clazz"/>
<!--查询单个-->
<select id="getList" parameterClass="map" resultClass="Clazz">
select
id as id ,
grade as grade ,
seq_num as seqNum ,
head_tch_id as headTchId ,
ch_tch_id as chTchId ,
math_tch_id as mathTchId ,
en_tch_id as enTchId
from class A
where 1=1
<isNotEmpty prepend="AND" property="id"> A.id = #id# </isNotEmpty>
<isNotEmpty prepend="AND" property="grade"> A.grade = #grade# </isNotEmpty>
<isNotEmpty prepend="AND" property="seqNum"> A.seq_num = #seqNum# </isNotEmpty>
<isNotEmpty prepend="AND" property="headTchId"> A.head_tch_id = #headTchId# </isNotEmpty>
<isNotEmpty prepend="AND" property="chTchId"> A.ch_tch_id = #chTchId# </isNotEmpty>
<isNotEmpty prepend="AND" property="mathTchId"> A.math_tch_id = #mathTchId# </isNotEmpty>
<isNotEmpty prepend="AND" property="enTchId"> A.en_tch_id = #enTchId# </isNotEmpty>
</select>
<select id="get" parameterClass="map" resultClass="Clazz">
select
id as id,
grade as grade,
seq_num as seqNum,
head_tch_id as headTchId,
ch_tch_id as chTchId,
math_tch_id as mathTchId,
en_tch_id as enTchId
from class A
where id = #id#
</select>
<!--新增所有列-->
<insert id="insert" parameterClass="map">
insert into class(id, grade, seq_num, head_tch_id, ch_tch_id, math_tch_id, en_tch_id)
values (#id# , #grade# , #seqNum# , #headTchId# , #chTchId# , #mathTchId# , #enTchId# )
</insert>
<!--通过主键修改数据-->
<update id="update" parameterClass="map">
update class
set
grade = #grade# ,
seq_num = #seqNum# ,
head_tch_id = #headTchId# ,
ch_tch_id = #chTchId# ,
math_tch_id = #mathTchId# ,
en_tch_id = #enTchId#
where id = #id#
</update>
<!-- 通过主键修改设定了值(不含null和"")的字段 -->
<update id="updateNotEmpty" parameterClass="map">
update class
<dynamic prepend="SET">
<isNotEmpty prepend="," property="grade"> grade = #grade# </isNotEmpty>
<isNotEmpty prepend="," property="seqNum"> seq_num = #seqNum# </isNotEmpty>
<isNotEmpty prepend="," property="headTchId"> head_tch_id = #headTchId# </isNotEmpty>
<isNotEmpty prepend="," property="chTchId"> ch_tch_id = #chTchId# </isNotEmpty>
<isNotEmpty prepend="," property="mathTchId"> math_tch_id = #mathTchId# </isNotEmpty>
<isNotEmpty prepend="," property="enTchId"> en_tch_id = #enTchId# </isNotEmpty>
</dynamic>
where id = #id#
</update>
<!--通过主键删除-->
<delete id="delete" parameterClass="map">
delete from class where id = #id#
</delete>
</sqlMap>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<!--cacheModelsEnabled 是否启用SqlMapClient上的缓存机制。建议设为"true" -->
<!--enhancementEnabled 是否针对POJO启用字节码增强机制以提升getter/setter的调用效能,避免使用JavaReflect所带来的性能开销。同时,这也为Lazy Loading带来了极大的性能提升。建议设为"true" -->
<!--errorTracingEnabled 是否启用错误日志,在开发期间建议设为"true"以方便调试 -->
<settings
useStatementNamespaces="true"
cacheModelsEnabled="true"
enhancementEnabled="true"
errorTracingEnabled="true"
/>
<sqlMap resource="data/orm/ibatis/sqlmap/Clazz.xml" />
</sqlMapConfig>
<?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="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocations">
<list>
<value>classpath:data/orm/ibatis/sqlMapConfig.xml</value>
</list>
</property>
<property name="dataSource" ref="dataSourceProxy"/>
</bean>
<bean id="baseIbatisDao" class="com.fxy.spring.data.orm.ibatis.BaseIbatisDao">
<property name="sqlMapClient" ref="sqlMapClient"/>
</bean>
</beans>
package com.fxy.spring.data.orm.ibatis;
import com.fxy.spring.entity.BaseEntity;
import com.ibatis.sqlmap.client.SqlMapClient;
import java.sql.SQLException;
import java.util.List;
public class BaseIbatisDao {
SqlMapClient sqlMapClient;
public SqlMapClient getSqlMapClient() {
return sqlMapClient;
}
public void setSqlMapClient(SqlMapClient sqlMapClient) {
this.sqlMapClient = sqlMapClient;
}
public <T extends BaseEntity> T get(T t){
String nameSpace = getNameSpace(t);
T result = null;
try {
result = (T)sqlMapClient.queryForObject(nameSpace + ".get", t.toMap());
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return result;
}
public <T extends BaseEntity> List<T> getList(T t){
String nameSpace = getNameSpace(t);
List<T> list = null;
try {
list = sqlMapClient.queryForList(nameSpace + ".getList", t.toMap());
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return list;
}
public <T extends BaseEntity> Integer insert(T t){
String nameSpace = getNameSpace(t);
Integer num = null;
try {
num = (Integer)sqlMapClient.insert(nameSpace + ".insert", t.toMap());
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return num;
}
public <T extends BaseEntity> Integer update(T t){
String nameSpace = getNameSpace(t);
Integer num = 0;
try {
num = sqlMapClient.update(nameSpace + ".update", t.toMap());
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return num;
}
public <T extends BaseEntity> Integer updateNotEmpty(T t){
String nameSpace = getNameSpace(t);
Integer num = 0;
try {
num = sqlMapClient.update(nameSpace + ".updateNotEmpty", t.toMap());
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return num;
}
public <T extends BaseEntity> Integer delete(T t){
String nameSpace = getNameSpace(t);
Integer num = null;
try {
num = (Integer)sqlMapClient.insert(nameSpace + ".delete", t.toMap());
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return num;
}
public String getNameSpace(Object obj){
String simpleName = obj.getClass().getSimpleName();
return simpleName;
}
}
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"classpath:data/spring-datasource.xml","classpath:data/spring-transaction.xml", "classpath:data/orm/ibatis/spring-ibatis.xml"});
BaseIbatisDao baseIbatisDao = context.getBean(BaseIbatisDao.class);
List<Clazz> clazzes = baseIbatisDao.getList(new Clazz());
System.out.println(clazzes.toString());
}
[Clazz{id=1, grade=7, seqNum=1, headTchId=2, chTchId=4, mathTchId=2, enTchId=3}, Clazz{id=10, grade=7, seqNum=2, headTchId=null, chTchId=null, mathTchId=null, enTchId=null}]
<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-4.0.xsd">
<!-- spring和MyBatis完美整合 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSourceProxy"/>
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:data/orm/mybatis/mapper/*.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.fxy.spring.data.orm.mybatis"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
</beans>
<?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.fxy.spring.data.orm.mybatis.ClazzMapper">
<resultMap type="com.fxy.spring.entity.Clazz" id="ClassMap">
<result property="id" column="id" jdbcType="INTEGER"/>
<result property="grade" column="grade" jdbcType="INTEGER"/>
<result property="seqNum" column="seq_num" jdbcType="INTEGER"/>
<result property="headTchId" column="head_tch_id" jdbcType="INTEGER"/>
<result property="chTchId" column="ch_tch_id" jdbcType="INTEGER"/>
<result property="mathTchId" column="math_tch_id" jdbcType="INTEGER"/>
<result property="enTchId" column="en_tch_id" jdbcType="INTEGER"/>
</resultMap>
<!--查询单个-->
<select id="queryById" resultMap="ClassMap">
select
id, grade, seq_num, head_tch_id, ch_tch_id, math_tch_id, en_tch_id
from Class
where id = #{id}
</select>
<!--查询指定行数据-->
<select id="queryAllByLimit" resultMap="ClassMap">
select
id, grade, seq_num, head_tch_id, ch_tch_id, math_tch_id, en_tch_id
from Class
limit #{offset}, #{limit}
</select>
<!--通过实体作为筛选条件查询-->
<select id="queryAll" resultMap="ClassMap">
select
id, grade, seq_num, head_tch_id, ch_tch_id, math_tch_id, en_tch_id
from Class
<where>
<if test="id != null">
and id = #{id}
</if>
<if test="grade != null">
and grade = #{grade}
</if>
<if test="seqNum != null">
and seq_num = #{seqNum}
</if>
<if test="headTchId != null">
and head_tch_id = #{headTchId}
</if>
<if test="chTchId != null">
and ch_tch_id = #{chTchId}
</if>
<if test="mathTchId != null">
and math_tch_id = #{mathTchId}
</if>
<if test="enTchId != null">
and en_tch_id = #{enTchId}
</if>
</where>
</select>
<!--新增所有列-->
<insert id="insert" keyProperty="id" useGeneratedKeys="true">
insert into test.class(grade, seq_num, head_tch_id, ch_tch_id, math_tch_id, en_tch_id)
values (#{grade}, #{seqNum}, #{headTchId}, #{chTchId}, #{mathTchId}, #{enTchId})
</insert>
<!--通过主键修改数据-->
<update id="update">
update Class
<set>
<if test="grade != null">
grade = #{grade},
</if>
<if test="seqNum != null">
seq_num = #{seqNum},
</if>
<if test="headTchId != null">
head_tch_id = #{headTchId},
</if>
<if test="chTchId != null">
ch_tch_id = #{chTchId},
</if>
<if test="mathTchId != null">
math_tch_id = #{mathTchId},
</if>
<if test="enTchId != null">
en_tch_id = #{enTchId},
</if>
</set>
where id = #{id}
</update>
<!--通过主键删除-->
<delete id="deleteById">
delete from Class where id = #{id}
</delete>
</mapper>
package com.fxy.spring.data.orm.mybatis;
import com.fxy.spring.entity.Clazz;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface ClazzMapper {
public Clazz queryById(@Param("id") String id);
public List<Clazz> queryAllByLimit(@Param("offset") String offset,@Param("limit") String limit);
public List<Clazz> queryAll(Clazz clazz);
public int insert(Clazz clazz);
public int update(Clazz clazz);
public int deleteById(Clazz clazz);
}
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"classpath:data/spring-datasource.xml","classpath:data/spring-transaction.xml", "classpath:data/orm/mybatis/spring-mybatis.xml"});
ClazzMapper clazzMapper = context.getBean(ClazzMapper.class);
List<Clazz> clazzes = clazzMapper.queryAll(null);
System.out.println(clazzes.size());
}
<?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-4.0.xsd">
<!-- 配置能够产生connection的connectionfactory,由JMS对应的服务厂商提供 -->
<bean id="tagertConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<constructor-arg name="brokerURL" value="tcp://127.0.0.1:61616"/>
</bean>
<!-- 配置spring管理真正connectionfactory的connectionfactory,相当于spring对connectionfactory的一层封装 -->
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
<property name="targetConnectionFactory" ref="tagertConnectionFactory"/>
</bean>
<!-- 配置生产者 -->
<!-- Spring使用JMS工具类,可以用来发送和接收消息 -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<!-- 这里是配置的spring用来管理connectionfactory的connectionfactory -->
<property name="connectionFactory" ref="connectionFactory"/>
</bean>
<!-- 配置destination -->
<!-- 队列目的地 -->
<bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="spring-queue"/>
</bean>
<!-- 话题目的地 -->
<bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg value="spring-topic"/>
</bean>
</beans>
package jms.activemq;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.jms.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:jms/activemq/spring-activemq-producer.xml" })
public class SpringAMQProducerTest {
@Autowired
JmsTemplate jmsTemplate;
@Autowired
Queue queue;
@Autowired
Topic topic;
@Test
public void sendToQueue(){
/*jmsTemplate.send(queue, new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
TextMessage textMessage = session.createTextMessage("付雄跃测试");
return textMessage;
}
});*/
MessageCreator messageCreator = (Session session) -> session.createTextMessage("test queue");
jmsTemplate.send(queue, messageCreator);
}
@Test
public void sendToTopic(){
MessageCreator messageCreator = (Session session) -> session.createTextMessage("test topic");
jmsTemplate.send(topic, messageCreator);
}
}
package com.fxy.spring.jms.activemq.spring;
import org.springframework.jms.core.JmsTemplate;
import javax.jms.*;
public class SpringConsumer implements MessageListener {
@Override
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println(textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
}
<?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:jms="http://www.springframework.org/schema/jms"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.0.xsd">
<!-- 配置能够产生connection的connectionfactory,由JMS对应的服务厂商提供 -->
<bean id="tagertConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<constructor-arg name="brokerURL" value="tcp://127.0.0.1:61616"/>
</bean>
<!-- 配置spring管理真正connectionfactory的connectionfactory,相当于spring对connectionfactory的一层封装 -->
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
<property name="targetConnectionFactory" ref="tagertConnectionFactory"/>
</bean>
<!-- 配置生产者 -->
<!-- Spring使用JMS工具类,可以用来发送和接收消息 -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<!-- 这里是配置的spring用来管理connectionfactory的connectionfactory -->
<property name="connectionFactory" ref="connectionFactory"/>
</bean>
<!-- 配置destination -->
<!-- 队列目的地 -->
<bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="spring-queue"/>
</bean>
<!-- 话题目的地 -->
<bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg value="spring-topic"/>
</bean>
<bean id="springConsumer" class="com.fxy.spring.jms.activemq.spring.SpringConsumer"/>
<!--配置消息监听器方式1-->
<!--<bean class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="destination" ref="topicDestination"/>
<property name="messageListener" ref="springConsumer"/>
</bean>-->
<!--配置消息监听器方式2-->
<!--<bean id="listenerContainer" class="org.springframework.jms.listener.SimpleMessageListenerContainer">
<property name="connectionFactory" ref="tagertConnectionFactory" />
<property name="destination" ref="topicDestination" />
<property name="messageListener" ref="springConsumer" />
</bean>-->
<!--配置消息监听器方式3 可配置多个监听器-->
<jms:listener-container destination-type="topic" connection-factory="connectionFactory">
<jms:listener destination="spring-topic" ref="springConsumer"/>
</jms:listener-container>
<jms:listener-container destination-type="queue" connection-factory="connectionFactory">
<jms:listener destination="spring-queue" ref="springConsumer"/>
</jms:listener-container>
</beans>
package jms.activemq;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.jms.Queue;
import javax.jms.Topic;
import java.io.IOException;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:jms/activemq/spring-activemq-consumer.xml" })
public class SpringAMQConsumerTest {
@Test
public void listenQueue(){
try {
int read = System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
}