Hibernate Named Native SQL in Annotation
In this section, you will learn how to execute the Named Native SQL written in Model class Annotation.
You can put frequently used Named Native SQL query inside Model class annotation to prevent yourself from repetitive work. Plus it also helps in arranging code, now you can put model class, mapping and its related queries together.
EXAMPLE
The project hierarchy and the jar files used is given below:
The SQL query used to create worker table is given below :
CREATE TABLE `worker` ( `worker_id` bigint(10) NOT NULL auto_increment, `firstname` varchar(50) default NULL, `lastname` varchar(50) default NULL, `birth_date` date NOT NULL, `cell_phone` varchar(15) NOT NULL, PRIMARY KEY (`worker_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1
CODE
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/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://192.168.10.13:3306/anky</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <property name="connection.pool_size">1</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="current_session_context_class">thread</property> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">validate</property> <mapping class="net.roseindia.Worker"/> </session-factory> </hibernate-configuration>
Worker.java
package net.roseindia; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.NamedNativeQueries; import javax.persistence.NamedNativeQuery; import javax.persistence.Table; @NamedNativeQueries({ @NamedNativeQuery( name = "findViaWorkerId", query = "select * from worker w where w.worker_id = :workerId", resultClass = Worker.class ) }) @Entity @Table(name = "worker") public class Worker { @Id @GeneratedValue @Column(name = "worker_id") private Long workerId; @Column(name = "firstname") private String firstname; @Column(name = "lastname") private String lastname; @Column(name = "birth_date") private Date birthDate; @Column(name = "cell_phone") private String cellphone; public Worker() { } public Worker(String firstname, String lastname, Date birthdate, String phone) { this.firstname = firstname; this.lastname = lastname; this.birthDate = birthdate; this.cellphone = phone; } public Long getWorkerId() { return workerId; } public void setWorkerId(Long workerId) { this.workerId = workerId; } 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; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public String getCellphone() { return cellphone; } public void setCellphone(String cellphone) { this.cellphone = cellphone; } }
HibernateNamedNativeSQLAnnotation.java
package net.roseindia; import java.util.Iterator; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; public class HibernateNamedNativeSQLAnnotation { private static SessionFactory sf; private static ServiceRegistry serviceRegistry; public static void main(String[] args) { try { Configuration configuration = new Configuration(); configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings( configuration.getProperties()).buildServiceRegistry(); sf = configuration.buildSessionFactory(serviceRegistry); } catch (Throwable ex) { System.err.println("Failed to create sessionFactory object." + ex); throw new ExceptionInInitializerError(ex); } System.out.println("*** Hibernate Named Native SQL in Annotation ***"); System.out.println("----------------------------------------------------------"); Session session = sf.openSession(); try { session.beginTransaction(); Query query = session.getNamedQuery("findViaWorkerId").setString("workerId", "13"); List workers = query.list(); for (Iterator iterator = workers.iterator(); iterator.hasNext();) { Worker worker = (Worker) iterator.next(); System.out.println("Worker Id:" + worker.getWorkerId()); System.out.println("Worker Name:" + worker.getFirstname()); System.out.println("Worker Birth Date:" + worker.getBirthDate()); System.out.println("Worker CellPhone No."+ worker.getCellphone()); System.out.println("-----------------------------------------------------------"); } session.getTransaction().commit(); } catch (HibernateException e) { if (session.getTransaction() != null) session.getTransaction().rollback(); e.printStackTrace(); } finally { session.close(); } } }
OUTPUT
After execution, you will get something like this on console :
*** Hibernate Named Native SQL in Annotation *** ---------------------------------------------------------- Hibernate: select * from worker w where w.worker_id = ? Worker Id:13 Worker Name:Somesh Worker Birth Date:1987-07-21 00:00:00.0 Worker CellPhone No.919595959090 -----------------------------------------------------------