首页 > 解决方案 > Hibernate collection with @ElementCollection contains duplicated elements in database

问题描述

Have a class.

@Entity
@Table(name="sessions")
@Component
public class Session {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ElementCollection
    private Set<String> addedWords;
}

My flow is: get session one time. Add one word to addedWords and save session, repeat it. The problem that when I check my database, there are a lot of duplications, at the same time I don't have any duplications in Java class. So the Set<String> addedWords in class and this words in database not the same. Why I have this strange behavior and how to make things work well without any duplication? I use PostgreSQL. Saving method:

public synchronized void addWord(Session session, String word) {
        session.getAddedWords().add(word);
        sessionRepository.save(session);
}

Here spring config

spring:
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: update

标签: springpostgresqlhibernatejpaspring-data-jpa

解决方案


推荐阅读