【问题标题】:JPA ManyToOne with repository saving problem具有存储库保存问题的 JPA ManyToOne
【发布时间】:2022-01-15 04:09:51
【问题描述】:

在我的UserService 中,我为新用户调用save 方法,createdBy 将被设置并保存。当 save get 调用时发生以下错误:

org.springframework.dao.DataIntegrityViolationException: A different object with the same identifier value was already associated with the session : [at.qe.skeleton.model.User#1];

看起来它试图保存设置为createdByUser 对象(已存在于数据库中)。我在 ManyToOne 注释中尝试了各种 CascadeTypes,但它不起作用。也许我有其他一些注释错误,但我不知道是什么。

我有以下课程:

DBEntity.java

@MappedSuperclass
public class DBEntity implements Persistable<Long>, Serializable, Comparable<DBEntity> {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "default_generator"
    )
    private Long id;

    @ManyToOne()
    @JoinColumn(
            name = "created_by",
            referencedColumnName = "id",
            insertable = false,
            updatable = false,
            foreignKey = @ForeignKey(
                    name = "created_by_user_id_fk"
            )
    )
    private User createdBy;

    @Column(
            name = "created_on",
            nullable = false,
            columnDefinition = "TIMESTAMP WITHOUT TIME ZONE"
    )
    private Date createdOn;
    //shortened 
}

用户.java

@Entity(name = "User")
@Table(
        name = "\"user\"",
        uniqueConstraints = {
                @UniqueConstraint(name = "user_username_unique", columnNames = "username")
        }
)
@SequenceGenerator(
        name = "default_generator",
        sequenceName = "user_role_sequence",
        allocationSize = 1
)
public class User extends DBEntity {

    @Column(
            name = "username",
            nullable = false,
            columnDefinition = "TEXT"
    )
    private String username;
    //shortened 
}

用户服务.java

public class UserService {

    @Autowired
    private UserRepository userRepository;
    public User saveUser(User user) {
        if (user.isNew()) {
            user.setCreatedOn(new Date());
            user.setCreatedBy(getAuthenticatedUser());
        } else {
            user.setUpdatedOn(new Date());
            user.setUpdatedBy(getAuthenticatedUser());
        }

        return userRepository.save(user);
    }

    private User getAuthenticatedUser() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return userRepository.findFirstByUsername(auth.getName());
    }
}

UserRepository.java

public interface UserRepository extends AbstractRepository<User, Long> {}

【问题讨论】:

    标签: java spring-boot spring-data-jpa


    【解决方案1】:

    发现问题。 序列生成器与测试数据冲突,因此它试图为新用户提供一个已经在数据库中的 id

    【讨论】:

      猜你喜欢
      • 2018-07-22
      • 1970-01-01
      • 1970-01-01
      • 2011-10-14
      • 1970-01-01
      • 2016-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多