I have a pojo which contains a few named queries to get data.
@NamedQueries({
@NamedQuery(name="abc", query="test")
})
@Entity
@Table(name = "MY_TABLE")
public class MyTable implements java.io.Serializable{
private long id;
private String name;
...........
I have to access the result of this named query from inside a service layer method. So I tried to autowire the hibernate session factory into the service layer class.
@Service
public class MyServiceClass{
@Autowired
SessionFactory sessionFactory;
..........
public void myMethod() {
Session session = acceSessionFactory.getCurrentSession();
Query query = session.getNamedQuery("abc").setInteger("id", 1).setString("name", "testname");
MyTable mytablerow = (MyTable) query.uniqueResult();
.......
}
However in the above approach - I think we are having the dao layer logic in service layer. Is this the correct way to access the named queries?
Note: I do not have a DAO interface or class for the MyTable class above.
Yes you are having DAO layer logic in your service class. Better design would be to have a MyTableDao interface which exposes various methods which can be used to retrieve data from MyTable.
In you approach you actually have no DAO layer.
The common approach for Service Layer with DAO will be
The purpose of having the named queries is that they are compiled and validated at app start-up time See Advantages of Named queries in hibernate?
I suggest that you will consider the GenericDAO pattern