Table Structure in Database
Technologies Used in example :
- JPA 2.1
- Hibernate 5.2.6
- MySql 8.0
- Maven 3
- Spring Tool Suite (STS) 3.9.8
- Java 1.8
Persistence.xml (Where Database configuration provided)
<persistence-unit name="jbd-pu"> <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <properties> <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" /> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpa_jbd?useJDBCCompliantTimezoneShift=true" /> <property name="javax.persistence.jdbc.user" value="root" /> <property name="javax.persistence.jdbc.password" value="password" /> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect"/> </properties> </persistence-unit>
Mapping Studen.java class
@Entity(name="STUDENT") public class Student { @Id @GeneratedValue(strategy=GenerationType.AUTO, generator="native") @GenericGenerator( name = "native", strategy = "native" ) @Column(name = "ID") private Long studentId; @Column(name = "FNAME") private String firstName; @Column(name = "LNAME") private String lastName; @Column(name = "CONTACT_NO") private String contactNo; // Setters Getters
Quick look on annotations :
- Student.java class mapped to the Student table in database.
- @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”)
.
Saving Entity to the Database :
- To Save Entity in DB:
- Create
EntityManagerFactory
. - Create
EntityManager
usingEntityManagerFactory
. - Get
Transaction
by usingEntityManager
. - call the Transaction’s begin();
- call the EntityManger’s persist(Entity);
- commit the transaction.
- Create
Persistence.createEntityManagerFactory(“jbd-pu”)
– returnsEntityManagerFactory
and it uses persistence unit and it finds processes the persistence meta information.
Persist
- The
persist
operation must be used for only new entities. When you create new entity, it’s in the transient entity lifecycle . - A transient state entity is not associated with any database table record and it’s not managed by persistence context.
- To save an entity to database you need to attach entity to persistence context and they become managed. You can use EntityManager’s
persist
operation to persist an entity in DB - And persisted entity lifecycle state becomes Persistent and can be managed with in current persistence context.
public class App { public static void main( String[] args ) { EntityManagerFactory emf = null; EntityManager entityManager = null; EntityTransaction transaction = null; try{ emf = Persistence.createEntityManagerFactory("jbd-pu"); entityManager = emf.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); Student student = new Student(); student.setFirstName("Alex"); student.setLastName("Minova"); student.setContactNo("+1-408-575-1317"); entityManager.persist(student); transaction.commit(); }catch(Exception e){ transaction.rollback(); }finally{ entityManager.close(); emf.close(); } } }
You will see like following output in console.
Hibernate: insert into STUDENT (CONTACT_NO, FNAME, LNAME) values (?, ?, ?) Feb 14, 2020 5:44:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/jpa_jbd?useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false]
Read more :
Download Application – JPA-Helloworld.zip (16 KB)