3

Since the "open session in view" pattern have some drawbacks (see Why is Hibernate Open Session in View considered a bad practice?), I am wondering what is considered the best approach in displaying results from a hibernate query to a jsp page?

One method I thought of is put a java.util.list object in the request and output the contents to the jsp page. Are there other/better methods?

Community
  • 1
  • 1
morbidCode
  • 2,325
  • 5
  • 21
  • 47
  • The way I understand why OSIV is a bad practice is that you pass your DB objects into your front end software - a simple generic example would be to have DTO out of your entity objects, created by your backend and passed to your frontend. – Smutje Aug 02 '15 at 10:26

1 Answers1

1

The best way is to use DTO projections for your UI views. This way you can avoid LazyInitializationExceptions and make sure you only fetch what you need in a certain view. From a performance point of view, nothing beats an SQL projection anyway.

The DTO projection looks like this:

select new my.package.UserInfo(u.name, u.age, u.gender)
from Users u
Vlad Mihalcea
  • 103,297
  • 39
  • 432
  • 788
  • not sure I understand because I am new in hibernate. When you say DTO projections do you mean using Criteria Queries? – morbidCode Aug 02 '15 at 14:44
  • You can use both Criteria and HQL. The goal is to select everything into a DTO, instead of a root Entity. – Vlad Mihalcea Aug 02 '15 at 15:21
  • can you provide an example on selecting it all in a DTO? Do you mean something like this? session.createQuery(hql).list() – morbidCode Aug 02 '15 at 15:35
  • Done. But if you don't mind can you also provide an example on selecting it all in a DTO? I'm now studdiing how to do this but it would be really great if you provide an example for reference. Thanks. – morbidCode Aug 15 '15 at 10:32
  • we would put the result of the query to a list right? So is binding the list to a request object a great solution? – morbidCode Aug 15 '15 at 17:39
  • You get a LIst from this query, which you can then use it in a root response object, if that's what you want. – Vlad Mihalcea Aug 15 '15 at 17:49
  • thanks. I think I can use it like this: request.setAttribute("userInfo",userInfoList); or ther is a better way... – morbidCode Aug 15 '15 at 18:19
  • You can use it like that. – Vlad Mihalcea Aug 15 '15 at 18:34