0% found this document useful (0 votes)
57 views10 pages

JPA2

The document discusses how to create entity classes in Java Persistence API (JPA) that map to existing database tables or are used to generate new database tables. It provides steps for generating entity classes from existing database tables in NetBeans or Eclipse. It also shows an example of an entity class created manually that can be used to generate a new database table.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views10 pages

JPA2

The document discusses how to create entity classes in Java Persistence API (JPA) that map to existing database tables or are used to generate new database tables. It provides steps for generating entity classes from existing database tables in NetBeans or Eclipse. It also shows an example of an entity class created manually that can be used to generate a new database table.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

CIS 3052 [Part 2] JPA

Java Persistence API (JPA)


An entity class is a conventional Java class – Plan Old Java Object (POJO) that is used to be
mapped to a particular database table. An entity can either be mapped to an existing table
or else it can be used to actually generate a new SQL table in a database.

Creating an entity class from a database table


In this tutorial the flightsdb database that was created for the Servets/JSP tutorial is going to
be used. This database is implemented using MySQL therefore it is important that the
MySQL JDBC Connector library is included in the project.

1. Create a new entity class by selecting the option Entity Classes from Database… as
shown in the screen shot below:

2. A dialog box as shown below is displayed on the screen. You have to either select a
stored connection (if you have already created other entities for the same project) or
else select New Database Connection… and follow the wizard to create a new
database connection.

Matthew Xuereb © 2012/2013 Page 1 of 10


CIS 3052 [Part 2] JPA

3. It is very important that when a new database connection is created, the appropriate
database is selected as shown in the screen shot below:

4. When the database connection is established, a dialog box as shown below is


displayed on the screen. Select the tables from the database that you want to map
to an entity class and click on the Next button.

Matthew Xuereb © 2012/2013 Page 2 of 10


CIS 3052 [Part 2] JPA

5. Select or type in a package where to store the entity classes and click on finish.

6. When you click on finish notice that an entity class is created together with a
persistence.xml file in a META-INF sub-directory directory under the source package
directory as shown in the screen shot below. This file will be explained later in this
tutorial.

The entity class


When an entity class is created, apart from the usual Java code, the class is also populated
with special annotations. These annotations are used to provide information about the
mapping between the entity POJO and the SQL table. When an entity is mapped from an
existing table using an IDE such as NetBeans or eclipse there is no need to add any other
special annotations.

The following is the code (excluding the package declaration and the imports) that was
generated in the above example for the Flights table:
@Entity
@Table(name = "flights")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Flights.findAll", query = "SELECT f FROM Flights f"),
@NamedQuery(name = "Flights.findById", query = "SELECT f FROM Flights f WHERE f.id = :id"),
@NamedQuery(name = "Flights.findByFlightNum", query = "SELECT f FROM Flights f WHERE f.flightNum = :flightNum"),
@NamedQuery(name = "Flights.findByFlightDate", query = "SELECT f FROM Flights f WHERE f.flightDate = :flightDate"),
@NamedQuery(name = "Flights.findBySeatsLeft", query = "SELECT f FROM Flights f WHERE f.seatsLeft = :seatsLeft")})
public class Flights implements Serializable {

Matthew Xuereb © 2012/2013 Page 3 of 10


CIS 3052 [Part 2] JPA

private static final long serialVersionUID = 1L;


@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@Column(name = "flight_num")
private String flightNum;
@Basic(optional = false)
@Column(name = "flight_date")
@Temporal(TemporalType.DATE)
private Date flightDate;
@Column(name = "seats_left")
private Integer seatsLeft;

public Flights() {
}

public Flights(Integer id) {


this.id = id;
}

public Flights(Integer id, String flightNum, Date flightDate) {


this.id = id;
this.flightNum = flightNum;
this.flightDate = flightDate;
}

public Integer getId() {


return id;
}

public void setId(Integer id) {


this.id = id;
}

public String getFlightNum() {


return flightNum;
}

public void setFlightNum(String flightNum) {


this.flightNum = flightNum;
}

public Date getFlightDate() {


return flightDate;
}

public void setFlightDate(Date flightDate) {


this.flightDate = flightDate;
}

public Integer getSeatsLeft() {


return seatsLeft;
}

public void setSeatsLeft(Integer seatsLeft) {


this.seatsLeft = seatsLeft;
}

Matthew Xuereb © 2012/2013 Page 4 of 10


CIS 3052 [Part 2] JPA

@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object object) {
if (!(object instanceof Flights)) {
return false;
}
Flights other = (Flights) object;
if ((this.id == null && other.id != null) || (this.id != null &&
!this.id.equals(other.id))) {
return false;
}
return true;
}

@Override
public String toString() {
return "entities.Flights[ id=" + id + " ]";
}
}

The following is the SQL code that was used to create the flights database table on the
MySQL server:

create table flights(


id int primary key not null auto_increment,
flight_num varchar(8) not null,
flight_date date not null,
seats_left int
);

The entity class is following the rules of encapsulation and therefore all attributes are set to
be private and getters and setters are used to provide access to them. An empty and
parameter less constructor is included and the entity class is also implementing the
Serializable interface.

Note that although every item in the table is mapped to a Java POJO, the Java naming
convention is used in the Java entity. For this reason, fields such as flight_num where
written as flightNum in the Java entity class. To indicate the mapping (as different naming
convention is used) notice the use of the tags @Column and @Table both with the name
field for the table fields and table name respectively. Other tags such as @Id and
@GeneratedValue as used to indicate which are the primary fields and the method of auto
filling them with values.

There are a lot of annotations that can be used with JPA 2.0. For a full list of annotations
and their respective explanation, consult with the official Oracle Java EE 6 tutorial
http://docs.oracle.com/javaee/6/tutorial/doc/javaeetutorial6.pdf.

Matthew Xuereb © 2012/2013 Page 5 of 10


CIS 3052 [Part 2] JPA

Creating an entity class and automatically creating an SQL table in


database
With JPA it is also possible to first create an entity class and then it JPA will automatically
create it respective SQL table in the database.

1. Create a new entity class by selecting the Entity Class… option.

2. Type in the name of the entity and the appropriate primary key type as shown in the
screen shot below.

3. The outline of the entity class is automatically generated. The attributes of this
entity should now be coded including the relevant JPA annotations, getters, setter
and constructors.

The following source code illustrates and example of an entity (excluding the package
declaration and the imports) that was created from scratch and it will be used to create a
new SQL table in the database. Notice that only few annotations were used in this example:

@Entity
@Table(name="passengers")

Matthew Xuereb © 2012/2013 Page 6 of 10


CIS 3052 [Part 2] JPA

public class Passenger implements Serializable {


private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String surname;
@Column(name="passport_num")
private String passportNum;

public Passenger(){
// Empty parameter less constructor
}

public Passenger(String name,String surname,String passportNum){


this.name = name;
this.surname = surname;
this.passportNum = passportNum;
}

public Long getId() {


return id;
}

public void setId(Long id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getSurname() {


return surname;
}

public void setSurname(String surname) {


this.surname = surname;
}

public String getPassportNum() {


return passportNum;
}

public void setPassportNum(String passportNum) {


this.passportNum = passportNum;
}

@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object object) {
if (!(object instanceof Passenger)) {
return false;
}
Passenger other = (Passenger) object;
if ((this.id == null && other.id != null) || (this.id != null &&
!this.id.equals(other.id))) {
return false;

Matthew Xuereb © 2012/2013 Page 7 of 10


CIS 3052 [Part 2] JPA

}
return true;
}

@Override
public String toString() {
return "entities.Passenger[ id=" + id + " ]";
}
}

The persistence.xml file


The persistence.xml file is usually generated automatically by the IDE. It is a very important
file that is used to configure the persistence unit. The following is a screen shot of this file
when opened by the NetBeans IDE after the above two entities are created:

The above screen shot represents a simple GUI that can be used to configure the
persistence.xml file. This GUI is a mapping to an xml file (click on source to view the file) that
is shown below:

<?xml version="1.0" encoding="UTF-8"?>


<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="JPA_DemoPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>entities.Flights</class>
<class>entities.Passenger</class>
<properties>
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/flightsdb"/>
<property name="javax.persistence.jdbc.password" value="letmein"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="eclipselink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>

Matthew Xuereb © 2012/2013 Page 8 of 10


CIS 3052 [Part 2] JPA

The tag persistence-unit name is used to define an identifier for this particular persistence
application. The provider tag is used to indicate the persistence unit provider. In the above
example the provider is the EclipseLink however other such as Hibernate can be used. The
list of class tags lists the entity classes. The property tag includes a number of very
important properties such as the database url, username, password and driver. The
property <property name="eclipselink.ddl-generation" value="create-tables"/>
is used to allow the persistence unit to create new SQL tables in the database from a given
entity class.

Using entity classes


The following are some examples of how to use entity classes and JPA to work with
databases.

Adding a new record


Passenger passenger = new Passenger("Matthew","Xuereb","123456");
EntityManagerFactory emFactory =
Persistence.createEntityManagerFactory("JPA_DemoPU");
EntityManager em = emFactory.createEntityManager();
em.getTransaction().begin();
em.persist(passenger);
em.getTransaction().commit();
em.close();

Querying a table using the Java Persistence Query Language


EntityManagerFactory emFactory =
Persistence.createEntityManagerFactory("JPA_DemoPU");
EntityManager em = emFactory.createEntityManager();
Query query =
em.createQuery("select f from Flights f where f.flightNum='KM102'");
List<Flights> result = query.getResultList();
// ...
em.close();

Querying a table using Named queries


Named queries are queries that can be written using JPU annotations as shown in the Flights
entity example above. Note that when an entity is generated automatically from a table,
such named queries are also generated automatically.

EntityManagerFactory emFactory =

Persistence.createEntityManagerFactory("JPA_DemoPU");
EntityManager em = emFactory.createEntityManager();
Query query = em.createNamedQuery("Flights.findByFlightNum");
query.setParameter("flightNum","KM102");
List<Flights> result = query.getResultList();
// ...
em.close();

Matthew Xuereb © 2012/2013 Page 9 of 10


CIS 3052 [Part 2] JPA

Updating a table record


EntityManagerFactory emFactory =
Persistence.createEntityManagerFactory("JPA_DemoPU");
EntityManager em = emFactory.createEntityManager();
em.getTransaction().begin();
Passenger passenger = em.find(Passenger.class,new Long(1));
passenger.setPassportNum("56789");
em.getTransaction().commit();
em.close();

Matthew Xuereb © 2012/2013 Page 10 of 10

You might also like