- Jakarta EE Cookbook
- Elder Moraes
- 239字
- 2021-06-24 16:12:46
How to do it...
You need to perform the following steps to complete this recipe:
- 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>
- 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
}
- 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);
}
}
- 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");
}
}
推薦閱讀
- MariaDB High Performance
- TypeScript項(xiàng)目開發(fā)實(shí)戰(zhàn)
- bbPress Complete
- R數(shù)據(jù)科學(xué)實(shí)戰(zhàn):工具詳解與案例分析
- 開源項(xiàng)目成功之道
- Building Serverless Web Applications
- Scala Functional Programming Patterns
- 算法圖解
- Magento 2 Beginners Guide
- 零基礎(chǔ)輕松學(xué)C++:青少年趣味編程(全彩版)
- 大數(shù)據(jù)時(shí)代的企業(yè)升級(jí)之道(全3冊(cè))
- UML基礎(chǔ)與Rose建模實(shí)用教程(第三版)
- iOS Development with Xamarin Cookbook
- Pandas 1.x Cookbook
- Visual C#(學(xué)習(xí)筆記)