spring-data-jpa通过Atomikos实现JTA事务

阅读更多

最近刚搭建一个Atomikos实现的JTA,数据库持久层用的spring-data-jpa,底层实现是Hibernate。

一.环境

spring 3.2.6.RELEASE

hibernate 4.2.8.Final

spring-data-jpa 1.4.3.RELEASE

atomikos.version 3.9.2

 

永久链接: http://sgq0085.iteye.com/blog/2001918

 

atomikos在Maven环境中导入依赖如下



    com.atomikos
    transactions-jdbc
    3.9.2


    com.atomikos
    transactions-hibernate3
    3.9.2


    javax.transaction
    jta
    1.1

 

atomikos依赖结构如下

[INFO] +- com.atomikos:transactions-jdbc:jar:3.9.2:compile
[INFO] |  \- com.atomikos:transactions-jta:jar:3.9.2:compile
[INFO] |     \- com.atomikos:transactions:jar:3.9.2:compile
[INFO] |        \- com.atomikos:transactions-api:jar:3.9.2:compile
[INFO] |           \- com.atomikos:atomikos-util:jar:3.9.2:compile
[INFO] +- com.atomikos:transactions-hibernate3:jar:3.9.2:compile
[INFO] +- javax.transaction:jta:jar:1.1:compile

 

 

二.配置

1.web.xml

  spring.profiles.default为了配合配置文件applicationContext.xml中标签,用于管理多套环境

 


    spring.profiles.default
    development



    contextConfigLocation
    
        classpath*:/applicationContext.xml
    



 
    openEntityManagerInViewFilter
    org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
    
        entityManagerFactoryBeanName
        entityManagerFactory1
    


    openEntityManagerInViewFilter
    /*
 

 

2.persistence.xml

 

  
  
      
      
      
      
  
 

 这里JPA 不在 persistence.xml 文件中配置每个Entity实体类,在后面的applicationContext.xml中通过去扫描所有标记@Entity注解的PO。

 

3.application.properties

数据库一个Oracle,一个H2

 

#development
dev.jdbc.driver=oracle.jdbc.driver.OracleDriver
dev.jdbc.url=jdbc:oracle:thin:@192.168.3.129:1521:gtf
dev.jdbc.username=my_app
dev.jdbc.password=my_app

dev.jdbc.driver2=org.h2.jdbcx.JdbcDataSource
dev.jdbc.url2=jdbc:h2:file:~/.h2/myapp;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSE
dev.jdbc.username2=sa
dev.jdbc.password2=

databasePlatform.oracle=org.hibernate.dialect.Oracle10gDialect
databasePlatform.h2=org.hibernate.dialect.H2Dialect
 

 

4.applicationContext.xml



    
    Spring公共配置

    
    
        
        
    

    
        
    

    
        
        
    

    
    
        
        
        
    

    
    

    
    

    
        
        
            
                
            
        
        
        
        
    

    
    
        
        
        
        
        
        
            
                
                false
                false
                after_statement
                
                org.hibernate.cfg.ImprovedNamingStrategy
                true
                none
                oracle.jdbc.xa.client.OracleXADataSource
                jta
                com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup
            
        
    

    
    

    
    
        
        
        
        
        
        
            
                
                false
                false
                after_statement
                
                org.hibernate.cfg.ImprovedNamingStrategy
                true
                none
                oracle.jdbc.xa.client.OracleXADataSource
                jta
                com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup
            
        
    

    
    

    
    
        

        
        
            
            
            
                
                    ${dev.jdbc.url}
                    ${dev.jdbc.username}
                    ${dev.jdbc.password}
                
            
            
            
            
        

        
        
            
            
            
                
                    ${dev.jdbc.url2}
                    ${dev.jdbc.username2}
                    ${dev.jdbc.password2}
                
            
            
            
            
        
    

 

 

 

 

注意:

1.Entity可以被两个EntityManagerFactory同时扫描到

2.通过jpa:repositories的base-package来区分两个EntityManagerFactory维护的持久层在这里这个用dao包,另一个用repository

 

三.测试

 

-------------- 表1 ------------
create table jta_pu1 (
	id char(32),
	description varchar2(255),
    primary key (id)
);

-------------- 表2 ------------
create table jta_pu2 (
	id char(32),
	description varchar2(255),
    primary key (id)
);

 

 

在Oracle中建表1

在H2中表1和表2都建

 

三个Entity类

 

package com.myapp.jta.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

import org.hibernate.annotations.GenericGenerator;

@MappedSuperclass
public abstract class BaseEntity implements Serializable {

	private static final long serialVersionUID = 1L;
	protected String id;

	@Id
	@Column(name = "id", nullable = false)
	@GeneratedValue(generator = "system-uuid")
	@GenericGenerator(name = "system-uuid", strategy = "uuid")
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
}
 

 

 

package com.myapp.jta.entity;

import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = "JTA_PU1")
public class PU1 extends BaseEntity {

    private String description;

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}
 

 

 

package com.myapp.jta.entity;

import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = "JTA_PU2")
public class PU2 extends BaseEntity {

    private String description;

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}
 

 

三个数据库持久层类

对应数据源一

 

package com.myapp.jta.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.myapp.jta.entity.PU1;

public interface PU1Dao extends JpaRepository {

}
 

 

对应数据源二

 

package com.myapp.jta.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.myapp.jta.entity.PU1;

public interface PU1Repository extends JpaRepository {

}
 
package com.myapp.jta.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.myapp.jta.entity.PU2;

public interface PU2Repository extends JpaRepository {

}
 

 

注意源一对应的包名是dao,源二对应的包名是repository

 

Service比较简单只有一个save,第一次不抛出异常,第二次抛出异常来测试事务回滚。

package com.myapp.jta.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.myapp.jta.dao.PU1Dao;
import com.myapp.jta.entity.PU1;
import com.myapp.jta.entity.PU2;
import com.myapp.jta.repository.PU1Repository;
import com.myapp.jta.repository.PU2Repository;

@Service
@Transactional
public class JTAService {

    @Value("${property.value}")
    private String propertyValue;

    @Autowired
    private PU1Dao pu1Dao;

    @Autowired
    private PU1Repository pu1Repository;

    @Autowired
    private PU2Repository pu2Repository;

    public void save() {
        PU1 pu = new PU1();
        pu.setDescription(propertyValue);
        pu1Dao.save(pu);
        pu1Repository.save(pu);

        PU2 pu2 = new PU2();
        pu2.setDescription("pu2");
        pu2Repository.save(pu2);
        // throw new RuntimeException();
    }
}

 

JUnit4的测试用例

package com.myapp.jta.service;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext.xml"})
@ActiveProfiles("development")
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
public class JTAServiceTest {

    @Autowired
    private JTAService jtaService;

    @Test
    public void savePU1() {
        jtaService.save();
    }
}

 

说明,同一个EntityPU1分别被保存到数据源一和数据源二中,但通过查询数据库可以看到第一次保存的时候id被赋值,第二次保存的时候id没有再做修改。但查询数据库,发现第二次的id与第一次的不同。所以真有同一个Entity保存到两个数据库中的需求时,推荐在保存之前深拷贝一份出来,分别保存。 

 

永久链接: http://sgq0085.iteye.com/blog/2001918

 

注意两个离奇错误

错误1: 数据库必须是DBA,否则出错 (具体哪个权限没有去排查,感兴趣找到了告诉我)

错误2:用maven tomcat7-maven-plugin插件时小心useTestClasspath需要是false

 

DEMO中在使用jdbcdslog的基础上,修改Atomikos核心类,实现JTA管理数据源下SQL的输出。

注意:该方法未经过大量测试,只适用于开发环境,生产环境不可以使用。

你可能感兴趣的:(atomikos,jta,spring-data-jpa,hibernate,jdbcdslog)