2011-06-27 97 views
0

我对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; } 

... 

} 
+0

从axtavt(下)的答案,再加上有关嵌入的对象设计的关系,duffymo的答案,这个帖子http://stackoverflow.com/questions位/ 949427/is-it-need-to-call-a-flush-jpa-interface-in-this-situation帮助我解决了这个问题。 – mdtsandman

回答

3

当双方的双向关系不一致,拥有一方的状态(即没有0​​的一方)是坚持到数据库。所以,你需要consitently修改双方:

for (Part p: corolla.getParts()) { 
    p.setCar(null); 
} 
corolla.getParts().clear(); 
+0

关于拥有的一面正在坚持的一点是我需要的。非常感谢! – mdtsandman

0

它看起来不错,但是,同时从数据库中删除一个实体,你应该使用:

EntityManager.remove 
+0

我不认为这是我正在寻找的东西:我不想从数据库中删除零件,而是删除它们与特定汽车的关联。谢谢,虽然:) – mdtsandman