2021年3月23日星期二

JPA and Hibernate: Entity with composite primary key using multiple @Id

I'm using SpringBoot with JPA and Hibernate.

For a specific entity I need to use a primary key composed by a relationship + a field.

Something like this:

@Entity  @Table(      name = "book",      uniqueConstraints=@UniqueConstraint(columnNames={"book_id",       "field_a"}))  public class Book extends MyBaseEntity {        @Id      @Column(name = "id")      @Type(type = "uuid-char")      private UUID uuid = UUID.randomUUID();        @Column(name = "name", nullable = false)      private String name;        @OneToMany(mappedBy = "book")      private List<Author> authors = new ArrayList<>();    }    @Entity  @Table(name = "author")  @IdClass(CustomID.class)  public class Author extends MyBaseEntity {            /* Here the composite key */      @Id      @ManyToOne()      @JoinColumn(name = "book_id")      private Book book;        @Id      @Column(name = "field_a", nullable = false)      @Type(type = "uuid-char")      private UUID fieldA;        @CreationTimestamp      @Column(name = "creation_date")      private Instant creationDate;        @UpdateTimestamp      @Column(name = "last_mod_date")      private Instant lastModificationDate;    }    public class CustomID implements Serializable {      private UUID book;      private UUID fieldA;  }  

Using this approach, after some inserts on the DB, for Author entity book_id column contains values like these:

ÃFË5ÊL©T¾Äd Why? Why there aren't Book primary keys values?

https://stackoverflow.com/questions/66772415/jpa-and-hibernate-entity-with-composite-primary-key-using-multiple-id March 24, 2021 at 06:53AM

没有评论:

发表评论