2

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

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

1 回答 1

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在其他任何地方引用 etc,因此只有一个字符串引用。你得到了所有预测智能文本的好处。如下所示:

Session session = sessionFactory.getCurrentSession();
Query query = session.getNamedQuery(User.follows);
于 2012-09-18T12:36:14.520 回答