开发者

Hibernate, select by id or unique column

I am using hibernate for Java, and I want to be able to select users by id or by name from the database.

Nice thing about Hibernate is that it caches the result by id, but I seem to be unable to make it cache by name.

static Session openSession = Factory.openSession();

public static User GetUser(int Id) {
    return (User) openSession.get(User.开发者_运维知识库class, new Integer(Id));
}

public static User GetUser( String Name ){
   return (User) openSession.createCriteria( User.class ).
           add( Restrictions.eq("username", Name) ).
           uniqueResult();

}

If I use GetUser(1) many times, hibernate will only show that it executed the first time.

But every time I use GetUser("user1"), hibernate shows that it is executing a new query to database.

What would be the best way to have the string identifier be cached also?


You need to use the query cache to avoid the database access when querying by name.

http://www.javalobby.org/java/forums/t48846.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜