无法使用SpringBoot在@Embeddable上设置UUID

时间:2019-02-19 20:44:02

标签: hibernate jpa

我想为@ManyToMany关系建立一个带有附加列的中间表。目前,我正在使用H2数据库,MariaDB / MySQL已计划上线。 我上课:

UserEntity

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class UserEntity {
    @Id
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
    private UUID id;

    @OneToMany(mappedBy = "userEntity",
            cascade = CascadeType.ALL,
            orphanRemoval = true)
    private Set<VoteEntity> votedRoutes = new HashSet<>();
}

RouteEntity

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class RouteEntity {
    @Id
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
    private UUID id;
    ...

    @OneToMany(mappedBy = "routeEntity",
            cascade = CascadeType.ALL,
            orphanRemoval = true)
    private Set<VoteEntity> votedUsers = new HashSet<>();
}

并且我有一个 VoteEntity 可以将它们保持在一起:

@Data
@NoArgsConstructor
@Entity
public class VoteEntity {
    @EmbeddedId
    private VoteEntityID id;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @MapsId("userId")
    private UserEntity userEntity;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @MapsId("routeId")
    private RouteEntity routeEntity;

    //... additional stuff
}

和ID的可嵌入类 VoteEntityID

@Embeddable
@Data
@NoArgsConstructor
public class VoteEntityID implements Serializable {
    private UUID userId;
    private UUID routeId;
}

我正在尝试使用方法添加UserService的投票

public void addVote(String userEmail, Route route) {
    UserEntity userEntity = findByEmail(userEmail);
    RouteEntity routeEntity = routeService.map(route);

    VoteEntity voteEntity = new VoteEntity();
    voteEntity.setUserEntity(userEntity);
    voteEntity.setRouteEntity(routeEntity);

    userEntity.getVotedRoutes().add(voteEntity);
    routeEntity.getVotedUsers().add(voteEntity);

    userRepository.save(userEntity);
    routeService.save(routeEntity);
}

每次尝试创建ID时,我都会收到错误消息:

  带有路径的Servlet [dispatcherServlet]中的

Servlet.service()   []抛出异常

     

[请求处理失败;嵌套异常为   org.springframework.orm.jpa.JpaSystemException:无法设置字段   反射值[ff5ea4d4-1834-45e6-b30d-beec2b376a42]的值:
  的[类package.VoteEntityID.routeId]设置器   package.VoteEntityID.routeId;嵌套异常为   org.hibernate.PropertyAccessException:无法设置字段值   [ff5ea4d4-1834-45e6-b30d-beec2b376a42]反射值:[类别   package.VoteEntityID.routeId]的设置程序。   有根本原因        java.lang.NullPointerException:在java.base / jdk.internal.reflect.UnsafeFieldAccessorImpl.ensureObj中为null(UnsafeFieldAccessorImpl.java:57)   〜[na:na] ... ...

我真的不敢动手:(我正在使用@Data Lombok批注,其中带有@Setter。 知道为什么将null传递给sureObj吗?

0 个答案:

没有答案