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 class

Quick look on annotations :

  • class mapped to the Student table. Observe the highlighted lines in class.
  • @Entity: Represents that 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 – (16 KB)