JUnit with H2 database: unique index or primary key violation when adding multilingual services for multiple data

When creating a database using Hibernate, it adds a unique key constraint to the external table id_studentin the table oe_iv_student_lang, because we need to implement an interface Serializable, which leads to the fact that Hibernate does not allow adding multiple rows with the same parent foreign key in the corresponding child table .

I have attached a snippet for a better understanding.

Student class:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "oe_iv_student")
public class OeIvStudent {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_student")
    private Integer idStudent;
}

Student language class:

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "oe_iv_student_lang")
public class OeIvStudentLang implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_student_lang")
    private Integer idStudentLang;

    @OneToOne
    @JoinColumn(name = "id_student")
    private OeIvStudent idStudent;

    @Column(name = "ln_code")
    private String lnCode;
}

Location Class:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "oe_locations")
public class OeLocations {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_location")
    private Integer idLocation;

    @OneToOne
    @JoinColumn(name = "id_student", referencedColumnName = "id_student")
    private OeIvStudentLang idStudent;

    @Column(name = "code")
    private String code;
}

, Serializable, , OeIvStudentLang OeLocations, , , OeIvStudent. OeIvStudentLang , ..

OeLocationsOeIvStudentLangOeIvStudent

Serializable OeIvStudentLang, Hibernate Exception, , OeIvStudentLang Serializable, OeLocations. Object OeIvStudent, lang OeLocations.

, , .

:)

+6
3

Serializable.

OeIvStudentLang OeIvStudent @OneToOne. , OeIvStudentLang OeIvStudent. , "--", @OneToOne @OneToMany .

:

" " "--" , .

+3

you need to map it as @OneToMany relation and change the column id_studentas the given object

0
source

All Articles