问题描述
我有一个 pojo,其中包含一些用于获取数据的命名查询.
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();
.......
}
但是在上述方法中 - 我认为我们在服务层中有 dao 层逻辑.这是访问命名查询的正确方法吗?
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?
注意:我没有上面 MyTable 类的 DAO 接口或类.
Note: I do not have a DAO interface or class for the MyTable class above.
推荐答案
在你的方法中,你实际上没有 DAO 层.
带有 DAO 的服务层的常用方法是
In you approach you actually have no DAO layer.
The common approach for Service Layer with DAO will be
@NamedQueries({
@NamedQuery(name="abc", query="test")
})
@Entity
@Table(name = "MY_TABLE")
public class MyTable
@Repository
public class MyTableDAOImpl implements MyTableDAO
@Autowire
protected SessionFactory sessionFactory;
public MyTable myMethod1() {
Query query = session.getNamedQuery("abc")
.setInteger("id",1).setString("name", "testname");
return (MyTable) query.uniqueResult();}
public MyTable myMethod2() { ...}
@Service
public class MyTableServiceImpl implements MyTableService
@Autowire
protected MyTableDAO myTableDAO;
public MyTable myMethodService() {
//Some logic
...
return myTableDAO.myMethod1()
}
使用命名查询的目的是在应用启动时编译和验证它们请参阅hibernate 中命名查询的优势?
The purpose of having the named queries is that they are compiled and validated at app start-up timeSee Advantages of Named queries in hibernate?
我建议您考虑 GenericDAO 模式
这篇关于spring 休息服务-hibernate dao-注释-pojo-namedqueries的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!