开发者

JPA Cascade Persist not working

I have two classes : Expenditure and Category. An Expenditure can have multiple Categories. I wish to implement Cascade save o开发者_运维知识库f all Categories(children) with Expenditure(parent). But unable to achieve this.On persisting Expenditure record no Category entries are created. Please let me know what I am doing wrong. Here are my classes:

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


Try adding

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

And also don't mix up the field and property access types in your entity classes.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜