Sergey Chepurnov
Sergey Chepurnov

Reputation: 1447

one-to-many with Collection<Integer>

I have a table "seance" in DB ('id' is a PK):

CREATE TABLE seance(
    id int NOT NULL AUTO_INCREMENT,
    seance_id int,
    number int,
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

seance

id, seance_id, number
1, 111222, 1951
2, 111222, 1951
3, 111222, 1951
4, 333222, 1415
5, 333222, 1415
6, 333222, 1415

Entity class:

@Entity
@Table(name = "seance")
public class Seance {

    public Seance() {}

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column(name = "seance_id")
    private Integer seanceId;

    @Column(name = "number")
    @ElementCollection// it is wrong cause require TWO tables
    //what I should write here or modify?
    private Set<Integer> number = new HashSet<Integer>();

    public Seance(Integer seanceId, Set<Integer> number) {
        this.seanceId = seanceId;
        this.number = number;
    }

    // getters and setters

}

As a result I want to have an instance of Seance class:

Integer seanceId: 111222;

Set number: 1951, 1951, 1951;

Upvotes: 2

Views: 1731

Answers (2)

Vivien SA&#39;A
Vivien SA&#39;A

Reputation: 767

You need to have your entity like this :

@Entity
@Table(name = "seance")
public class Seance {

    public Seance() {
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column(name = "seance_id")
    private Integer seanceId;

@ElementCollection
  @CollectionTable(
        name="NUMBER",
        joinColumns=@JoinColumn(name="OWNER_ID")
  )
    private Set<Integer> number = new HashSet<Integer>();

    public Sessions(Integer seanceId, Set<Integer> number) {
        this.seanceId = seanceId;
        this.number = number;
    }

    public Integer getSeanceId() {
        return seanceId;
    }

    public void setSeanceId(Integer seanceId) {
        this.seanceId = seanceId;
    }

    public Set<Integer> getNumber() {
        return number;`enter code here`
    }

    public void setNumber(Set<Integer> number) {
        this.number = number;
    }

}

doing like this, you will have two tables and number is going to have a table, without being and entity. Moreover, your conception is event bad because you have redundance that is something to avoid when deeling with DataBases. you can also follow this link https://en.wikibooks.org/wiki/Java_Persistence/ElementCollection

Upvotes: 2

Liping Huang
Liping Huang

Reputation: 4476

Yes, It is meant to handle several non-standard relationship mappings, the ElementCollection can be used to define a one-to-many relationship and the ElementCollection values are always stored in a separate table.

Upvotes: 1

Related Questions