开发者

Hibernate: Retrieving Lists

I am a beginner with hibernate. My intetions are really simple: I ha开发者_JAVA百科ve mapped objects into one table with annotations. Now I want to retrieve them as a List of objects to display them. Later I want to implement simple filters.

Do I need to write SQL Queries? or is there a kind of Annotation based method?


Option 1: see Rupeshit's solution!

One question for that: what kind of list should I use? hibernate or util?


Is that maybe a option too?: link


Well, if you want to retrieve a list of Entities matching some conditions you have somehow to do a query. Hibernate offers several ways do do this:

Option 1: Using the Hibernate Query Language. HQL is close to SQL except that you work on objects and associations rather than tables. HQL is also portable (SQL is generated depending on the Dialect). This is the traditional way to go.

Query q = session.createQuery("from foo Foo as foo where foo.name=:name");
q.setParameter("name", "bar"); 
List foos = q.list();

Option 2: Using the Criteria API. When using the Criteria API, you write queries using an object oriented API. This API is especially nice for dynamic queries. Criteria queries are also portable.

List cats = session.createCriteria(Cat.class)
    .add( Restrictions.like("name", "Fritz%") )
    .add( Restrictions.between("weight", minWeight, maxWeight) )
    .list();

Option 3: Using Native SQL Queries. You usually use native SQL only if you want to utilize database-specific features.

List cats = session.createSQLQuery("SELECT * FROM CATS").addEntity(Cat.class);

I would probably use HQL in your case.

References

  • Chapter 14. HQL: The Hibernate Query Language
  • Chapter 15. Criteria Queries
  • Chapter 16. Native SQL


You can do it like this....First of all create object of session......Then

 List<DomainClass> domainClass = session.createQuery("from DomainClass e where e.Id=23").list();

So you will get list of objects of your domain class type.


The best thing u can do to start with Hibernate (or in general with new Frameworks) is searching for tutorials to learn about all the basics. There are a lot of beginners tutorials for hibernate, like a documentation site from hibernate themselves. This tutorial is ok, eventhough there are some little mistakes in it, but with little search you'll even find better ones, which should fit ur needs.

To answer your question: u normally write HQL orders (which is basically almost same like SQL, just working with domain objects instead) to receive the data u want to.

The example from Rupeshit might be a bit confusing, since (if I get it right), the list will always just have one entry, since Id is supposed to be the primary key from domainClass, so there will be always just one match, but u get the entire idea of it.

EDIT: For resultlists u normally always use util-lists.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜