Вопрос

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.

Это было полезно?

Решение

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

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top