Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Jakarta EE Cookbook
  • Table Of Contents Toc
Jakarta EE Cookbook

Jakarta EE Cookbook - Second Edition

By : Moraes
5 (2)
close
close
Jakarta EE Cookbook

Jakarta EE Cookbook

5 (2)
By: Moraes

Overview of this book

Jakarta EE is widely used around the world for developing enterprise applications for a variety of domains. With this book, Java professionals will be able to enhance their skills to deliver powerful enterprise solutions using practical recipes. This second edition of the Jakarta EE Cookbook takes you through the improvements introduced in its latest version and helps you get hands-on with its significant APIs and features used for server-side development. You'll use Jakarta EE for creating RESTful web services and web applications with the JAX-RS, JSON-P, and JSON-B APIs and learn how you can improve the security of your enterprise solutions. Not only will you learn how to use the most important servers on the market, but you'll also learn to make the best of what they have to offer for your project. From an architectural point of view, this Jakarta book covers microservices, cloud computing, and containers. It allows you to explore all the tools for building reactive applications using Jakarta EE and core Java features such as lambdas. Finally, you'll discover how professionals can improve their projects by engaging with and contributing to the community. By the end of this book, you'll have become proficient in developing and deploying enterprise applications using Jakarta EE.
Table of Contents (14 chapters)
close
close

Using EJB and JTA for transaction management

Jakarta Transaction (formerly JTA) is an API that enables distributed transactions over the Jakarta EE environment. It is most powerful when you delegate transaction management to the server.

This recipe will show you how to do this!

Getting ready

First, add the required dependencies:

        <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.1.Final</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>8.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.openejb</groupId>
<artifactId>openejb-core</artifactId>
<version>4.7.4</version>
<scope>test</scope>
</dependency>

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");

}

}

How it works...

The key code line in this recipe for JTA is as follows:

<persistence-unit name="ch02-jta-pu" transaction-type="JTA">

When you use transaction-type='JTA', you are saying to the server that it should take care of all transactions made under this context. If you use RESOURCE-LOCAL instead, you are saying that you are taking care of the transactions:

 @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");

}

Each called method of UserBean starts a transaction to be completed and will run into a rollback if there's an issue while the transaction is alive. This would be committed to the end of it.

There's more...

Another important piece of code is the following one:

@Stateful
public class UserBean {

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

...
}

Here, we are defining PersistenceContext as EXTENDED. This means that this persistence context is bound to the @Stateful bean until it is removed from the container.

The other option is TRANSACTION, which means the persistence context will only live for the duration of the transaction.

See also

CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Jakarta EE Cookbook
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon