使用注解的Hibernate many-to-many映射

many to many映射是在两个实体间,一个实体可以和其他的多个实体建立关系。例如一个捐赠服务的实体Subscription实体和读取实体都是两个实体,一个捐赠可以有多个读者,一个读者可以有多个捐赠,在这篇文中我们将会学习在Hibernate3中怎么建立这种关系。

提出解决方案

为了演示多对多的关系,我们连接两个实体Reader实体和Subscription实体。他们的实体关系如下:


拥有者实体

拥有者实体负责建立和维护关系,在我们的例子中,我让Reader实体成为拥有者,@JoinTable注解使用来建立这种关系
package hibernate.test.manyToMany.joinTable;
 
import java.io.Serializable;
import java.util.Set;
 
import javax.persistence.CascadeType;
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.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
 
@Entity(name = "ReaderEntity")
@Table(name = "READER", uniqueConstraints = {
        @UniqueConstraint(columnNames = "ID"),
        @UniqueConstraint(columnNames = "EMAIL") })
public class ReaderEntity implements Serializable {
 
    private static final long serialVersionUID = -1798070786993154676L;
 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", unique = true, nullable = false)
    private Integer readerId;
 
    @Column(name = "EMAIL", unique = true, nullable = false, length = 100)
    private String email;
 
    @Column(name = "FIRST_NAME", unique = false, nullable = false, length = 100)
    private String firstName;
 
    @Column(name = "LAST_NAME", unique = false, nullable = false, length = 100)
    private String lastName;
 
    @ManyToMany(cascade=CascadeType.ALL)
    @JoinTable(name="READER_SUBSCRIPTIONS", joinColumns={@JoinColumn(referencedColumnName="ID")}
                                        , inverseJoinColumns={@JoinColumn(referencedColumnName="ID")}) 
    private Set<SubscriptionEntity> subscriptions;
 
    public Integer getReaderId() {
        return readerId;
    }
 
    public void setReaderId(Integer readerId) {
        this.readerId = readerId;
    }
 
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
 
    public String getFirstName() {
        return firstName;
    }
 
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
 
    public String getLastName() {
        return lastName;
    }
 
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
 
    public Set<SubscriptionEntity> getSubscriptions() {
        return subscriptions;
    }
 
    public void setSubscriptions(Set<SubscriptionEntity> subscriptions) {
        this.subscriptions = subscriptions;
    }
}

关系实体

我们的映射实体是Subscription实体,使用mappedBy建立和Reader实体的关系
package hibernate.test.manyToMany.joinTable;
 
import java.io.Serializable;
import java.util.Set;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
 
@Entity(name = "SubscriptionEntity")
@Table(name = "SUBSCRIPTION", uniqueConstraints = {
        @UniqueConstraint(columnNames = "ID")})
public class SubscriptionEntity implements Serializable
{
 
    private static final long serialVersionUID = -6790693372846798580L;
 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", unique = true, nullable = false)
    private Integer subscriptionId;
 
    @Column(name = "SUBS_NAME", unique = true, nullable = false, length = 100)
    private String subscriptionName;
     
    @ManyToMany(mappedBy="subscriptions")
    private Set<ReaderEntity> readers;
 
    public Integer getSubscriptionId() {
        return subscriptionId;
    }
 
    public void setSubscriptionId(Integer subscriptionId) {
        this.subscriptionId = subscriptionId;
    }
 
    public String getSubscriptionName() {
        return subscriptionName;
    }
 
    public void setSubscriptionName(String subscriptionName) {
        this.subscriptionName = subscriptionName;
    }
 
    public Set<ReaderEntity> getReaders() {
        return readers;
    }
 
    public void setReaders(Set<ReaderEntity> readers) {
        this.readers = readers;
    }
}

在配置文件中配置实体

我们已经有了两个可用的实体,我们必须在配置文件中配置他们
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatetest</property>
        <property name="hibernate.connection.password">XXXXXX</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create</property>
        <mapping class="hibernate.test.manyToMany.joinTable.ReaderEntity"/>
        <mapping class="hibernate.test.manyToMany.joinTable.SubscriptionEntity"/>
    </session-factory>
</hibernate-configuration>

测试代码

package hibernate.test.manyToMany;
 
import hibernate.test.HibernateUtil;
import hibernate.test.manyToMany.joinTable.*;
 
import java.util.HashSet;
import java.util.Set;
 
import org.hibernate.Session;
 
public class TestJoinTable
{
     
    public static void main(String[] args)
    {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        
        //Add subscription
        SubscriptionEntity subOne = new SubscriptionEntity();
        subOne.setSubscriptionName("Entertainment");
         
        SubscriptionEntity subTwo = new SubscriptionEntity();
        subTwo.setSubscriptionName("Horror");
         
        Set<SubscriptionEntity> subs = new HashSet<SubscriptionEntity>();
        subs.add(subOne);
        subs.add(subTwo);
         
        //Add readers
        ReaderEntity readerOne = new ReaderEntity();
        readerOne.setEmail("[email protected]");
        readerOne.setFirstName("demo");
        readerOne.setLastName("user");
         
        ReaderEntity readerTwo = new ReaderEntity();
        readerTwo.setEmail("[email protected]");
        readerTwo.setFirstName("demo");
        readerTwo.setLastName("user");
         
        Set<ReaderEntity> readers = new HashSet<ReaderEntity>();
        readers.add(readerOne);
        readers.add(readerTwo);
         
        readerOne.setSubscriptions(subs);
        readerTwo.setSubscriptions(subs);
 
        session.save(readerOne);
        session.save(readerTwo);
         
        session.getTransaction().commit();
        HibernateUtil.shutdown();
    }
}
 
Output:
 
Hibernate: insert into READER (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
Hibernate: insert into SUBSCRIPTION (SUBS_NAME) values (?)
Hibernate: insert into SUBSCRIPTION (SUBS_NAME) values (?)
Hibernate: insert into READER (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
Hibernate: insert into READER_SUBSCRIPTIONS (readers_ID, subscriptions_ID) values (?, ?)
Hibernate: insert into READER_SUBSCRIPTIONS (readers_ID, subscriptions_ID) values (?, ?)
Hibernate: insert into READER_SUBSCRIPTIONS (readers_ID, subscriptions_ID) values (?, ?)
Hibernate: insert into READER_SUBSCRIPTIONS (readers_ID, subscriptions_ID) values (?, ?)

可以在原文中下载源码,原文地址:http://howtodoinjava.com/2012/11/17/hibernate-many-to-many-mapping-using-annotations/

你可能感兴趣的:(Hibernate,many-to-many)