Sleep mode, 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.

The good thing about Hibernate is that it caches the result by id, but I can't seem to make it a 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, hibernation will only show that it was running for the first time.

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

What would be the best way to cache a string identifier?

+3
source share

Source: https://habr.com/ru/post/1750418/


All Articles