I have an entity A that have 3 attributes having reference to another entity B. From a relational POV, this is fine because I may have 3 different ids from table B stored as different columns in table A. To provide further clarification, my table A has 3 columns called manager_id, supervisor_id, worker_id. All three columns have reference to an employee table(table B). But in JPA, when the entity manager builds the entity A (corresponding to table A), if more than one of the three columns have the same id, entity 开发者_开发问答A will not have individual objects of Entity B, but will point to the same reference. (As an example, if manager_id and supervisor_id is '12345' then when Entity A is built, the fields mapped to the manager_id and supervisor_id will point to the same reference object of Entity B with id = '12345'
This is fine until commit time. Whenever I change manager_id tp '67891', then supervisor_id also gets stored with this id because they pointed to the same reference. This is wrong. How can I configure the framework to either get individual reference objects for each attribute regardless of whether they point ot he same object or not, or specify that the entity manager persists only the field that was changed? I dont want to write a native query for this.
Any advice would be much appreciated!
If the database table's manager_id and supervisor_id columns have the same value, then the corresponding properties in the entity will point to the same object. This is normal, correct, JPA behaviour, and is not something you can or should try to avoid.
You talk about changing the manager_id value. How are you doing that? I believe you should be able to change the object to which the corresponding properties refer, and have JPA change the value in the database correctly.
In code:
@Entity
public class A {
@ManyToOne @Column(name="manager_id")
private B manager;
@ManyToOne @Column(name="supervisor_id")
private B supervisor;
@ManyToOne @Column(name="worker_id")
private B worker;
public void setManager(B manager) {
this.manager = manager;
}
}
A a;
B b67891;
a.setManager(b67891);
To see a complete, self-contained, example of this, see:
- https://gist.github.com/1188549
精彩评论