如何在Hibernate OneToMany双向关系上自动映射父项?

时间:2017-10-03 18:30:45

标签: java spring hibernate jpa

我有两个实体之间的关系:

用户配置

@Getter
@Setter
@NoArgsConstructor
@Entity
@Table(name="userprofile")
public class UserProfile implements Identifiable, Displayable {

    @Id
    @GeneratedValue(generator = "uuid2", strategy = GenerationType.SEQUENCE)
    @GenericGenerator(name = "uuid2", strategy = "uuid2", parameters = { @org.hibernate.annotations.Parameter(name = "uuid_gen_strategy_class", value = "org.hibernate.id.uuid.CustomVersionOneStrategy") })
    private UUID id;

    @Column(length = 100)
    @NotNull
    private String name;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "userProfile", cascade = {CascadeType.ALL}, orphanRemoval = true)
    private List<UserPermission> permissions;

    @Override
    public String getDisplayString() {
        return name;
    }
}

UserPermission

@Getter
@Setter
@NoArgsConstructor
@Entity
@Table(name="userpermission")
public class UserPermission implements Identifiable {

    @Id
    @GeneratedValue(generator = "uuid2", strategy = GenerationType.SEQUENCE)
    @GenericGenerator(name = "uuid2", strategy = "uuid2", parameters = { @org.hibernate.annotations.Parameter(name = "uuid_gen_strategy_class", value = "org.hibernate.id.uuid.CustomVersionOneStrategy") })
    private UUID id;

    @NotNull
    @Column(length = 100)
    private String permission;

    @ManyToOne
    @JoinColumn(name = "profile_id")
    private UserProfile userProfile;

    private boolean canChange;
}

我有一个REST服务,它为这些实体公开CRUD服务。

这些信息是通过JSON收到的:

{
    name: 'Profile Name',
    permissions: [
        {
            permission: 'PERMISSION_1',
            canChange: true
        },
        {
            permission: 'PERMISSION_2',
            canChange: false
        }
    ]
}

杰克逊正在转换这些信息并创建我的DTO。 之后,使用dozer,我将这些数据映射到UserProfile实体的实例。

问题是,在保存时,Hibernate没有自动设置UserPermission实例中的userProfile属性,这给了我异常:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'profile_id' cannot be null

Hibernate是否会自动设置它们?怎么样?

我想避免在UserPermission实例中手动设置userProfile实例。有没有办法做到这一点?

谢谢。

0 个答案:

没有答案