hibernate之關於使用連線表實現多對一關聯對映

weixin_33831673發表於2015-06-04


【Hibernate】之關於使用連線表實現多對一關聯對映


在我們專案使用中採用中間表最多的一般就是多對一,或者是多對多,當然一對一使用中間表也是能夠的,可是這樣的機率通常少之又少!所以這裡重點介紹多對一和一對多的採用中間表進行關聯對映!


依舊採用Group和Person來描寫敘述這個邏輯!


Annotations配置

@Entity
@Table(name="t_group")
publicclass Group {
    private Integer id;
    private String name;
    @Id
    @GeneratedValue
    public Integer getId() {
       returnid;
    }
    publicvoid setId(Integer id) {
       this.id = id;
    }
    @Column(name="g_name")
    public String getName() {
       returnname;
    }
    publicvoid setName(String name) {
       this.name = name;
    }
}

@Entity
@Table(name="p_person")
publicclass Person {
    private Integer id;
    private String name;
    private Integer age;
    private Group group;
    @ManyToOne
    //以下是配置中間表的核心
    @JoinTable(name="g_p",joinColumns={@JoinColumn(name="p_id")},
           inverseJoinColumns={@JoinColumn(name="g_id")})
    public Group getGroup() {
       returngroup;
    }
    publicvoid setGroup(Group group) {
       this.group = group;
    }
    @Id
    @GeneratedValue
    public Integer getId() {
       returnid;
    }
    publicvoid setId(Integer id) {
       this.id = id;
    }
    @Column(name="p_name")
    public String getName() {
       returnname;
    }
    publicvoid setName(String name) {
       this.name = name;
    }
    @Column(name="p_age")
    public Integer getAge() {
       returnage;
    }
    publicvoid setAge(Integer age) {
       this.age = age;
    }
}


XML配置


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/HibernateMapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="csg.hibernate.entity">
    <class name="Person" table="t_person">
       <id name="id">
           <column name="id"/>
           <generator class="native" />
       </id>
       <property name="name" />
       <property name="age" />
       <join table="t_p" optional="true">
           <key column="p_id"></key>
           <many-to-one name="group" column="g_id" class="Group" unique="true"/>
       </join>
    </class>
</hibernate-mapping>

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/HibernateMapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="csg.hibernate.entity">
    <class name="Group" table="t_group">
       <id name="id">
           <column name="id"/>
           <generator class="native" />
       </id>
       <property name="name" />
    </class>
</hibernate-mapping>


寫這篇文章,我特意查詢了一下網上的文章,發現大家都是採用XML配置的,所以我這裡也寫了Annotations配置,由於JPA中的Annotations使用起來遠比XML要方便!OK?







XML配置


相關文章