spring rest service - hibernate dao - annotations - pojo - namedqueries

孤者浪人 提交于 2019-12-11 11:04:07

问题


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.


回答1:


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

  }

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




回答2:


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.



来源:https://stackoverflow.com/questions/19288364/spring-rest-service-hibernate-dao-annotations-pojo-namedqueries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!