简体   繁体   English

Hibernate,按id或唯一列选择

[英]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. 我正在使用hibernate for Java,我希望能够通过数据库中的id或名称选择用户。

Nice thing about Hibernate is that it caches the result by id, but I seem to be unable to make it cache by name. 关于Hibernate的好处是它通过id缓存结果,但我似乎无法按名称进行缓存。

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. 如果我多次使用GetUser(1),hibernate将只显示它第一次执行。

But every time I use GetUser("user1"), hibernate shows that it is executing a new query to database. 但每次我使用GetUser(“user1”)时,hibernate都会显示它正在对数据库执行新查询。

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 http://www.javalobby.org/java/forums/t48846.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM