快捷搜索:

在EJB中测试JTA

1、首先在jboss 中mysql-ds.xml的设置设置设备摆设摆设文件中设置设置设备摆设摆设二个数据源

MySqlDS

jdbc:mysql://localhost:3306/ejb

com.mysql.jdbc.Driver

root

admin

org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter

mySQL

MySqlDS2

jdbc:mysql://localhost:3306/ejb2

com.mysql.jdbc.Driver

root

admin

org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter

mySQL

2、在建立好的ejb项目中的persistence.xml设置设置设备摆设摆设文件中做好响应的设置设置设备摆设摆设

java:/MySqlDS

com.bjsxt.jpa.Person

true

java:/MySqlDS2

com.bjsxt.jpa.User

true

3、详细编码

//为了测试不合的事物,下面编写了2个实体类

import java.io.Serializable;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

@Entity

public class Person implements Serializable{

@Id

@GeneratedValue

private int id;

private String name;

public int getId() {

return id;

}

public String getName() {

return name;

}

public void setId(int id) {

this.id = id;

}

public void setName(String name) {

this.name = name;

}

}

import java.io.Serializable;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

@Entity

public class User implements Serializable{

@Id

@GeneratedValue

private int id;

private String name;

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 interface PersonService {

public void add(Person p, User u);

}

//编写实现

import javax.ejb.Local;

import javax.ejb.Remote;

import javax.ejb.Stateless;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

@Stateless

@Remote

@Local

public class PersonServiceImpl implements PersonService {

//留意:下面的add措施中存储的二个工具是放在两个不合的数据库中的

@PersistenceContext(unitName="test")

private EntityManager entityManager;

@PersistenceContext(unitName="test2")

private EntityManager entityManager2;

public void add(Person p, User u) {

entityManager.persist(p);

entityManager2.persist(u);

//在此抛出一个非常,看事物能否回滚、

throw new RuntimeException("Error"); }

}

//客户端调用

import javax.naming.InitialContext;

import com.bjsxt.jpa.Person;

import com.bjsxt.jpa.PersonService;

import com.bjsxt.jpa.User;

public class Client {

public static void main(String[] args) throws Exception{

InitialContext ctx = new InitialContext();

PersonService ps = (PersonService)ctx.lookup("PersonServiceImpl/remote");

Person p = new Person();

p.setName("张三");

User u = new User();

u.setName("李四");

ps.add(p, u);

}

}

实验结果:在add措施中假如不抛出非常,那么二个数据库中的数据都能添加成功,而假如在在二个措施中有一个呈现差错,事物便会回滚包管事物的同等性。

您可能还会对下面的文章感兴趣: