Wednesday, April 27, 2016

Named Query in hibernate & Hibernate Example 6


    1)     To consolidate all the queries of an Entity class. Putting all queries as annotations
          at Entity level.
    2)     To write queries at Entity level

@NamedQuery(name, actual query)
@NamedNativeQuery(name,actual SQL query)

In NamedNativeQuery , we can actually provide SQL type query as an argument.

HibernateNamedQuery.java
public class HibernateNamedQuery {

     public static void main(String[] args) {
          
         SessionFactory sessionFactory = new                                     Configuration().configure().buildSessionFactory();
           Session session = sessionFactory.openSession();
           session.beginTransaction();
          
           Query query = session.getNamedQuery("Person.byId");
           query.setLong(0,5);
           List<Person> list = (List<Person>) query.list();
           for(Person p: list)
                System.out.println(p.getName());

           Query query1 = session.getNamedQuery("Person.byName");
           query1.setString(0,"Person 1");
           List<Person> list1 = (List<Person>) query1.list();
           for(Person p: list1)
                System.out.println(p.getName());
          
           session.getTransaction().commit();
           session.close();
     }
}

Person.java

@Entity(name="PERSON")
@NamedQuery(name="Person.byId",query="from PERSON where id=?")
@NamedNativeQuery(name="Person.byName",query="Select * from Person where Name=?",resultClass=Person.class)
public class Person implements java.io.Serializable{

      private static final long serialVersionUID = 1L;

      private String name;
     
      @Id
      @GeneratedValue(strategy=GenerationType.AUTO)
      private long id;

      public String getName() {
            return name;
      }

      public void setName(String name) {
            this.name = name;
      }

      public long getId() {
            return id;
      }

      public void setId(long id) {
            this.id = id;
      }
}

Output:

Hibernate: select person0_.id as id0_, person0_.name as name0_ from PERSON person0_ where person0_.id=?
Person 5

Hibernate: Select * from Person where Name=?
Person 1


No comments:

Post a Comment