0

I need to map a list of Enums to a table in postgres.

For the generic mapping of a 1:1 relation I found this post very helpful. The code looks like:

@Entity(name = "Post")
@Table(name = "post")
@TypeDef(
    name = "pgsql_enum",
    typeClass = PostgreSQLEnumType.class
)
public static class Post {

    @Id
    private Long id;

    private String title;

    @Enumerated(EnumType.STRING)
    @Column(columnDefinition = "post_status_info")
    @Type( type = "pgsql_enum" )
    private PostStatus status;

    //Getters and setters omitted for brevity
}

But I have no troubles to figure out a solution if PostStatus is a List<PostStatus>. Because than the definition fails.

To make it specific: I have a table, e.g. PostRelations where I can store post_id and status. For the sake of sample I can store multiple status (e.g. timebased). So how to define it properly if I have

@Entity(name = "Post")
@Table(name = "post")
public static class Post {

    @Id
    private Long id;
    private String title;
    private List<PostStatus> status;

}

The approach to define it the same way cause an exception (which seems clear because the annotation is for a enum and not for a List)

Caused by: java.lang.ClassCastException: interface java.util.List
    at java.lang.Class.asSubclass(Class.java:3404) ~[na:1.8.0_212]
    at org.hibernate.type.EnumType.setParameterValues(EnumType.java:86) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
LeO
  • 4,238
  • 4
  • 48
  • 88

1 Answers1

0

After some research and digging into the issue I finally solved the problem thanks to the sample for proper linking and setup:

@ElementCollection
@CollectionTable(name = "post_permission", joinColumns = @JoinColumn(name = "post_id"))
private List<PostStatus4Save> status;

and a thin wrapper around the existing enum PostStatus

@Embeddable
@Data //lombok
@TypeDef(name = "pgsql_enum", typeClass = PostgreSQLEnumType.class)
@AllArgsConstructor //lombok
@NoArgsConstructor  //lombok
public class PostStatus4Save {

    @Enumerated(EnumType.STRING)
    @Type(type = "pgsql_enum")
    PostStatus postPermission;
}
LeO
  • 4,238
  • 4
  • 48
  • 88