官术网_书友最值得收藏!

How to do it...

You need to perform the following steps to complete this recipe:

  1. First, we need to create our persistence unit (at persistence.xml):
    <persistence-unit name="ch02-jta-pu" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>

<jta-data-source>userDb</jta-data-source>
<non-jta-data-source>userDbNonJta</non-jta-data-source>

<exclude-unlisted-classes>false</exclude-unlisted-classes>

<properties>
<property name="javax.persistence.schema-
generation.database.action"
value="create"/>
</properties>
</persistence-unit>
  1. Then, we need to create a User class as an entity (@Entity):
@Entity
public class User implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String name;
private String email;

protected User() {
}

public User(Long id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}

//DO NOT FORGET TO IMPLEMENT THE GETTERS AND SETTERS
}
  1. We also need a Jakarta Enterprise Bean (formerly EJB) to perform the operations over the User entity:
@Stateful
public class UserBean {

@PersistenceContext(unitName = "ch02-jta-pu",
type = PersistenceContextType.EXTENDED)
private EntityManager em;

public void add(User user){
em.persist(user);
}

public void update(User user){
em.merge(user);
}

public void remove(User user){
em.remove(user);
}

public User findById(Long id){
return em.find(User.class, id);
}
}
  1. Then, we need to create our unit test:
public class Ch02JtaTest {

private EJBContainer ejbContainer;

@EJB
private UserBean userBean;

public Ch02JtaTest() {
}

@Before
public void setUp() throws NamingException {
Properties p = new Properties();
p.put("userDb", "new://Resource?type=DataSource");
p.put("userDb.JdbcDriver", "org.hsqldb.jdbcDriver");
p.put("userDb.JdbcUrl", "jdbc:hsqldb:mem:userdatabase");

ejbContainer = EJBContainer.createEJBContainer(p);
ejbContainer.getContext().bind("inject", this);
}

@After
public void tearDown() {
ejbContainer.close();
}

@Test
public void validTransaction() throws Exception{
User user = new User(null, "Elder Moraes",
"elder@eldermoraes.com");

userBean.add(user);
user.setName("John Doe");
userBean.update(user);

User userDb = userBean.findById(1L);
assertEquals(userDb.getName(), "John Doe");

}

}
主站蜘蛛池模板: 龙陵县| 东方市| 上思县| 调兵山市| 临海市| 安国市| 锦屏县| 闸北区| 连南| 崇礼县| 富源县| 长宁区| 洞口县| 如东县| 红桥区| 宜春市| 湛江市| 梁河县| 佳木斯市| 临清市| 昌江| 仁怀市| 合水县| 眉山市| 吴江市| 彰武县| 昌图县| 金塔县| 枣强县| 洪雅县| 久治县| 竹山县| 中宁县| 辽阳市| 会昌县| 大新县| 墨竹工卡县| 天峨县| 玛多县| 泗阳县| 津市市|