坚持与JPA

时间:2018-05-25 14:55:47

标签: java spring hibernate jpa

我有4个与OneToMany Realtionship和JPA相关的实体。我对如何坚持实体感到困惑。坚持这4个实体的正确方法是什么(我不想使用cascade.persist)。我使用Spring和Hibernate。我将仅在我的实体中放置相关字段以使其变得简单。

响应实体:

@Entity
public class Response{
@Id 
private long responseID;
@OneToManye(mappedBy="response")
List <Income> incomes;
}

收入实体:

  @Entity
    public class Income{
    @Id 
    private long incomeID;
    @ManytoOne
    JoinColumn(name="RESPONSE_ID")
    private Response response;
    @OneToManye(mappedBy="income")
    List <IncomeBlock> incomeBlocks;
    }

IncomeBlock实体:

 @Entity
    public class IncomeBlock{
    @Id 
    private long incomeBlockID;
    @ManytoOne
    JoinColumn(name="INCOME_ID")
    private Income income;
    @OneToManye(mappedBy="incomeBlock")
    List <IncomeDetail> incomeDetails;
    }

IncomeDetail实体:

 @Entity
    public class IncomeDetail{
    @Id 
    private long incomeDetailID;
    @ManytoOne
    JoinColumn(name="INCOME_BLK_ID")
    private IncomeBlock incomeBlock;
    }
谢谢你们的帮助。 到目前为止,我尝试了两种方法:

创建收入详情:

IncomeBlock incomeBlock=new IncomeBlock ();
 em.persist (incomeBlock);
 IncomeDetail incomeDetail=new IncomeDetail ();
 incomeBlock.addIncomeDetail(incomeDetail);
 em.persist(incomeDetail);

创建incomeBlock:

 IncomeBlock incomeBlock=new IncomeBlock ();
 Income income=new Income();
 em.persist (income);
 IncomeDetail incomeBlock=new IncomeBlock ();
 income.addIncomeBlock(incomeBlock);
 em.persist(incomeDetail);

到目前为止,我尝试了这两种方法,并且不会在数据库中持续存在。

1 个答案:

答案 0 :(得分:0)

如果要与实体保持OneToMany关系,则需要在声明关系时定义cascadeType。 e.g。

@OneToMany(cascade = CascadeType.ALL, mappedBy="income")
List <IncomeBlock> incomeBlocks;

详情请参阅https://docs.oracle.com/javaee/5/api/javax/persistence/OneToMany.html

如果您不想使用cascade,可以尝试以下代码段:

 Income income=new Income();
 IncomeBlock incomeBlock=new IncomeBlock ();
 IncomeDetail incomeDetail=new IncomeDetail ();
 incomeBlock.addIncomeDetail(incomeDetail);
 income.addIncomeBlock(incomeBlock);
 em.persist(income);