【问题标题】:manipulate JSON array in Spring Hibernate在 Spring Hibernate 中操作 JSON 数组
【发布时间】:2014-12-30 16:07:52
【问题描述】:
我正在尝试使用 Spring 和 Hibernate 在 MySQL 中存储 JSON 数组。
应用程序从用户那里获取点赞,并将用户的 id 存储在 JSON Array 中,例如
[1,2,3,4,5,6]
在列名likes和类型text (MySQL)中
¿如何在数组中添加新的 id?我的意思是,获取 JSON 表单数据库并插入 id 并计算元素的数量。
【问题讨论】:
标签:
java
mysql
json
spring
hibernate
【解决方案1】:
我会使用transient 变量来解决这个问题。我认为没有更好的解决方案。您也可以尝试休眠 interceptors 作为解决方案。
@Table
@Entity(name='Likes')
public class LikesEntity implements Serializable {
@Transient
private List<String> userIds;
@Column
private String likes;
@Column
private String count;
//getter and setters for the like and count
...
public void addUserId(String id){
this.userIds.add(userIds);
this.likes = convertToJsonArray(userIds); // use GSON or Jackson or any other library that can help you convert array to JSON string
this.count = this.userIds.size();
}
}
在您的服务层中执行以下操作
@Transactional(lockmode = LockMode.READ){
LikesEntity le = sess.get(LikesEntity.class,234);
le.addUserId("userPk");
session.saveOrUpdate(le);
}