在Entity类中使用命名查询的最佳实践是什么?

时间:2012-09-18 12:12:16

标签: hibernate

我在带有注释的Hibernate Entity类中使用命名查询 如果每个实体类有多个查询,我应该遵循哪些最佳实践?

Note: We have ruled the idea of putting queries in any property file or hbm.xml file

1 个答案:

答案 0 :(得分:3)

@Entity
@NamedQueries({@NamedQuery(name = User.byUsername, query = "select u from User u where u.username = :username"),
        @NamedQuery(name = User.follows, query = "select u from Follow as f inner join f.following as u where f.user = :user")})
public final class User extends Base implements UserDetails {

   static public final String byUsername = "User.byUsername";
   static public final String follows = "User.follows";
...
}

然后您可以在其他地方引用User.byUsername等,因此只能引用一个字符串。而且你得到了所有预测的intellitext优点。如下所示:

Session session = sessionFactory.getCurrentSession();
Query query = session.getNamedQuery(User.follows);