How to persist an Entity in Database using JPA?

/, JPA/How to persist an Entity in Database using JPA?
Note:
Maven dependencies used all over JPA tutorials same. Please follow "Setting up Project" section to understand about project configuration.

Table Structure in Database

Student Table

Mapping Studen.java class

Quick look on annotations :

  • Student.java class mapped to the Student table. Observe the highlighted lines in Student.java class.
  • @Entity: Represents that Student.java class is mapped to Student table in DB.
  • @Id : Specifies the primary key property or field of an entity. To map field to the primary key column in table.
  • @GeneratedValue : Provides for the specification of generation strategies for the values of primary keys.
  • GenerationType : Defines the types of primary key generation. In this case autoincrement in Mysql database.
  • @column : Is used to map with specific table column. By default each field is mapped to a column with the name of the field. However if column names are different than the field names , then they can be specified @Column(name=”COLUMN_NAME”).

Persistence.xml (Where Database configuration provided):

Saving Entity to the Database :

  • To Save Entity in DB:
    1. Create EntityManagerFactory.
    2. Create EntityManager using EntityManagerFactory.
    3. Get Transaction by using EntityManager.
    4. call the Transactions begin();
    5. call the EntityManger’s persist(Entity);
    6. commit the transaction.
  • Persistence.createEntityManagerFactory(“jbd-pu”); – returns EntityManagerFactory and it uses persistence unit and it finds processes the persistence meta information.
Download Application – JPA-Helloworld.zip (16 KB)
2017-08-31T12:42:48+00:00Categories: Hibernate, JPA|Tags: , , , |0 Comments

Leave A Comment