我对JPA/Hibernate和Java都很陌生,在使用EntityManager类管理持久对象的基础知识方面遇到了一些麻烦。如果有人会为我解释一些非常基本的东西,我将非常感激,因为我无法从文档中找出它。在JSE环境中使用JPA 2/Hibernate/Postgresql。JPA EntityManager问题
*类定义如下*
,我会期待它下面的工作:
em.getTransaction().begin();
Car corolla = new Car();
Part clutch = new Part();
clutch.setCar(corolla);
Part bumper = new Part();
bumper.setCar(corolla);
em.persist(corolla);
em.persist(clutch);
em.persist(bumper);
em.getTransAction().commit();
但这不会删除从零件链接到汽车数据库:
tx.begin();
corolla.getParts().clear();
tx.commit();
为什么会出现这种情况?
在此先感谢,并对不起,如果这是一个愚蠢的问题。
Mike。
车类:
@Entity
public class Car {
private Long id;
private Set<Part> parts;
....
public Car() { parts = new HashSet<Part>(); }
@Id
@GeneratedValue(generator="increment")
@GenericGenerator(name="increment", strategy = "increment")
public Long getId() { return id; }
private void setId(Long id) { this.id = id; }
@OneToMany(mappedBy="car", cascade=CascadeType.ALL)
public Set<Part> getParts() { return this.parts; }
public void setParts(Set<Part> parts) { this.parts = parts; }
....
}
部件类:
@Entity
public class Part {
private Long id;
private Car car;
...
public Part() {};
@Id
@GeneratedValue(generator="increment")
@GenericGenerator(name="increment", strategy = "increment")
public Long getId() { return id; }
private void setId(Long id) { this.id = id; }
@ManyToOne
@JoinColumn(name="car_id")
public Car getCar() { return this.car; }
public void setCar(Car car) { this.car = car; }
...
}
从axtavt(下)的答案,再加上有关嵌入的对象设计的关系,duffymo的答案,这个帖子http://stackoverflow.com/questions位/ 949427/is-it-need-to-call-a-flush-jpa-interface-in-this-situation帮助我解决了这个问题。 – mdtsandman