在上一个部分中,我们已经使用XML文件进行了多对多映射。这里,我们将使用注解来执行这个任务。

我们可以使用list、set、bag、map等来映射多对多关系。这里,我们将使用list进行多对多映射。在这种情况下,将创建三个表。

多对多映射示例

在这个示例中,我们将通过list在问题和答案之间生成多对多关系。

1) 创建持久化类

Question.java

package cn.javatiku;

import java.util.List;
import javax.persistence.*;

@Entity
@Table(name="ques1123")
public class Question {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String qname;

    @ManyToMany(targetEntity = Answer.class, cascade = { CascadeType.ALL })
    @JoinTable(name = "q_ans1123",  
        joinColumns = { @JoinColumn(name = "q_id") },  
        inverseJoinColumns = { @JoinColumn(name = "ans_id") })
    private List<Answer> answers;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getQname() {
        return qname;
    }

    public void setQname(String qname) {
        this.qname = qname;
    }

    public List<Answer> getAnswers() {
        return answers;
    }

    public void setAnswers(List<Answer> answers) {
        this.answers = answers;
    }
}

Answer.java

package cn.javatiku;

import javax.persistence.*;

@Entity
@Table(name="ans1123")
public class Answer {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String answername;
    private String postedBy;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getAnswername() {
        return answername;
    }

    public void setAnswername(String answername) {
        this.answername = answername;
    }

    public String getPostedBy() {
        return postedBy;
    }

    public void setPostedBy(String postedBy) {
        this.postedBy = postedBy;
    }
}

2) 在pom.xml文件中添加项目信息和配置

打开pom.xml文件并点击source。现在,在<dependencies>....</dependencies>标签之间添加以下依赖项。

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.3.1.Final</version>
</dependency>

<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc14</artifactId>
    <version>10.2.0.4.0</version>
</dependency>

3) 创建配置文件

此文件包含有关数据库和映射文件的信息。

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC 
    "-//Hibernate/Hibernate Configuration DTD 5.3//EN" 
    "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hbm2ddl.auto">create</property>
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
        <property name="connection.username">system</property>
        <property name="connection.password">jtp</property>
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <mapping class="cn.javatiku.Question"/>
        <mapping class="cn.javatiku.Answer"/>
    </session-factory>
</hibernate-configuration>

4) 创建存储数据的类

StoreData.java

package cn.javatiku;

import java.util.ArrayList;
import org.hibernate.*;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class StoreData {
    public static void main(String[] args) {
        StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
        Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
        SessionFactory factory = meta.getSessionFactoryBuilder().build();
        Session session = factory.openSession();
        Transaction t = session.beginTransaction();

        Answer an1 = new Answer();
        an1.setAnswername("Java is a programming language");
        an1.setPostedBy("Ravi Malik");

        Answer an2 = new Answer();
        an2.setAnswername("Java is a platform");
        an2.setPostedBy("Sudhir Kumar");

        Question q1 = new Question();
        q1.setQname("What is Java?");
        ArrayList<Answer> l1 = new ArrayList<Answer>();
        l1.add(an1);
        l1.add(an2);
        q1.setAnswers(l1);

        Answer ans3 = new Answer();
        ans3.setAnswername("Servlet is an Interface");
        ans3.setPostedBy("Jai Kumar");

        Answer ans4 = new Answer();
        ans4.setAnswername("Servlet is an API");
        ans4.setPostedBy("Arun");

        Question q2 = new Question();
        q2.setQname("What is Servlet?");
        ArrayList<Answer> l2 = new ArrayList<Answer>();
        l2.add(ans3);
        l2.add(ans4);
        q2.setAnswers(l2);

        session.persist(q1);
        session.persist(q2);

        t.commit();
        session.close();
        System.out.println("success");
    }
}

输出

9-1.png
9-2.png

标签: Hibernate, Hibernate教程, Hibernate框架, Hibernate框架设计, Hibernate初级教程, Hibernate框架用法, Hibernate指南, Hibernate入门, Hibernate中级教程, Hibernate进阶教程, Hibernate高级教程, Hibernate下载