插入具有连接列的实体

Insert entity with join columns

我想在数据库中插入具有两个连接列的实体 "CategorieTresorerie"。问题是,其中一个 (RegroupementCategorieTresorerie) 正在尝试自动插入...但是这个已经在数据库中,所以我有一个重复的键值违规异常。

错误代码:

Hibernate: insert into "RegroupementCategorieTresorerie" ("RegroupementCategorieTresorerieCode") values (?)
2015-12-29 15:32:05.207  WARN 6960 --- [tomcat-http--26] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 23505
2015-12-29 15:32:05.208 ERROR 6960 --- [tomcat-http--26] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: duplicate key value violates unique constraint "RegroupementCategorieTresorerie_PK"
  Détail : Key ("RegroupementCategorieTresorerieCode")=(MARGE_BRUT) already exists.
2015-12-29 15:32:05.210  INFO 6960 --- [tomcat-http--26] o.h.e.j.b.internal.AbstractBatchImpl     : HHH000010: On release of batch it still contained JDBC statements
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [RegroupementCategorieTresorerie_PK]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

Class我要插入:

@Entity
public class CategorieTresorerie
    {
    @Id
    @Column(name="CategorieTresorerieID")
    @SequenceGenerator(name = "CategorieTresorerie_CategorieTresorerieID_seq", sequenceName = "\"CategorieTresorerie_CategorieTresorerieID_seq\"", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CategorieTresorerie_CategorieTresorerieID_seq")
    private Integer categorieTresorerieId;

    @MapsId
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "regroupementCategorieTresorerieCode", insertable = false, updatable = false)
    @Fetch(FetchMode.JOIN)
    private RegroupementCategorieTresorerie regroupement;

    @MapsId
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "typeCategorieTresorerieId", insertable = false, updatable = false)
    @Fetch(FetchMode.JOIN)
    private TypeCategorieTresorerie typeCategorieTresorerie;

    private Boolean estActif = true;

加入classRegroupementCategorieTresorerie,是hibernate尝试自动插入的:

@Entity
public class RegroupementCategorieTresorerie implements EstTraductible
{
    @Id
    private String regroupementCategorieTresorerieCode;

    @Transient
    private String libelle;

加入列 TypeCategorieTresorerie:

@Entity
public class TypeCategorieTresorerie
    {
    @Id
    @Column(name = "TypeCategorieTresorerieID")
    private Integer typeCategorieTresorerieId;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "CategorieTresorerieFamilleID", insertable = false, updatable = false)
    @Fetch(FetchMode.JOIN)
    private CategorieTresorerieFamille famille;

如何在不自动插入连接列的情况下插入 CategorieTresorerie?

感谢您的帮助。

不确定你在没有看到插入代码的情况下到底想做什么,但是如果你想加入一个已经存在的实体,请尝试获取它并指向获取的实体(带有 id),这样休眠就会不要尝试创建新记录。