JPA: Part 2

This is continued from JPA: part 1.

Other Annotations:

  • @Table(name = “TABLENAME”)
    • Used before class name to explicitly specify table name.
  • @Column(name = “COLUMN_NAME”)
    • Used before instance variables to explicitly set column names.

Example:

@Entity
@Table(name = "EMP")
public class Employee {
    @Id
    @Column(name = "EMP_ID")
    private int id;

    @Column(name = "EMP_NAME")
    private String name;

    //getters and setters
}

this maps to
Table: EMP

 --------------------------
 | EMP_ID (PK) | EMP_NAME |
 --------------------------
 |_____________|__________|

JPA automatically maps ‘int’ to ‘NUMBER’ and ‘String’ to ‘CHAR’ or ‘VARCHAR’. But it cannot automatically convert Date or Time datatypes. So we need to specify the Temporal type to be used. (Temporal = related to time)

Other Annotations:

  • @Temporal(TemporalType.TYPE)
    • TYPE can be DATE, TIME or TIMESTAMP. Used before ‘Date’ or ‘Calendar’ datatypes. Oracle only has DATE datatype. It doesn’t have TIME or TIMESTAMP.
  • @Transient
    • Used before those instance variables that need not be persisted.

Example:

@Entity
public class Student {
    @Id
    private int regNo;
    private String name;

    @Temporal(TemporalType.DATE)
    private Calendar dob; //'dob' column od database is of 'DATE' datatype

    private int mark1;
    private int mark2;
    private int mark3;

    @Transient
    private float averageMark; //Not stored in database

    //getters and setters
}

Configuring JPA

Configure ‘persistence unit’ in ‘persistence.xml‘:
Persistence unit name is specified as:

<persistence-unit name="EmployeeService" transaction-type="RESOURCE_LOCAL">

Here EmployeeService is the persistence unit.

We should then specify all Entity classes that need to be persisted in <class> tags

<class>me.sinu.entity.Entity1</class>
<class>me.sinu.entity.Entity2</class>
<class>me.sinu.entity.Entity3</class>

We then configure the db related stuff like URL,username,password etc.

<properties>
    <property name="toplink.jdbc.url" value="jdbc:oracle:thin:@127.0.0.1:1521/db"/>
    <property name="toplink.jdbc.user" value="username"/>
    <property name="toplink.jdbc.password" value="password"/>
    <property name="toplink.jdbc.driver" value="oracle.jdbc.driver.OracleDriver"/>
    <property name="toplink.ddl-generation" value="create-tables"/>
</properties>

This is for TopLink implementation of JPA to connect to Oracle. It might be different for other implementations.

Persisting an Entity using JPA

  1. Creating an instance of ‘EntityManagerFactory
    • Persistence.createEntityManagerFactory(persistence-unit_name_defined_in_xml_file)
  2. Obtaining an instanceof ‘EntityManager
  3. Persist the Entity
    • Begin EntityTransaction
    • Invoke persist()
    • Commit the transaction

Example:

EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeeService");
EntityManager em = emf.createEntityManager();
EntityTransaction et = em.getTransaction();
if(et==null) {
    //ERROR. Cannot obtain transaction
    return;
}
et.begin(); //begin transaction
    Employee emp = new Employee();
    emp.setEmpId(101);
    emp.setName("sinu");
    em.persist(emp); //persist the data
et.commit(); //ending transaction

When we call em.persist(), data is sent to the database and it is stored in DB Buffer. It is not yet updated in the table. When we call em.commit(), the data gets updated in the table.

Finding an Entity

To find an entity, we need not begin a transaction. We can find it using EntityManager.
Syntax:
EntityManager.find(EntityClassName.class, PrimaryKey)

Example:

Employee empl = em.find(Employee.class, 101);

Here 101 is the empId(primary key) to be searched.

If table doesn’t exist or record is not present, it returns null.

Updating an Entity

Once we find an entity, the entity object in the heap memory gets a connection to the table. So,if we modify the object, the table also gets updated.
An object which is connected to a table(relation) is called ‘Managed Object‘. If we update the Managed Object, the table also gets updated.

Example:

EntityTransaction et = em.getTransaction();
et.begin();
    Employee empl = em.find(Employee.class, 101);
    //empl is now a Managed Object. We can now modify it
    if(empl!=null) {
        empl.setSalary(empl.getSalary()+1000);
    }
et.commit();

Removing an Entity

This is similar to update. Once we find the object we call EntityManager.remove(entityObject)

Example:

EntityTransaction et = em.getTransaction();
et.begin();
    Employee empl = em.find(Employee.class, 101);
    //empl is now a Managed Object. We can now modify it
    if(empl!=null) {
        em.remove(empl)
    }
et.commit();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s