Java持久性复合ID

时间:2017-01-29 21:21:58

标签: java hibernate jpa spring-data javax

我尝试使用复合主键插入记录,但在保存新记录时,我收到此消息:

  

e =(org.springframework.orm.jpa.JpaSystemException)   org.springframework.orm.jpa.JpaSystemException:无法设置字段   通过反射值[POST_INSERT_INDICATOR]值...

public class AppConfig extends WebMvcConfigurerAdapter {

    ...

    @Bean
    public BuildingService buildingService(){
        return new BuildingService();
    }

    @Override
    public void addFormatters (FormatterRegistry registry) {
        registry.addConverter(new  BuildingIdToBuildingConverter(buildingService()));
    }
}

有没有人见过这样的错误?

1 个答案:

答案 0 :(得分:0)

要创建复合主键,您可以参考此示例

@Entity
@Table(name="testuserrole")
public class UserRole{
    @EmbeddedId
    private UserRoleId id = new UserRoleId();

    public UserRoleId getId() {
        return id;
    }

    public void setId(UserRoleId id) {
        this.id = id;
    }

    @Transient
    public long getUserId() {
        return id.userId;
    }

    public void setUserId(long userId) {
        id.userId=userId;
    }

    @Transient
    public long getRoleId() {
        return id.roleId;
    }

    public void setRoleId(long roleId) {
        id.roleId=roleId;
    }

}

@Embeddable
class UserRoleId implements Serializable {

    @Column(name = "user_id")
    public long userId;

    @Column(name = "role_id")
    public long roleId;

}