2017-08-01 148 views
1

我有兩個問題entityes在我的項目領域: 第一:Hibernate映射減排問題

public class User implements UserDetails { 
    private static final long serialVersionUID = -8442780593066407492L; 
    @Id 
    @Column(name = "id") 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private long id; 

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) 
    @JoinTable(name = "user_role", 
      joinColumns = {@JoinColumn(name = "user_id")}, 
      inverseJoinColumns = {@JoinColumn(name = "role_id")}) 
    private Set<UserRole> userRoles = new HashSet<UserRole>(); 

    @OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE) 
    private Set<CommentReserv> comments = new HashSet<CommentReserv>(); 

    public Collection<? extends GrantedAuthority> getAuthorities() { 
     List<SimpleGrantedAuthority> result = new 
     ArrayList<SimpleGrantedAuthority>(); 
     for (UserRole userRole: userRoles) { 
      result.add(new 
      SimpleGrantedAuthority(userRole.getListRole().name())); 
      } 
     return result; 
    } 
... 
} 

二:

public class CommentReserv implements Serializable { 
    private static final long serialVersionUID = 1579363480188238317L; 

    @Id 
    @Column(name = "id") 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private long id; 

    @ManyToOne 
    @JoinColumn(name = "reservation_id") 
    private Reservation reservation; 

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) 
    @JoinColumn(name = "user_id") 
    private User user; 
... 
} 

三:

public class Reservation implements Serializable{ 
    private static final long serialVersionUID = -9007238193656173229L; 

    @Id 
    @Column(name = "id") 
    private String id = generateId(); 
... 
    @OneToMany(mappedBy = "reservation", cascade = CascadeType.REMOVE) 
    private Set<CommentReserv> comments = new HashSet<CommentReserv>(); 
... 

然後我得到保留和用戶從DB ...

Reservation reservation = this.reservationRepository.getReservationById(params.get("reservationId").toString());    
User currentUser = this.userRepository.getUser(principal.getName()); 

(我檢查了它。用戶正確加載。) 並將其設置爲新的CommentReserv實例。

commentReserv.setReservation(reservation); 
commentReserv.setComment(params.get("comment").toString()); 
commentReserv.setUser(currentUser); 

當我試圖挽救新CommentReserv,我得到用戶拷貝在我的數據庫。 我嘗試從CommentReserv中刪除cascadetype,但它產生TransientObjectException。 我的代碼有什麼問題?第二晚沒有睡覺...

+0

你能分享預訂代碼嗎? –

+0

已添加預訂代碼 –

+0

您能分享完整的例外 –

回答

0

在我的數據庫中我有一個id = 0的用戶。這很奇怪,但休眠假設,如果用戶id = 0,那麼用戶不存在於數據庫中。真奇怪。我只是將ID更改爲1,它工作正常。