JPA Cascade Persist不工作

时间:2011-05-01 14:39:19

标签: hibernate jpa

我有两个类:支出和类别。支出可以有多个类别。我希望用支出(父)实现所有类别(子)的级联保存。但是无法实现这一点。在持续支出记录中没有创建类别条目。请让我知道我做错了什么。这是我的课程:

@Entity
@Table(name="EXPENDITURE")
public class Expenditure {

    private Long id;

    @OneToMany(cascade={CascadeType.PERSIST,CascadeType.MERGE}, mappedBy="expenditure")
    private Set<Category> associatedCategories = new HashSet<Category>();   

    public Expenditure() {  }

    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="EXPENDITURE_ID")
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }

    public void addCategory(Category category)
    {
        this.associatedCategories.add(category);
        category.setExpenditure(this);      
    }
}

@Entity
@Table(name="CATEGORY")
public class Category {

    @Id @GeneratedValue
    @Column(name="CATEGORY_ID")
    private Long id;
    private String name;

    @ManyToOne(targetEntity=Expenditure.class)
    private Expenditure expenditure;

    public Category(){}
    public Category(String name)
    {
        this.name = name;
    }
    public Category(String name,String description)
    {
        this.name = name;
    }
    @Column(name="NAME")
    public String getName() {
        return name;
    }       

    public Expenditure getExpenditure() {
        return expenditure;
    }
    public void setExpenditure(Expenditure expenditure) {
        this.expenditure = expenditure;
    }

1 个答案:

答案 0 :(得分:0)

尝试添加

@ManyToOne(targetEntity=Expenditure.class)
@JoinColumn(name="parentExpenditureId")   // or whatever column name exists in your database schema
private Expenditure expenditure;

并且不要混淆实体类中的字段和属性访问类型。

相关问题