Reputation: 1180
I'm trying to store an JSON Array in MySQL with Spring and Hibernate.
The application gets the likes from the users and stores the id of a user in a JSON Array, for example
[1,2,3,4,5,6]
in a column name likes
with type text
(MySQL)
¿How can I put a new id in the array? I mean, get the JSON form database and insert the id and count the number of elements.
Upvotes: 1
Views: 994
Reputation: 6566
I'd use transient
variables as a solution for this problem. I don't think there is a better solution for this. You may also try hibernate interceptors
for this as a solution.
@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();
}
}
within your service layer do the following
@Transactional(lockmode = LockMode.READ){
LikesEntity le = sess.get(LikesEntity.class,234);
le.addUserId("userPk");
session.saveOrUpdate(le);
}
Upvotes: 2