`

Hibernate映射关系

阅读更多
1. Hibernate映射关系

新建项目Hibernate08


hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!--数据库连接设置 -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate4</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <!-- 方言 -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <!-- 控制台显示SQL -->
        <property name="show_sql">true</property>
        <!-- 自动更新表结构 -->
        <property name="hbm2ddl.auto">update</property>
        <!-- Mapper -->
        <mapping resource="com/andrew/model/User.hbm.xml"/>
        <mapping resource="com/andrew/model/Address.hbm.xml"/>
        <mapping resource="com/andrew/model/User2.hbm.xml"/>
        <mapping resource="com/andrew/model/Address2.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

HibernateUtil.java

package com.andrew.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();
    private static SessionFactory buildSessionFactory() {
        // 1. 实例化配置文件
        Configuration configuration = new Configuration().configure();
        // 2. 实例化服务登记
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();
        // 3. 获取Session工厂
        return configuration.buildSessionFactory(serviceRegistry);
    }
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}


1) Hibernate一对一映射关系实现

1.1) 按照主键映射

User.java

package com.andrew.model;
public class User {
    private int id;
    private String name;
    private Address address;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
}

User.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.andrew.model">
    <class name="User" table="t_user">
        <id name="id" column="userId">
            <generator class="native"></generator>
        </id>
        <property name="name" column="userName"></property>
        <one-to-one name="address" class="com.andrew.model.Address" cascade="all"></one-to-one>
    </class>
</hibernate-mapping>

Address.java

package com.andrew.model;
public class Address {
    private int id;
    private String address;
    private String zipcode;
    private User user;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getZipcode() {
        return zipcode;
    }
    public void setZipcode(String zipcode) {
        this.zipcode = zipcode;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
}

Address.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.andrew.model">
    <class name="Address" table="t_address">
        <id name="id" column="addressId">
            <generator class="foreign">
                <param name="property">user</param>
            </generator>
        </id>
        <property name="address" column="address"></property>
        <property name="zipcode" column="zipcode"></property>
        <one-to-one name="user" class="com.andrew.model.User" constrained="true"></one-to-one>
    </class>
</hibernate-mapping>

UserTest.java

package com.andrew.service;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.andrew.model.Address;
import com.andrew.model.Address2;
import com.andrew.model.User;
import com.andrew.model.User2;
import com.andrew.util.HibernateUtil;
public class UserTest {
    private SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
    private Session session;
    @Before
    public void setUp() throws Exception {
        session=sessionFactory.openSession(); // 1. 生成一个session
        session.beginTransaction(); // 2. 开启事务
    }
    @After
    public void tearDown() throws Exception {
         session.getTransaction().commit(); // 3. 提交事务
         session.close(); // 4. 关闭session
    }
    @Test
    public void testSave1() {
        User user = new User();
        user.setName("张三");
        Address address = new Address();
        address.setAddress("某地方");
        address.setZipcode("43242");
        address.setUser(user);
        user.setAddress(address);
        session.save(user);
    }
}

运行结果:
Hibernate: insert into t_user (userName) values (?)
Hibernate: insert into t_address (address, zipcode, addressId) values (?, ?, ?)
数据库
t_address
addressId    address    zipcode
1            某个地方   43242
t_user
userId    userName
1         张三


1.2) 按照外键映射

User2.java

package com.andrew.model;
public class User2 {
    private int id;
    private String name;
    private Address2 address;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Address2 getAddress() {
        return address;
    }
    public void setAddress(Address2 address) {
        this.address = address;
    }
}

User2.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.andrew.model">
    <class name="User2" table="t_user2">
        <id name="id" column="userId">
            <generator class="native"></generator>
        </id>
        <property name="name" column="userName"></property>
        <many-to-one name="address" class="com.andrew.model.Address2" column="addressId" cascade="all" unique="true"></many-to-one>
    </class>
</hibernate-mapping>

Address2.java

package com.andrew.model;
public class Address2 {
    private int id;
    private String address;
    private String zipcode;
    private User2 user;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getZipcode() {
        return zipcode;
    }
    public void setZipcode(String zipcode) {
        this.zipcode = zipcode;
    }
    public User2 getUser() {
        return user;
    }
    public void setUser(User2 user) {
        this.user = user;
    }
}

Address2.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.andrew.model">
    <class name="Address2" table="t_address2">
        <id name="id" column="addressId">
            <generator class="native">
            </generator>
        </id>
        <property name="address" column="address"></property>
        <property name="zipcode" column="zipcode"></property>
        <one-to-one name="user" class="com.andrew.model.User2" property-ref="address"></one-to-one>
    </class>
</hibernate-mapping>

UserTest.java

package com.andrew.service;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.andrew.model.Address;
import com.andrew.model.Address2;
import com.andrew.model.User;
import com.andrew.model.User2;
import com.andrew.util.HibernateUtil;
public class UserTest {
    private SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
    private Session session;
    @Before
    public void setUp() throws Exception {
        session=sessionFactory.openSession(); // 1. 生成一个session
        session.beginTransaction(); // 2. 开启事务
    }
    @After
    public void tearDown() throws Exception {
         session.getTransaction().commit(); // 3. 提交事务
         session.close(); // 4. 关闭session
    }
    @Test
    public void testSave2() {
        User2 user = new User2();
        user.setName("李四");
        Address2 address = new Address2();
        address.setAddress("某地方2");
        address.setZipcode("432422");
        address.setUser(user);
        user.setAddress(address);
        session.save(user);
    }
}

运行结果:
Hibernate: insert into t_address2 (address, zipcode) values (?, ?)
Hibernate: insert into t_user2 (userName, addressId) values (?, ?)
数据库:
t_address2
addressId    address    zipcode
1            某个地方   43242
t_user2
userId    userName    addressId
1         李四        1


2) Hibernate多对多映射关系实现

新建项目Hibernate08


2.1) 多对多单向实现

Student.java

package com.andrew.model;
import java.util.HashSet;
import java.util.Set;
public class Student {
    private int id;
    private String name;
    private Set<Course> courses = new HashSet<Course>();
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Set<Course> getCourses() {
        return courses;
    }
    public void setCourses(Set<Course> courses) {
        this.courses = courses;
    }
}

Student.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.andrew.model">
    <class name="Student" table="t_student">
        <id name="id" column="studentId">
            <generator class="native"></generator>
        </id>
        <property name="name" column="studentName"></property>
        <set name="courses" table="student_course" cascade="save-update">
            <key column="student_id"></key>
            <many-to-many class="com.andrew.model.Course" column="course_id"></many-to-many>
        </set>
    </class>
</hibernate-mapping>

Course.java

package com.andrew.model;
public class Course {
    private int id;
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

Course.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.andrew.model">
    <class name="Course" table="t_course">
        <id name="id" column="courseId">
            <generator class="native"></generator>
        </id>
        <property name="name" column="courseName"></property>
    </class>
</hibernate-mapping>

StudentTest.java

package com.andrew.service;
import java.util.Iterator;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.andrew.model.Course;
import com.andrew.model.Course2;
import com.andrew.model.Student;
import com.andrew.model.Student2;
import com.andrew.util.HibernateUtil;
public class StudentTest {
    private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    private Session session;
    @Before
    public void setUp() throws Exception {
        session = sessionFactory.openSession(); // 1. 生成一个session
        session.beginTransaction(); // 2. 开启事务
    }
    @After
    public void tearDown() throws Exception {
        session.getTransaction().commit(); // 3. 提交事务
        session.close(); // 4. 关闭session
    }
    @Test
    public void testSave1() {
        Course course1 = new Course();
        course1.setName("语文");
        Course course2 = new Course();
        course2.setName("数学");
        Student student1 = new Student();
        student1.setName("张三");
        student1.getCourses().add(course1);
        student1.getCourses().add(course2);
        Student student2 = new Student();
        student2.setName("李四");
        student2.getCourses().add(course1);
        student2.getCourses().add(course2);
        session.save(student1);
        session.save(student2);
    }
    @Test
    public void testLoad1() {
        Student student = (Student) session.get(Student.class, 1);
        Set<Course> courses = (Set<Course>) student.getCourses();
        Iterator it = courses.iterator();
        while (it.hasNext()) {
            Course c = (Course) it.next();
            System.out.println(c.getName());
        }
    }
}

运行结果:
Hibernate: insert into t_student (studentName) values (?)
Hibernate: insert into t_course (courseName) values (?)
Hibernate: insert into t_course (courseName) values (?)
Hibernate: insert into t_student (studentName) values (?)
Hibernate: insert into student_course (student_id, course_id) values (?, ?)
Hibernate: insert into student_course (student_id, course_id) values (?, ?)
Hibernate: insert into student_course (student_id, course_id) values (?, ?)
Hibernate: insert into student_course (student_id, course_id) values (?, ?)
数据库:
t_student
studentId    studentName
1            张三
2            李四
t_course
courseId    courseName
1           语文
2           数学
student_course
student_id    course_id
1             1
1             2
2             1
2             2
运行结果:
Hibernate: select student0_.studentId as studentI1_4_0_, student0_.studentName as studentN2_4_0_ from t_student student0_ where student0_.studentId=?
Hibernate: select courses0_.student_id as student_1_4_0_, courses0_.course_id as course_i2_0_0_, course1_.courseId as courseId1_2_1_, course1_.courseName as courseNa2_2_1_ from student_course courses0_ inner join t_course course1_ on courses0_.course_id=course1_.courseId where courses0_.student_id=?
数学
语文


2.2) 多对多双向实现

Student2.java

package com.andrew.model;
import java.util.HashSet;
import java.util.Set;
public class Student2 {
    private int id;
    private String name;
    private Set<Course2> courses = new HashSet<Course2>();
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Set<Course2> getCourses() {
        return courses;
    }
    public void setCourses(Set<Course2> courses) {
        this.courses = courses;
    }
}

Student2.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.andrew.model">
    <class name="Student2" table="t_student2">
        <id name="id" column="studentId">
            <generator class="native"></generator>
        </id>
        <property name="name" column="studentName"></property>
        <set name="courses" table="student_course2" cascade="save-update">
            <key column="student_id"></key>
            <many-to-many class="com.andrew.model.Course2" column="course_id"></many-to-many>
        </set>
    </class>
</hibernate-mapping>

Course2.java

package com.andrew.model;
import java.util.HashSet;
import java.util.Set;
public class Course2 {
    private int id;
    private String name;
    private Set<Student2> students = new HashSet<Student2>();
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Set<Student2> getStudents() {
        return students;
    }
    public void setStudents(Set<Student2> students) {
        this.students = students;
    }
}

Course2.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.andrew.model">
    <class name="Course2" table="t_course2">
        <id name="id" column="courseId">
            <generator class="native"></generator>
        </id>
        <property name="name" column="courseName"></property>
        <set name="students" table="student_course2" inverse="true" >
            <key column="course_id"></key>
            <many-to-many class="com.andrew.model.Student2" column="student_id"></many-to-many>
        </set>
    </class>
</hibernate-mapping>

StudentTest.java

package com.andrew.service;
import java.util.Iterator;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.andrew.model.Course;
import com.andrew.model.Course2;
import com.andrew.model.Student;
import com.andrew.model.Student2;
import com.andrew.util.HibernateUtil;
public class StudentTest {
    private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    private Session session;
    @Before
    public void setUp() throws Exception {
        session = sessionFactory.openSession(); // 1. 生成一个session
        session.beginTransaction(); // 2. 开启事务
    }
    @After
    public void tearDown() throws Exception {
        session.getTransaction().commit(); // 3. 提交事务
        session.close(); // 4. 关闭session
    }
    @Test
    public void testSave2() {
        Course2 course1 = new Course2();
        course1.setName("语文");
        Course2 course2 = new Course2();
        course2.setName("数学");
        Student2 student1 = new Student2();
        student1.setName("张三");
        student1.getCourses().add(course1);
        student1.getCourses().add(course2);
        Student2 student2 = new Student2();
        student2.setName("李四");
        student2.getCourses().add(course1);
        student2.getCourses().add(course2);
        session.save(student1);
        session.save(student2);
    }
    @Test
    public void testLoad2() {
        Course2 course = (Course2) session.get(Course2.class, 1);
        Set<Student2> students = (Set<Student2>) course.getStudents();
        Iterator it = students.iterator();
        while (it.hasNext()) {
            Student2 s = (Student2) it.next();
            System.out.println(s.getName());
        }

    }
}

运行结果:
Hibernate: insert into t_student2 (studentName) values (?)
Hibernate: insert into t_course2 (courseName) values (?)
Hibernate: insert into t_course2 (courseName) values (?)
Hibernate: insert into t_student2 (studentName) values (?)
Hibernate: insert into student_course2 (student_id, course_id) values (?, ?)
Hibernate: insert into student_course2 (student_id, course_id) values (?, ?)
Hibernate: insert into student_course2 (student_id, course_id) values (?, ?)
Hibernate: insert into student_course2 (student_id, course_id) values (?, ?)
数据库:
t_student
studentId    studentName
1            张三
2            李四
t_course2
courseId    courseName
1           语文
2           数学
student_course2
student_id    course_id
1             1
1             2
2             1
2             2
运行结果:
Hibernate: select course2x0_.courseId as courseId1_3_0_, course2x0_.courseName as courseNa2_3_0_ from t_course2 course2x0_ where course2x0_.courseId=?
Hibernate: select students0_.course_id as course_i2_3_0_, students0_.student_id as student_1_1_0_, student2x1_.studentId as studentI1_5_1_, student2x1_.studentName as studentN2_5_1_ from student_course2 students0_ inner join t_student2 student2x1_ on students0_.student_id=student2x1_.studentId where students0_.course_id=?
张三
李四
分享到:
评论

相关推荐

    hibernate 映射关系学习入门 一对一映射

    本文将深入探讨 Hibernate 中的一对一映射关系,并以"hibernate 映射关系学习入门 一对一映射Eclipse源码"为主题,详细解析其概念、配置以及实际应用。 一对一映射是Hibernate中的一种关联关系,它表示两个实体之间...

    hibernate 映射关系

    hibernate 映射关系

    Hibernate映射关系配置:XML方式和注解方式

    标题“Hibernate映射关系配置:XML方式和注解方式”涉及到的是Java持久层框架Hibernate中的一个重要概念——对象关系映射(ORM)。在这个主题中,我们将探讨如何通过XML映射文件和注解来配置Hibernate实体之间的关系...

    hibernate映射关系讲解

    本文将深入讲解 Hibernate 中的映射关系,特别是如何实现一对一(One-to-One)的关联映射。 首先,Hibernate 的核心配置始于 `Configuration` 接口,它用于加载配置文件并创建 `SessionFactory`。`SessionFactory` ...

    hibernate 映射关系学习入门 多对多实体映射

    二、多对多映射关系 在关系数据库中,多对多关系是指两个表之间存在多个对应关系。例如,学生可以选修多门课程,而课程也可以被多名学生选修。在Hibernate中,多对多关系通过中间表(也称为联接表或关联表)来实现,...

    hibernate映射关系总结

    hibernate开发的关系: one-to-one,many-to-one,many-to-many学习经验总结

    Hibernate映射关系代码

    hibernate中oneTOone,one to many等映射关系代码

    hibernate映射关系关联查询

    关于hibernate的关联操作 分享下

    Hibernate映射解析 七种映射关系 后端 - Java.zip

    这个名为“Hibernate映射解析 七种映射关系 后端 - Java”的压缩包文件显然包含了关于Hibernate映射关系的详细讲解。让我们深入探讨一下Hibernate的映射解析及其七种主要的映射关系。 首先,Hibernate通过XML映射...

    hibernate映射关系

    在Java持久化框架Hibernate中,映射关系是数据库表与对象模型之间的一种关联方式,它使得数据操作可以更加便捷地在对象层面上进行。本文将深入探讨Hibernate中的三种主要映射关系:一对一(One-to-One)、一对多...

    hibernate表的映射关系总结

    hibernate表映射一直记不住,这次总结一下,放便下次使用。。。

    Hibernate映射关联关系总结

    对Hibernate映射关系详细总结,可以帮助你学习Hibernate知识

    Hibernate映射

    hibernate 映射关系 小结

    生成hibernate映射文件工具

    hibernate映射文件是Java开发中用于对象关系映射(ORM)的重要组成部分,它将数据库表与Java类之间的关系进行定义,使得开发者无需编写大量的SQL语句,就能实现对数据库的操作。`生成hibernate映射文件工具`是为了...

    用Hibernate映射继承关系

    ### 用Hibernate映射继承关系 #### 14.1 继承关系树的每个具体类对应一个表 在Hibernate中映射继承关系时,一种常见的策略是将继承关系树的每个具体类映射到单独的数据库表中。这种方法称为**表/类映射**(Table/...

    Hibernate对象关系映射

    Hibernate对象关系映射一对多 很基础等文档

Global site tag (gtag.js) - Google Analytics