0

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?

2
  • Your workaround is rather the right way to go, A Product is certainly an object with more properties than just the text which you may want to persist at some point. So it sould be implemented it as an entity. Please keep your code clean and do not go with hacks like comma separated + event hadler callbacks, it will most likely save you some migration headaches. You don't have to make it bidirectional tough. Commented Aug 4, 2015 at 8:13
  • I just used the product as an example. By realworld entity should and will only contain a simple list of textstrings, and won't be betting additional fields! Commented Aug 4, 2015 at 8:15

2 Answers 2

1

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.
Sign up to request clarification or add additional context in comments.

Comments

0

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?

1 Comment

The mapping above only states a workaround for the problem that a List<String> will trigger the creation of a join table. The question is not that is does not "work".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.