Hibernate Annotation – Creating table from java

Hibernate Annotation – Creating table from java

Hibernate is a very efficient framework for database.  Users can create tables from pure java file without creating using SQL queries.

Let us see how to create table from pure java file(POJOS) using annotations in Hibernate.

Directory Structure:
structure

employee.java

@Entity – Used to indicate the class a entity bean for the hibernate to understand
@Table – The name of the table that is to be created in the database (Optional). If this is not mentioned, By default hibernate creates table with java class name (In this case table name will be employee)
@Id – Marks the primary key for the table – In this case we have marked eid as primary key
@GeneratedValue – This is similar to auto_increment in MySQL
@Column (name=” “) – Column name in table for that field

NewHibernateUtil.java

hibernate.cfg.xml

hbm2ddl.auto – update – Used to update the field in table, if table is not available it creates a new table
hbm2ddl.auto – create – It creates new table on every execution, if table already present it drops the table and create new one.
mapping class – The class which we have marked as @Entity – so the hibernate understands it needs to create table for the fields of that class
hibernate.show_sql – Used to show the sql query hibernate used in the application (Optional)

Execution.java

Output:
op1

We can see the query used by hibernate in the output, that’s because we have mentioned hibernate.show_sql – true

op2

 

 

 

One thought on “Hibernate Annotation – Creating table from java

Leave a Reply

Your email address will not be published. Required fields are marked *