1

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 likeswith 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.

1 Answer 1

2

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);
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.