Hibernate映射保存问题

时间:2017-08-01 20:51:23

标签: java 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。 我的代码出了什么问题?第二天晚上没睡觉......

1 个答案:

答案 0 :(得分:0)

在我的数据库中,我有一个id = 0的用户。这很奇怪,但是休眠假设如果用户id = 0,则用户在DB中不存在。真奇怪。我只是将id更改为1,它的工作正常。