只插入多对多Hibernate

时间:2016-06-04 12:23:31

标签: hibernate spring-mvc jpa orm

我有2个表(用户和公告),现在可以将更多用户分配到一个公告(关系是多对多), 在我的控制器中,我有:

@Autowired
private AnnouncementService announcementService;

    User user = (User) httpSession.getAttribute("userAccount");
    Announcement announcement = announcementService.getAnnouncement(announcementId);
    user.getAssignedUsersToAnnouncement().add(announcement);
    announcement.getAnnouncementsAssignedToUsers().add(user);

我不想再在我的数据库中保存这些对象,我只想在第三个对象中保存关系(“Assigned_Users”)。        要坚持现在,我应该做这样的事情:

announcementService.save(announcement); //due to this will be dublicates in my table
Announcement class{
   @ManyToMany(fetch = FetchType.EAGER)
   @JoinTable(name = "Assigned_Users",
           joinColumns = {@JoinColumn(name = "anunt_id")},
            inverseJoinColumns = {@JoinColumn(name = "user_id")} )
   private Set<User> announcementsAssignedToUsers = new HashSet<User>();
}
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "Assigned_Users",
        joinColumns =  {@JoinColumn(name = "user_id")},
        inverseJoinColumns = {@JoinColumn(name = "anunt_id")})
private Set<Announcement> assignedUsersToAnnouncement = new HashSet<Announcement>();

我在那里的用户和公告已经存在于DB中,我不想再保存它们。如何解决这个问题,并插入多个表中

1 个答案:

答案 0 :(得分:0)

首先,您只需要将关系的操作侧映射到@JoinTable。另一方面,您只需要设置mappedBy属性。所以你的关系看起来像这样

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "Assigned_Users",
       joinColumns = {@JoinColumn(name = "anunt_id")},
        inverseJoinColumns = {@JoinColumn(name = "user_id")} )
private Set<User> announcementsAssignedToUsers = new HashSet<User>();


@ManyToMany(fetch = FetchType.EAGER, mappedBy = "announcementsAssignedToUsers")
private Set<Announcement> assignedUsersToAnnouncement = new HashSet<Announcement>();

其次,这种类型的逻辑应该在服务类中,而不是在控制器中。从控制器,您应该只将id传递给服务方法,然后通过服务类中的id获取所需的实体。像这样的东西

// controller
@Autowired
private AnnouncementService announcementService;

    announcementService.assignUserToAnnouncement(user.getId(), annoucmentId);

// service

@Transactional
public void assignUserToAnnouncement(Long userId, Long announcementId) {
    User user = userRepository.getById(userId);
    Announcement announcement = annRepository.getById();
    user.getAssignedUsersToAnnouncement().add(announcement);
    announcement.getAnnouncementsAssignedToUsers().add(user);
    annRepository.save(announcement);
    userRepository.save(user);
}