Hibernate HQL - 包括从PK到查询的列

时间:2014-02-27 10:33:03

标签: hibernate hql spring-roo

我使用Spring Roo对现有数据库进行逆向工程,以便在现有数据库上进行hibernate建模,在存在复合主键的情况下,它会生成XyzClass和XyzClassPK。

如果我想对属于复合主键的某些列执行HQL查询,则会出现错误,假设复合主键由primaryKey1和primaryKey2组成:

String hql = "select o from XyxClass o where primaryKey1 = :key1 and nonPrimaryKey = :key2";
    TypedQuery<XyzClass> query = entityManager().createQuery(hql, XyzClass.class);
    query.setParameter(......
    query.setParameter(......
    query.getResultList()
  

引起:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:   'where子句'中的未知列'primaryKey1'           at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)           at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)           at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)           at java.lang.reflect.Constructor.newInstance(Constructor.java:526)           在com.mysql.jdbc.Util.handleNewInstance(Util.java:411)           在com.mysql.jdbc.Util.getInstance(Util.java:386)           在com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)           在com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)           在com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)           在com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)           在com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)           在com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2624)           at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2127)           在com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2293)           在org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)           在org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)           at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:56)

这些是ROO生成的注释:

@RooJavaBean
@RooToString
@RooJpaActiveRecord(identifierType = XyzClassPK.class, versionField = "", table = "XYZ_CLASS")
@RooDbManaged(automaticallyDelete = true)
public class XyzClass {

主键:

@RooIdentifier(dbManaged = true)
public final class XyzClassPK {

    @Column(name = "PRIMARY_KEY1", nullable = false)
    private Integer primaryKey1;

    @Column(name = "PRIMARY_KEY2", nullable = false)
    private Integer primaryKey2;

我的HQL显然不正确,如何在我的hql查询中包含复合主键?

2 个答案:

答案 0 :(得分:3)

您的HQL应如下所示:

String hql = "select o from XyxClass o where o.xyz.primaryKey1 = :key1 and o.nonPrimaryKey = :key2";

其中xyz是XyxClass中Id字段的名称(我在代码中看不到它...) 希望这有帮助!

答案 1 :(得分:0)

使用@Embeddable注释(属性:其id和两个PK)为您的实体PK(例如EntityPK)创建一个类,然后在实体的类中添加一个私有EntityPK entityPk属性。在HQL中以这种方式使用它:...来自实体e,其中e.entityPk.pk1 =:primaryKey1和e.attribute =:attribute