membersound
membersound

Reputation: 86747

How to store string lists in database without a join table?

I want to store a List<String> in a postgres DB.

@ElementCollection
private List<String> products;

Hibernate will therefore create a join table. Is it possible to prevent this?

One workaround would be to create an explicit class with bidirectional mapping as follows:

@Entity
public class MainEntity {

    @OneToMany(mappedBy = "main")
    private List<Product> products;
}

@Entity
public class Product {
    @Id
    private long id;

    @ManyToOne
    private MainEntity main;

    private String text;
}

But I feel this is a bit over the top for just storing a string list, isn't it?

Upvotes: 0

Views: 167

Answers (2)

R.mto
R.mto

Reputation: 11

i'm not sure but could you remove :

@ManyToOne
private MainEntity main;

in class product.

I think it might works properly without this. Do you want to handle your list from MainEntity or from Product?

Upvotes: 0

cichystefan
cichystefan

Reputation: 328

If you don't find anything better, try this:

  1. Mark your List with @Transient so that it is never persisted directly.
  2. Prepare additional field for persisting your list, of a type that is "persistable" directly by JPA (concatenated, delimetered String seems to be quite natural).
  3. Use methods annotated with @PostLoad and @PrePersist to move data between those two fields, converting from List to String and back.

Upvotes: 1

Related Questions