春天休息服务 - 休眠道 - 注解 - POJO - namedqueries [英] spring rest service - hibernate dao - annotations - pojo - namedqueries

查看:211
本文介绍了春天休息服务 - 休眠道 - 注解 - POJO - namedqueries的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含了一些命名查询来获得数据的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?

请注意:我没有一个DAO接口或类以上的MyTable类

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()

  }

具有命名查询的目的是,它们被编译并在应用程序的启动时间验证
见<一href=\"http://stackoverflow.com/questions/7769447/advantages-of-named-queries-in-hibernate\">Advantages在Hibernate命名查询的?

我建议你会考虑 GenericDAO模式

这篇关于春天休息服务 - 休眠道 - 注解 - POJO - namedqueries的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆