休眠加入表

时间:2016-05-12 07:56:07

标签: java mysql hibernate jpa

我有一个MySQL数据库,它从Java实体更新。 我需要一个包含3列的两个表之间的连接表。

Bar ("bar_id")

中的1列

Owner ("owner_id", "bought")

中的2列

请你告诉我这是否可能或我是如何意识到的。

我想要一个看起来像这样的联接表:

'bar_id' | 'owner_id' | 'bought'
--------------------------------

BaseEntity.java

@MappedSuperclass
public class BaseEntity {
    private int id;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getId(){ return this.id; }
    public void setId(int id){ this.id = id; }
}

Bar.java

@Entity
@Table(name="bar")
public class Bar extends BaseEntity{

    private String name;
    private String bought;
    private List<Fan> fan;
    private List<Owner> owner;

    @Column(name="name")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @Column(name="bought")
    public String getBought() {
        return bought;
    }
    public void setBought(String bought) {
        this.bought = bought;
    }

    @ManyToMany(mappedBy="bar", targetEntity=Owner.class)
    public List<Owner> getOwner() {
        return owner;
    }
    public void setOwner(List<Owner> owner) {
        this.owner = owner;
    }

    @ManyToMany
    @JoinColumn(name="fan")
    public List<Fan> getFan() {
        return fan;
    }
    public void setFan(List<Fan> fan) {
        this.fan = fan;
    }
}

Owner.java

@Entity
@Table(name="owner")
public class Owner extends BaseEntity{

    private String firstname;
    private String lastname;
    private String birthday;
    private java.sql.Date bought;
    private List<Bar> bar;

    @Column(name="firstname")
    public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    @Column(name="lastname")
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    @Column(name="birthday")
    public String getBirthday() {
        return birthday;
    }
    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    @Column(name="bought")
    public java.sql.Date getBought() {
        return bought;
    }
    public void setBought(java.sql.Date bought) {
        this.bought = bought;
    }

    @ManyToMany
    @JoinColumn(name="bar")
    public List<Bar> getBar() {
        return bar;
    }
    public void setBar(List<Bar> bar) {
        this.bar = bar;
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用@JoinTable注释创建连接表。

请查看这篇文章,了解如何实现它。

How to create join table with JPA annotations?