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",
"[email protected]");

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

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

}

}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.239.148