NamedQuery in Hibernate

Hibernate NamedQuery attach the HQL with the Entity class. So you do not need to scatter queries all over the code. You can defined it using annotation and xml.

Annotation

@NamedQueries({
@NamedQuery(
name = "findEmployeeById",
query = "from Employee e where e.eid= :id"
)
})
@Entity
@Table(name = "employee", catalog = "akash")
public class Employee implements java.io.Serializable {...}

 

XML mapping file

<hibernate-mapping>
<class name="com.akash.Employee" table="employee" ...>
<id name="eid" type="java.lang.Integer">
<column name="EID" />
<generator class="identity" />
</id>
<property name="empName" type="string">
<column name="EMP_NAME" length="20" not-null="true" unique="true" />
</property>
...
</class>

<query name="findEmployeeById">
<![CDATA[from Employee e where e.eid= :id]]>
</query>

</hibernate-mapping>

 

Run code in main method

public class TestNamedQuery
{
    public static void main(String[] args)
    {
        //Open hibernate session
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        try
        {
            //Update record using named query
            Query query = session.getNamedQuery(Employee.findEmployeeById)
                                        .setInteger("id", 1)
                                        .setString("empName", "akash");
            query.executeUpdate();
             
            query = session.getNamedQuery(Employee.findEmployeeById)
                                        .setInteger("id", 1);
            //Get Employee object
            Employee emp = (Employee) query.uniqueResult();
            System.out.println(emp.getName());
        }
        finally
        {
            session.getTransaction().commit();
            HibernateUtil.shutdown();
        }
    }
}

Leave a Reply

%d bloggers like this: