简体   繁体   中英

Spring mvc : Saving a Java List in PostgreSQL with Hibernate

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. :-)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM