1

Greetings!

I have the following class and at times need to retrieve only title and subTitle elements:

public class Article implements Serializable {

    private static final long serialVersionUID;
    private int id;
    private String title;
    private String subTitle;
    private String body;
    ....
}

What's the best way to facilitate this? I thought about making title and subTitle stand alone objects but I honestly don't know what I'm doing yet.

I have the luxury of changing the entire composition of Article, but asking first is the most sensible thing for me at the moment.

Thanks in advance.

brainimus
  • 10,586
  • 12
  • 42
  • 64
vector
  • 7,334
  • 8
  • 52
  • 80
  • Is there a specific reason you want to do this? Why does it matter if Hibernate loads the extra fields? You're not required to use them. – brainimus Jan 27 '11 at 13:22
  • ... in all honesty, it seems very counter intuitive to be loading everything when I need only a few bits. In practical terms I could load the whole thing, but then I'm thinking performance and scale, at least in theory. – vector Jan 27 '11 at 13:28
  • 3
    Not returning those fields is not going to affect performance. Worry about the functionality of your application, not making a 0.001 second query run 0.000000000001 second faster. – Phill Jan 27 '11 at 14:00
  • ... hm, premature optimization?!? – vector Jan 27 '11 at 14:07
  • ... Phill, if you post your comment as an answer, I'll at least vote it up, or accept it. – vector Jan 28 '11 at 15:59

3 Answers3

1

You can annotate every simple property with LAZY -> just like this @Basic(fetch = FetchType.LAZY)

So, it will be loaded only if you need

Plínio Pantaleão
  • 1,229
  • 8
  • 13
1

Provided this is for displaying purpose, you could also rely on a ResultTransformer.

See this SO answer which deals with similar problem and limits the retrieved properties.

Community
  • 1
  • 1
nulltoken
  • 64,429
  • 20
  • 138
  • 130
1

I think you can solve this by creating a specific class to hold the information you want, then you import it in your mapping. See 5.1.19.import in the manual. I believe you can use the imported class in your HQL, like this:

"select new Titles(a.title, a.subTitle) from Article a where a.id = :id"

Here's a blog post I found on this subject: http://gustavoringel.blogspot.com/2009/02/creating-dto-in-nhibernate-hql-using.html.

Good luck!

Daniel Lidström
  • 9,930
  • 1
  • 27
  • 35