我有2個實體,比如汽車和引擎(只是示例名稱,但邏輯相同)。無法使用@MapsId和@Id進行查詢,但只能使用@Id
@Entity
public class Car {
@Id
private Long id;
@OneToOne(mappedBy = "car", cascade = Cascade.ALL)
private Engine engine;
...
}
@Entity
public class Engine {
@Id
private Long id; // 1
@MapsId // 2
@OneToOne
@JoinColumn(name = "car_id") // join column is optional here
private Car car;
...
}
所以,後來我做的:
em.save(car); // successfully saved, data is in the database, but (see below)
TypedQuery<Engine> query = em.createQuery("select engine from Engine engine where engine.car = :car", Engine.class)
query.setParameter("car", car);
query.getResultList();
拋出異常:
ERROR [main] (JDBCExceptionReporter.java:234) - No value specified for parameter 1.
WARN [main] (TestContextManager.java:409) - Caught exception while allowing TestExecutionListener [org.springframew[email protected]17e5cbd] to process 'after' execution for test: method , exception [org.springframework.orm.jpa.JpaSystemException: org.hibernate.exception.DataException: could not execute query; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.DataException: could not execute query]
但是,如果我改變引擎的實體只有有@Id對汽車本身的實例(刪除//1並將// 2更改爲@Id)它的工作原理。
根據JPA文檔,它應該以同樣的方式工作(至少我期望)。
我的環境:PostgreSQL 9,Spring框架3.1,Hibernate 3.6.8.Final,Tomcat 7(JPA支持被Spring Instrumentation添加)。
更新: 我已經試過的EclipseLink既映射和它的工作。所以問題可能與Hibernate有關。仍然不知道如何強制它與Hibernate一起工作。
如果刪除JoinColumn會發生什麼?同時擁有JoinColumn和MapsId似乎是矛盾的。第一個說:使用專用列,第二個說:使用與ID相同的列。 – 2012-07-28 06:10:57
什麼都不會發生。這種情況下的JoinColumn是可選的,它用於爲\ @Id字段設置\ @Column。如果錯過了,則默認使用默認的@JoinColumn,因此使用缺省的\ @JoinColumn中的@ @Id的默認列名。我真的覺得這可能是Hibernate中的錯誤,當然,當然,直到有人證明這一點。 – akazlou 2012-07-29 05:14:05