开发者

JPA EntityManager question

开发者 https://www.devze.com 2023-03-15 09:42 出处:网络
I\'m quite new to both JPA/Hibernate and to Java, and am having some trouble with the basics of using the EntityManager class to manage persistent objects.I would appreciate it very much if someone wo

I'm quite new to both JPA/Hibernate and to Java, and am having some trouble with the basics of using the EntityManager class to manage persistent objects. I would appreciate it very much if someone would explain something very basic to me, because I can't figure it out from the documentation.

JPA 2 / Hibernate / Postgresql in a JSE environment.

* Class definitions below *

The following works as I would expect it to:

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

But this does not remove the links from the parts to the cars in the database:

tx.begin();
corolla.getParts().clear();
tx.commit();

Why is this the case?

Thanks in advance, and sorry if this is a silly question.

Mike.

Car class:

@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; }

....

}

Part class:

@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 thi开发者_如何学JAVAs.car; }
public void setCar( Car car ) { this.car = car; }

...

}


When sides of bidirectional relationship disagree, a state of the owning side (i.e. a side without mappedBy) is persisted to the database. So, you need to modify both sides consitently:

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


It looks fine, however while removing an entity from your database you should be using:

EntityManager.remove
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号