2015-08-02 2 views
0

Можете ли вы мне помочь с какой-то проблемой? Я два объекта проект и Page связаны «один ко многим»:Hibernate jpa oneToMany: как добавить в «один» список многих детей

модели проекта (также связанной с моделью пользователя)

@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 
@JsonProperty 
private Integer id; 

@ManyToOne(optional = false, fetch = FetchType.EAGER) 
@JoinColumn(name = "username", referencedColumnName = "username", foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) 
private User user; 

@Column(name="projectName", unique = true, nullable = false) 
@JsonProperty 
private String projectName; 

@Column(name="style") 
@JsonProperty 
private String style; 

@Column(name="menu") 
@JsonProperty 
private String menu; 

@JsonProperty 
@Fetch(value = FetchMode.SELECT) 
@OneToMany(orphanRemoval=true, mappedBy = "project", cascade = {CascadeType.ALL}, fetch = FetchType.EAGER) 
private Set<Page> pages; 
//getters and setters 

Страницы модель:

@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 
@JsonProperty 
private Integer id; 

@Column(name="content") 
@JsonProperty 
private String content; 

@Column(name="pageName", nullable = false) 
@JsonProperty 
private String pageName; 

@ManyToOne(optional = false) 
@JoinColumn(name = "project", referencedColumnName = "projectName", foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) 
private Project project; 
//getters and setters 

Теперь я хочу сделать что-то вроде этого:

@Override 
public void updatePages(Set<Page> pages, Integer projectId) { 
    Project project = entityManager.find(Project.class, projectId); 
    project.setPages(pages); 
} 

Но имеют Hibernate запросы без результатов и ошибок.

Hibernate: 
select 
    project0_.id as id1_1_0_, 
    project0_.menu as menu2_1_0_, 
    project0_.projectName as projectN3_1_0_, 
    project0_.style as style4_1_0_, 
    project0_.username as username5_1_0_, 
    user1_.id as id1_4_1_, 
    user1_.email as email2_4_1_, 
    user1_.enabled as enabled3_4_1_, 
    user1_.password as password4_4_1_, 
    user1_.username as username5_4_1_, 
    userroles2_.username as username3_4_2_, 
    userroles2_.id as id1_2_2_, 
    userroles2_.id as id1_2_3_, 
    userroles2_.role as role2_2_3_, 
    userroles2_.username as username3_2_3_ 
from 
    projects project0_ 
inner join 
    users user1_ 
     on project0_.username=user1_.username 
left outer join 
    roles userroles2_ 
     on user1_.username=userroles2_.username 
where 
    project0_.id=? 
Hibernate: 
/* load project.model.User */ select 
    user0_.id as id1_4_2_, 
    user0_.email as email2_4_2_, 
    user0_.enabled as enabled3_4_2_, 
    user0_.password as password4_4_2_, 
    user0_.username as username5_4_2_, 
    projects1_.username as username5_4_4_, 
    projects1_.id as id1_1_4_, 
    projects1_.id as id1_1_0_, 
    projects1_.menu as menu2_1_0_, 
    projects1_.projectName as projectN3_1_0_, 
    projects1_.style as style4_1_0_, 
    projects1_.username as username5_1_0_, 
    userroles2_.username as username3_4_5_, 
    userroles2_.id as id1_2_5_, 
    userroles2_.id as id1_2_1_, 
    userroles2_.role as role2_2_1_, 
    userroles2_.username as username3_2_1_ 
from 
    users user0_ 
left outer join 
    projects projects1_ 
     on user0_.username=projects1_.username 
left outer join 
    roles userroles2_ 
     on user0_.username=userroles2_.username 
where 
    user0_.username=? 
Hibernate: 
select 
    pages0_.project as project4_1_0_, 
    pages0_.id as id1_0_0_, 
    pages0_.id as id1_0_1_, 
    pages0_.content as content2_0_1_, 
    pages0_.pageName as pageName3_0_1_, 
    pages0_.project as project4_0_1_ 
from 
    pages pages0_ 
where 
    pages0_.project=? 

Я хочу обновить страницы в проекте. Каков наилучший способ сделать это?

UPD

Project project = entityManager.find(Project.class, projectId); 
    entityManager.createQuery("DELETE FROM Page p WHERE p.project = :project") 
      .setParameter("project",project) 
      .executeUpdate(); 

ответ

1

Владелец сторона ассоциации Project-страницы на Page лица, в спящем режиме (так как он решает двунаправленный один-ко-многим), это означает, что вы должны установите Page.project за каждые Page, которые вы хотите связать с Project. Он не будет работать, если вы только добавите страницы в коллекцию страниц проекта.

ли это,

@Override 
public void updatePages(Set<Page> pages, Integer projectId) { 
    Project project = entityManager.find(Project.class, projectId); 
    for (Page p: pages) { 
    p.setProject (project); 
    //the pages are new? then also do em.persist(p) 
    } 
} 

ЗЕЬЕСТА вы видите прямо сейчас, по вашей модели сущностей, которые необходимы для получения проекта и генерируются при вызове методы entityManager.find.

+0

Благодарим за ответ! Но моих Set страниц пока нет в базе данных. Это происходит с клиентской стороны. В этом случае он будет работать? – jahra

+0

Полагаю, что, поэтому я отредактировал ответ, см. Комментарий в коде :) – Guillermo

+0

Он работает! Большое спасибо! Вы действительно спасли меня :) – jahra

Смежные вопросы