@LikeKey

Как решить javax.persistence.EntityExistsException в Hibernate?

Код ошибки:
javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [ru.likekey.main.entity.Photo#6]
        at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:123)
        at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
        at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
        at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1366)
        at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:453)
        at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3212)
        at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2380)
        at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447)
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183)
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40)
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281)
        at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101)
        at ru.likekey.main.dao.UserDAOImpl.updateUser(UserDAOImpl.java:46)
        at ru.likekey.main.service.UserServiceImpl.updateUser(UserServiceImpl.java:29)
        at ru.likekey.main.vk.callback.commands.BuyPhotoCommand.run(BuyPhotoCommand.java:114)
        at ru.likekey.main.vk.callback.commands.runnable_commands.BuyPhotoCommandThread.run(BuyPhotoCommandThread.java:19)
        at java.lang.Thread.run(Thread.java:748)

Метод, в котором вылетело исключение:
@Override
    public void updateUser(User user) {
        Session session = sessionFactory.getCurrentSession();
        try {
            session.beginTransaction();
            session.saveOrUpdate(user);
        } finally {
            session.getTransaction().commit();
        }
    }

UserEntity:
@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "vkId")
    private int vkId;

    @Column(name = "balance")
    private int balance;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "payments_id")
    private Payment userPayment;

    @ManyToMany(cascade = CascadeType.ALL)
    @LazyCollection(LazyCollectionOption.FALSE)
    @JoinTable(
            name = "user_photo",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "photo_id")
    )
    private List<Photo> photos;

    @ManyToMany(cascade = CascadeType.ALL)
    @LazyCollection(LazyCollectionOption.FALSE)
    @JoinTable(
            name = "user_video",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "video_id")
    )
    private List<Video> videos;

    public User() {
    }

    public User(int vkId, int balance) {
        this.vkId = vkId;
        this.balance = balance;
    }

    public void addPhotoToUser(Photo photo) {
        if (photos == null) photos = new ArrayList<>();
        photos.add(photo);
    }

    public void addVideoToUser(Video video) {
        if (videos == null) videos = new ArrayList<>();
        videos.add(video);
    }
//Сеттеры, геттеры

PhotoEntity:
@Entity
@Table(name = "photos")
public class Photo {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "path")
    private String path;

    @Column(name = "path_ready")
    private String pathReady;

    @Column(name = "price")
    private int price;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(
            name = "user_photo",
            joinColumns = @JoinColumn(name = "photo_id"),
            inverseJoinColumns = @JoinColumn(name = "user_id")
    )
    private List<User> users;

    public Photo() {
    }

    public Photo(String path, String pathReady, int price) {
        this.path = path;
        this.pathReady = pathReady;
        this.price = price;
    }

    public void addUserToPhoto(User user) {
        if (users == null) users = new ArrayList<>();
        users.add(user);
    }

Недавно начал работать с Hibernate и многие моменты не понятны, в частности из-за чего здесь вылетает ошибка
  • Вопрос задан
  • 41 просмотр
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы