我項目中,我不得不類一對多,org.hibernate.QueryException:無法解析屬性
@Entity
@Table(name = "asset")
public class Asset extends BaseEntity {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "last_position")
private Position lastPosition;
/**contructor, getter, setter method, other field etc..**/
}
和其他類
@Entity
@Table(name = "position")
@EntityListeners(EntityChangeCallback.class)
public class Position extends BaseEntity {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy="lastPosition")
private List<Asset> assets;
/**contructor, getter, setter method, other field etc..**/
}
數據訪問對象這樣
public abstract class BaseDaoImp<E extends Indexable> implements BaseDao<E> {
@PersistenceContext
protected EntityManager em;
/**some thing else**/
@SuppressWarnings("unchecked")
public List<E> list() {
Query qry = em.createQuery("from " + getType().getSimpleName() + " u");
return qry.getResultList();
}
}
當我運行代碼。我得到的錯誤
產生的原因:java.lang.IllegalArgumentException異常: org.hibernate.QueryException:無法解析屬性: lastPositionId的:com.abc.server.db.entity.Asset [FROM COM .abc.server.db.entity.Position pos WHERE pos.deviceId IN ('100 000000001000','100000000001001','100000000001002')AND pos.id IN (SELECT asset.lastPositionId FROM com.tma.ats.am .server .db.entity.Asset asset)]
我發現問題是Hibernate用字段生成查詢名稱lastPositionId而不是lastPosition。我將字段名稱從lastPosition更改爲lastPositionId。一切正常。但我在網上和我自己的項目中閱讀了很多例子。所有其他領域可以映射@ManyToOne好吧,他們不需要Postfix Id。我如何使上面的代碼與字段名lastPosition(不lastPositionId)工作? 感謝您的幫助。