spring rest service - hibernate dao - annotations

2019-07-27 14:03发布

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.

2条回答
家丑人穷心不美
2楼-- · 2019-07-27 14:21

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.

查看更多
在下西门庆
3楼-- · 2019-07-27 14:38

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

查看更多
登录 后发表回答