Reputation: 5313
I am working on a Spring-MVC project where I am using Hibernate for persistence. In one of the model classes I have a List which I want to persist. I am facing the problem as I don't know which dataType to use in PostgreSQL and do I need instruct hibernate in some way or other that I am trying to persist a List. Performance requirements are not that much of a problem on this list, as it does not get that much action. I am posting some code for reference, kindly let me know. Thanks a lot :
GroupAccount model class :
@Entity
@Table(name="groupaccount")
public class GroupAccount {
@Column(name = "blacklist")
private List<String> blacklist;
public List<String> getBlacklist() {
return blacklist;
}
public void setBlacklist(List<String> blacklist) {
this.blacklist = blacklist;
}
}
I would sometimes require to update the values of the blacklist, so I have a method in DAO which updates the groupAccount, I am pasting it below.
GroupAccountDAOImpl edit function :
@Override
public void editGroupAccount(GroupAccount groupAccount) {
session = this.sessionFactory.getCurrentSession();
GroupAccount groupAccount1 = (GroupAccount)session.get(GroupAccount.class,groupAccount.getGroupId());
if(!(groupAccount1==null)){
groupAccount.setOwnedcanvas(groupAccount1.getOwnedcanvas());
groupAccount.setGroupMembersSet(groupAccount1.getGroupMembersSet());
session.merge(groupAccount);
session.flush();
}
}
One use-case for adding users in blacklist :
List<String> blackListUsers;
blackListUsers = groupAccount.getBlacklist();
blackListUsers.add(memberForBlackListing.getMemberUsername());
groupAccount.setBlacklist(blackListUsers);
this.groupAccountService.editGroupAccount(groupAccount);
removeAllMemberships(memberId);
return true;
Any help would be nice. Thanks a lot. :-)
Upvotes: 1
Views: 3700
Reputation: 24423
You can't map List<String>
to a single column. For these cases, @ElementCollection
is used
@ElementCollection
@CollectionTable(name="blacklist", joinColumns=@JoinColumn(name="group_account_id")
@Column(name = "name")
private List<String> blacklist;
This requires a database table named blacklist
with columns name
and group_account_id
(which will be used as a foreign key to group_account
table). Of course, table and column names are customizable.
Upvotes: 3