Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@ElementCollection or @OnetoMany with Entity or primitives?

I have a site with multiple pages, and each page has a table that contains some data. The tables have many columns, and users can select which columns to display or hide. I am trying to persist these selections.

The question I have is choosing the best way to persist these objects.

I see many possible ways, none of which Ive had success in implementing. But before I commit to one of them, I would like to know if I am doing it horribly wrong, or am way off the mark with how this should be implemented.

I have a user class that is persisted already.

Option #1 In my user entity, add a field of Map> where the key is the page name, and the list is the columns the user has selected on that page. Using @ElementCollection.

Option #2 User entity has a @onetomany List. Which requires a UserColumns entity, with pagename as primary key, and @oneToMany relationship with another entity for each column.

Option 1:

@Entity
public class User{

private Map<String, List<String>> columns;

@ElementCollection
public void setColumns(Map<String, List<String>> colunms){

}


}

Option 2:

@Entity
public class User{

private List<UserColumns> columns;

@ElementCollection or @OneToMany
public void setColumns(List<UserColumns> colunms){

}


}

I realize this will be difficult to answer without looking at the actual code, and I've probably not described the situation adequately or precisely, but welcome all input anyways. Thank you.

like image 656
evenprime Avatar asked Dec 28 '25 22:12

evenprime


1 Answers

I personally always prefer to use a one to many relationship to other entities when doing something like this. My reason is that it is a much more flexible design going forward. It is pretty easy to see a scenario where instead of just knowing the column name you will want additional information. By using a real entity instead of a string you simply add a new property to your class. If you are using just a string though you will have a much more extensive refactoring on your hands. Takes a little longer in the beginning but it almost always pays off in the end.

like image 77
jjathman Avatar answered Dec 30 '25 14:12

jjathman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!