java 休眠,按 id 或唯一列选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3058660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:08:42  来源:igfitidea点击:

Hibernate, select by id or unique column

javahibernateselectunique

提问by Nican

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

我正在为 Java 使用 hibernate,我希望能够从数据库中按 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?

同时缓存字符串标识符的最佳方法是什么?

采纳答案by btreat

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