【问题标题】:JPA EntityManager questionJPA EntityManager 问题
【发布时间】:2011-06-27 07:32:12
【问题描述】:

我对 JPA/Hibernate 和 Java 都很陌生,并且在使用 EntityManager 类管理持久对象的基础知识方面遇到了一些麻烦。如果有人能向我解释一些非常基本的东西,我将不胜感激,因为我无法从文档中弄清楚。

JSE 环境中的 JPA 2 / Hibernate / Postgresql。

* 下面的类定义 *

以下工作如我所料:

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();

为什么会这样?

在此先感谢,如果这是一个愚蠢的问题,我们深表歉意。

迈克。

汽车类:

@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 对这篇帖子的回答 stackoverflow.com/questions/949427/… 中关于在对象设计中嵌入关系的一点帮助我解决了这个问题。

标签: hibernate jpa persistence entitymanager


【解决方案1】:

当双向关系的双方不一致时,拥有方的状态(即没有mappedBy的一方)被持久化到数据库中。所以,你需要不断地修改两边:

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

【讨论】:

  • 我需要的是关于拥有方被持久化的一点。非常感谢!
【解决方案2】:

看起来不错,但是在从数据库中删除实体时,您应该使用:

EntityManager.remove

【讨论】:

  • 我认为这不是我要找的:我不想从数据库中删除零件,而是删除它们与特定汽车的关联。不过谢谢:)
猜你喜欢
  • 2011-10-09
  • 2012-04-18
  • 2013-07-25
  • 2011-01-22
  • 1970-01-01
  • 1970-01-01
  • 2011-05-03
  • 1970-01-01
  • 2023-03-23
相关资源
最近更新 更多