- Hibernate
- What is ORM?
- First Hibernate Application
- Hibernate hbm2ddl.auto property
- Set table name for entity in Hibernate
- Set Column name for entity in Hibernate
- Disable mapping for a column
- Make the field as transient to not persist
- @Transient : disable persisting data
- Temporal : Handling date in Hibernate
- Hibernate : Lob : To persist large text
- Hibernate : Retrieving data from database
- GeneratedValue : GenerationType : Generating keys automatically
- Embeddable : Embedding value object into entity object
- Embedded : Embedding value object into entity object
- Change column names of embedded object
- @EmbeddedId : Represent embedded object as primary key
- ElementCollection : Save collection of objects
- JoinTable : To tweak collection object saved
- CollectionId : Adding primary key for collection table
- Hibernate FetchType : Lazy Vs Eager
- Hibernate : One-to-One mapping
- Hibernate : One to Many Mapping
- Hibernate : many to one mapping
- Hibernate : Many-To-Many mapping
- Inheritance in hibernate
- Tweaking Hibernate inheritance
- Inhertiance: Table per class strategy
- Inheritance : InheritanceType.JOINED
- Hibernate : CRUD Operations
- Hibernate : Delete data from database
- Hibernate : Update data
- HQL
- HQL : from clause
- HQL : From with where clause
- HQL : select clause
- HQL : Select few columns
- HQL: pagination
- HQL : Parameter binding
- HQL: Positional parameter binding
- HQL : Named parameter binding
- HQL : NamedQuery : Named Queries
- HQL : NamedQueries : Write multiple named queries for entity
- HQL : NamedNativeQuery : Named Native queries
- HQL : NamedNativeQueries : Write multiple native queries for entity
- Hibernate criteria API
- Hibernate HikariCP example
- HSQLDB & Hibernate Example
This blog is primarily focus on Java fundamentals and the libraries built on top of Java programming language. Most of the post are example oriented, hope you have fun in reading my blog....:)
Saturday, 27 December 2014
Hibernate Tutorial
Hibernate criteria API
Till
now we have seen how to manipulate tables using HQL (Hibernate Query language).
Hibernate provides another way of manipulating objects using criteria API. It
is a 3 step process.
Step 1: Create criteria
object.
Ex:
Criteria
crit = session.createCriteria(Employee.class);
Step 2: Apply filteration
rules or logical conditions.
Ex:
crit.add(Restrictions.eq("id",
6));
Step 3: Get results of
criteria query.
Ex:
List<Employee>
empList = (List<Employee>)crit.list();
package myFirstHibernate; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.NamedNativeQueries; import javax.persistence.NamedNativeQuery; @Entity(name="employee_details") @NamedNativeQueries({ @NamedNativeQuery(name="Employee.getById", query="select * from employee_details where id=?", resultClass=Employee.class), @NamedNativeQuery(name="Employee.getByFirstName", query="select * from employee_details where firstName=?", resultClass=Employee.class), @NamedNativeQuery(name="Employee.getByLastName", query="select * from employee_details where lastName=?", resultClass=Employee.class) }) public class Employee { @Id @GeneratedValue private int id; private String firstName; private String lastName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database Connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost/sample</property> <property name="connection.username">root</property> <property name="connection.password">tiger</property> <!-- Enable the logging of all the generated SQL statements to the console --> <property name="show_sql">true</property> <!-- Format the generated SQL statement to make it more readable, --> <property name="format_sql">false</property> <!-- Hibernate will put comments inside all generated SQL statements to hint what’s the generated SQL trying to do --> <property name="use_sql_comments">false</property> <!-- This property makes Hibernate generate the appropriate SQL for the chosen database. --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">create</property> <!-- mappings for annotated classes --> <mapping class="myFirstHibernate.Employee" /> </session-factory> </hibernate-configuration>
package myFirstHibernate; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Restrictions; public class TestEmployee { /* Step 1: Create session factory */ private static SessionFactory getSessionFactory() { Configuration configuration = new Configuration().configure(); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder(). applySettings(configuration.getProperties()); SessionFactory factory = configuration.buildSessionFactory(builder.build()); return factory; } public static void main(String args[])throws Exception{ Employee emp1 = new Employee(); Employee emp2 = new Employee(); Employee emp3 = new Employee(); Employee emp4 = new Employee(); Employee emp5 = new Employee(); Employee emp6 = new Employee(); Employee emp7 = new Employee(); Employee emp8 = new Employee(); emp1.setFirstName("Hari Krishna"); emp1.setLastName("Gurram"); emp2.setFirstName("Shreyas"); emp2.setLastName("Desai"); emp3.setFirstName("Piyush"); emp3.setLastName("Rai"); emp4.setFirstName("Rama Krishna"); emp4.setLastName("Gurram"); emp5.setFirstName("Sailaja"); emp5.setLastName("Navakotla"); emp6.setFirstName("Keerthi"); emp6.setLastName("Parush"); emp7.setFirstName("Gopi"); emp7.setLastName("Battu"); emp8.setFirstName("Jaideep"); emp8.setLastName("Gera"); SessionFactory sessionFactory = getSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); /* Saving objects to database */ session.save(emp1); session.save(emp2); session.save(emp3); session.save(emp4); session.save(emp5); session.save(emp6); session.save(emp7); session.save(emp8); Criteria crit = session.createCriteria(Employee.class); crit.add(Restrictions.eq("id", 6)); List<Employee> empList = (List<Employee>)crit.list(); for(Employee emp : empList) System.out.println(emp.getId() + " " + emp.getFirstName() +" " + emp.getLastName()); session.getTransaction().commit(); session.close(); } }
Run
TestEmployee class, you will get output like below.
Hibernate: drop table if exists employee_details Hibernate: create table employee_details (id integer not null auto_increment, firstName varchar(255), lastName varchar(255), primary key (id)) Dec 23, 2014 4:36:04 PM org.hibernate.tool.hbm2ddl.SchemaExport execute INFO: HHH000230: Schema export complete Hibernate: insert into employee_details (firstName, lastName) values (?, ?) Hibernate: insert into employee_details (firstName, lastName) values (?, ?) Hibernate: insert into employee_details (firstName, lastName) values (?, ?) Hibernate: insert into employee_details (firstName, lastName) values (?, ?) Hibernate: insert into employee_details (firstName, lastName) values (?, ?) Hibernate: insert into employee_details (firstName, lastName) values (?, ?) Hibernate: insert into employee_details (firstName, lastName) values (?, ?) Hibernate: insert into employee_details (firstName, lastName) values (?, ?) Hibernate: select this_.id as id1_0_0_, this_.firstName as firstNam2_0_0_, this_.lastName as lastName3_0_0_ from employee_details this_ where this_.id=? 6 Keerthi Parush
HQL : NamedNativeQueries : Write multiple native queries for entity
You
can write any number of named native queries for an entity by placing them in “@NamedNativeQueries”
annotation.
@Entity(name="employee_details") @NamedNativeQueries({ @NamedNativeQuery(name="Employee.getById", query="select * from employee_details where id=?", resultClass=Employee.class), @NamedNativeQuery(name="Employee.getByFirstName", query="select * from employee_details where firstName=?", resultClass=Employee.class), @NamedNativeQuery(name="Employee.getByLastName", query="select * from employee_details where lastName=?", resultClass=Employee.class) }) public class Employee { }
package myFirstHibernate; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.NamedNativeQueries; import javax.persistence.NamedNativeQuery; @Entity(name="employee_details") @NamedNativeQueries({ @NamedNativeQuery(name="Employee.getById", query="select * from employee_details where id=?", resultClass=Employee.class), @NamedNativeQuery(name="Employee.getByFirstName", query="select * from employee_details where firstName=?", resultClass=Employee.class), @NamedNativeQuery(name="Employee.getByLastName", query="select * from employee_details where lastName=?", resultClass=Employee.class) }) public class Employee { @Id @GeneratedValue private int id; private String firstName; private String lastName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database Connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost/sample</property> <property name="connection.username">root</property> <property name="connection.password">tiger</property> <!-- Enable the logging of all the generated SQL statements to the console --> <property name="show_sql">true</property> <!-- Format the generated SQL statement to make it more readable, --> <property name="format_sql">false</property> <!-- Hibernate will put comments inside all generated SQL statements to hint what’s the generated SQL trying to do --> <property name="use_sql_comments">false</property> <!-- This property makes Hibernate generate the appropriate SQL for the chosen database. --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">create</property> <!-- mappings for annotated classes --> <mapping class="myFirstHibernate.Employee" /> </session-factory> </hibernate-configuration>
package myFirstHibernate; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; public class TestEmployee { /* Step 1: Create session factory */ private static SessionFactory getSessionFactory() { Configuration configuration = new Configuration().configure(); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder(). applySettings(configuration.getProperties()); SessionFactory factory = configuration.buildSessionFactory(builder.build()); return factory; } public static void main(String args[])throws Exception{ Employee emp1 = new Employee(); Employee emp2 = new Employee(); Employee emp3 = new Employee(); Employee emp4 = new Employee(); Employee emp5 = new Employee(); Employee emp6 = new Employee(); Employee emp7 = new Employee(); Employee emp8 = new Employee(); emp1.setFirstName("Hari Krishna"); emp1.setLastName("Gurram"); emp2.setFirstName("Shreyas"); emp2.setLastName("Desai"); emp3.setFirstName("Piyush"); emp3.setLastName("Rai"); emp4.setFirstName("Rama Krishna"); emp4.setLastName("Gurram"); emp5.setFirstName("Sailaja"); emp5.setLastName("Navakotla"); emp6.setFirstName("Keerthi"); emp6.setLastName("Parush"); emp7.setFirstName("Gopi"); emp7.setLastName("Battu"); emp8.setFirstName("Jaideep"); emp8.setLastName("Gera"); SessionFactory sessionFactory = getSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); /* Saving objects to database */ session.save(emp1); session.save(emp2); session.save(emp3); session.save(emp4); session.save(emp5); session.save(emp6); session.save(emp7); session.save(emp8); String empId = "4"; String firstName = "Shreyas"; String lastName = "Gurram"; /* Executing named query Employee.getByID */ System.out.println("---------------------------------------"); System.out.println("Executing named query Employee.getByID"); Query query = session.getNamedQuery("Employee.getById"); query.setString(0, empId); List<Employee> list = (List<Employee>)query.list(); for(Employee emp : list) System.out.println(emp.getId() + " " + emp.getFirstName() + " " + emp.getLastName()); /* Executing named query Employee.getByFirstName */ System.out.println("---------------------------------------"); System.out.println("Executing named query Employee.getByFirstName"); query = session.getNamedQuery("Employee.getByFirstName"); query.setString(0, firstName); list = (List<Employee>)query.list(); for(Employee emp : list) System.out.println(emp.getId() + " " + emp.getFirstName() + " " + emp.getLastName()); /* Executing named query Employee.getByLastName */ System.out.println("---------------------------------------"); System.out.println("Executing named query Employee.getByLastName"); query = session.getNamedQuery("Employee.getByLastName"); query.setString(0, lastName); list = (List<Employee>)query.list(); for(Employee emp : list) System.out.println(emp.getId() + " " + emp.getFirstName() + " " + emp.getLastName()); session.getTransaction().commit(); session.close(); } }
Run
TestEmployee class, you will get output like below.
Hibernate: drop table if exists employee_details Hibernate: create table employee_details (id integer not null auto_increment, firstName varchar(255), lastName varchar(255), primary key (id)) Dec 23, 2014 12:07:36 PM org.hibernate.tool.hbm2ddl.SchemaExport execute INFO: HHH000230: Schema export complete Hibernate: insert into employee_details (firstName, lastName) values (?, ?) Hibernate: insert into employee_details (firstName, lastName) values (?, ?) Hibernate: insert into employee_details (firstName, lastName) values (?, ?) Hibernate: insert into employee_details (firstName, lastName) values (?, ?) Hibernate: insert into employee_details (firstName, lastName) values (?, ?) Hibernate: insert into employee_details (firstName, lastName) values (?, ?) Hibernate: insert into employee_details (firstName, lastName) values (?, ?) Hibernate: insert into employee_details (firstName, lastName) values (?, ?) --------------------------------------- Executing named query Employee.getByID Hibernate: select * from employee_details where id=? 4 Rama Krishna Gurram --------------------------------------- Executing named query Employee.getByFirstName Hibernate: select * from employee_details where firstName=? 2 Shreyas Desai --------------------------------------- Executing named query Employee.getByLastName Hibernate: select * from employee_details where lastName=? 1 Hari Krishna Gurram 4 Rama Krishna Gurram
Prevoius Next Home
Subscribe to:
Posts (Atom)