简体   繁体   中英

persist several OneToMany relationships with JPA

I have 4 entities related with OneToMany Realtionship with JPA . I m confused on how to persist in the entities .What is the correct way to persist this 4 entities (I don t want to use cascade.persist).I use Spring and Hibernate. I will put only relevant fields in my entities to make it simple.

Response Entity :

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

Income entity :

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

IncomeBlock entity :

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

IncomeDetail entity :

 @Entity
    public class IncomeDetail{
    @Id 
    private long incomeDetailID;
    @ManytoOne
    JoinColumn(name="INCOME_BLK_ID")
    private IncomeBlock incomeBlock;
    }

thank you guys for your help . so far I tried 2 methods :

create incomeDetail :

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

create incomeBlock :

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

I tried this 2 methods so far and that doesn't persist in database .

If you want to persists OneToMany relation with your entity, you need to define cascadeType while declaring the relation. eg

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

For details please refer https://docs.oracle.com/javaee/5/api/javax/persistence/OneToMany.html

If you don't want to use cascade , you can try below snippet of code :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM