JPA OnetoOne关系删除

时间:2014-11-17 19:24:59

标签: java jpa orm eclipselink jpa-2.0

所以这个问题已被问了很多次,但我的问题有点不同。我有2个班级" PlaceType"和"地方"。 PlaceType类用于表示Place类型的对象,例如"餐馆,俱乐部,hotesl等"。每个类型的对象" Place"将有一个placeType。但这两者的存在并不相关。即当我删除Place时,不得在数据库中删除PlaceType。我正在使用Eclipselink。这两个类的代码如下所示。

@Entity
@Table(schema = "itmd4515", name = "placeType", uniqueConstraints = @UniqueConstraint(columnNames = "placeTypeName"))
public class PlaceType implements Serializable {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 255, unique = true)
@Size(max = 255, message = "The type of the Place must not be more than 255 characters")
@NotNull
private String placeTypeName;
@Size(max = 2500, message = "The Description should be no more than 2500 characters")
@NotNull
@Column(name = "placeTypeDesc", nullable = false, updatable = true)
private String placeTypeDesc;

地方的课程如下:

@Entity
@Table(schema = "itmd4515", name = "places", uniqueConstraints = @UniqueConstraint(columnNames = "locationOfThePlace"))

public class Places implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@NotNull
@OneToOne(cascade = CascadeType.PERSIST)
private PlaceType typeOfPlace;

删除数据库中数据的代码如下所示。

public boolean delete(Object id) {
    try {
        tx.begin();
        T entityToBeRemoved = em.getReference(entityClass, id);
        LOG.info("The Entity to be removed"+entityToBeRemoved.toString());
        em.remove(entityToBeRemoved);
        tx.commit();
        return true;
    } catch (Exception ex) {
        LOG.info("There was an exception while deleting the object" + entityClass.getName() + ex.getMessage());
        tx.rollback();
        return false;
    }
}

现在在jUnit测试中,我为PlaceType和Places类创建一个测试对象,插入它然后将其删除。插入正在运行,但删除由于某种原因不起作用。我试图使用Cascade.REMOVE,但仍然无法正常工作。有人可以让我知道我做错了什么吗?

此外,我试图删除" Places"而不是" PlaceType"在数据库中。因为许多"地点"可以共享一个PlaceType。我确信我在设计上做错了。如果有人指出正确的方法,这将是非常有帮助的。感谢。

0 个答案:

没有答案