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 : Elder Moraes
5 (2)
close
close
Jakarta EE Cookbook

Jakarta EE Cookbook

5 (2)
By: Elder 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 JPA for smart data persistence

Jakarta Persistence (formerly JPA) is a specification that describes an interface for managing relational databases using Jakarta EE.

It eases data manipulation and reduces a lot of the code written for it, especially if you are used to the SQL American National Standards Institute (ANSI).

This recipe will show you how to use it to persist your data.

Getting ready

First, let's 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...

To complete this recipe, we need to perform the following steps:

  1. Let's begin by creating an entity (you can view it as a table):
@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. Here, we will declare our persistence unit (at persistence.xml):
    <persistence-unit name="ch02-jpa-pu" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>userDb</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. Now, we need to create a session bean to manage our data:
@Stateless
public class UserBean {

@PersistenceContext(unitName = "ch02-jpa-pu",
type = PersistenceContextType.TRANSACTION)
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. Here, we're using a unit test to try it out:
public class Ch02JpaTest {

private EJBContainer ejbContainer;

@EJB
private UserBean userBean;

public Ch02JpaTest() {
}

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


}

}

Now, let's see how this recipe works.

How it works...

Let's break down our Persistence Unit (PU).

The following line defines the pu name and the transaction type used:

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

The following line shows the provider the JPA implementation used:

<provider>org.hibernate.ejb.HibernatePersistence</provider>

This is the data source name that will be accessed through the Java Naming and Directory Interface (JNDI):

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

The following line lets all your entities be available for this pu, so you don't need to declare each one:

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

The following code allows the database objects to be created if they don't exist:

<properties>
<property name="javax.persistence.schema-
generation.database.action"
value="create"/>
</properties>

Now, let's have a look at UserBean:

@Stateless
public class UserBean {

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

...

}

EntityManager is the object responsible for the interface between the bean and the data source. It's bound to the context by the PersistenceContext annotation.

Let's check the EntityManager operations, as follows:

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

The persist() method is used to add new data to the data source. At the end of its execution, the object is attached to the context:

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

The merge() method is used to update existing data on the data source. The object is first found at the context, then updated at the database and attached to the context with the new state:

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

Now, let's look at the remove() method – guess what it is:

public User findById(Long id){
return em.find(User.class, id);
}

Finally, the find() method uses the id parameter to search for a database object with the same ID. That's why JPA demands that your entities have an ID declared with the @Id annotation.

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