Hibernate 一对多关系

Hibernate 一对多关系

环境

java 12.0.1
Apache Maven 3.6.3
MySQL Server version: 5.7.18-20170830-log 20170531
hibernate-core-5.4.27.Final.jar
mysql-connector-java-8.0.21.jar
IntelliJ IDEA 2020.2.3 (Ultimate Edition)

Maven配置文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demo.one-to-many-hibernate</groupId>
    <artifactId>OneToManyHibernate</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-agroal</artifactId>
            <version>5.4.27.Final</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>12</source>
                    <target>12</target>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.hbm.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

</project>

Hibernate核心配置文件

src/main/resources/hibernate.cfg.xml

数据库参数

  • [hostname] : 主机名(本地为localhost
  • [port] : 端口号(默认端口号为3306
  • [database] : 数据库名
  • [username] : 用户名
  • [password] : 密码

配置文件

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- dialect configuration -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>

        <!-- database configuration -->
        <property name="hibernate.connection.url">jdbc:mysql://[hostname]:[port]/[database]</property>
        <property name="hibernate.connection.username">[username]</property>
        <property name="hibernate.connection.password">[password]</property>

        <!-- hibernate configuration-->

        <property name="hibernate.show_sql">true</property>
        
        <!-- update: create if table not exist, else update-->
        <property name="hibernate.hbm2ddl.auto">update</property>
		
		<!-- mapping resource -->
        <mapping resource="com/demo/hibernate/one2many/User.hbm.xml"/>
        <mapping resource="com/demo/hibernate/one2many/Order.hbm.xml"/>

    </session-factory>
</hibernate-configuration>

映射文件

参数

  • set

    • key : 外键
      • column : 外键名
    • one-to-many :
      • class : 被参照类的包名和类名
  • name : 被参照类对应的Set对象

  • cascade : 级联保存

  • many-to-one

    • name : 参照表名
    • class : 参照类的包名和类名
    • column : 外键名

User类映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!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.demo.hibernate">
    <class name="com.demo.hibernate.one2many.User" table="user" catalog="hibernate">
        <id name="id" column="id">
            <generator class="native" />
        </id>
        <property name="username" column="username" length="128"></property>
        <property name="password" column="password" length="128"></property>
        <set name="orders" cascade="save-update">
            <key column="user_id"></key>
            <one-to-many class="com.demo.hibernate.one2many.Order"/>
        </set>
    </class>
</hibernate-mapping>

Order类映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!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.demo.hibernate">
    <class name="com.demo.hibernate.one2many.Order" table="order" catalog="hibernate">
        <id name="id" column="id">
            <generator class="native" />
        </id>
        <property name="price" column="price"></property>
        <property name="timestamp" column="timestamp" length="128"></property>

        <many-to-one name="user" class="com.demo.hibernate.one2many.User" column="user_id"></many-to-one>
    </class>
</hibernate-mapping>

Java代码

User类

src/main/java/com/demo/hibernate/one2many/User.java

package com.demo.hibernate.one2many;

import java.util.HashSet;
import java.util.Set;

public class User {
    private int id;
    private String username;
    private String password;

    private Set<Order> orders;

    public User(String user, String password) {
        this.username = user;
        this.password = password;
        orders = new HashSet<Order>();
    }

    public User() {
        orders = new HashSet<Order>();
    }

    public Set<Order> getOrders() {
        return orders;
    }

    public void setOrders(Set<Order> orders) {
        this.orders = orders;
    }

    public int getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Order类

src/main/java/com/demo/hibernate/one2many/Order.java

package com.demo.hibernate.one2many;

public class Order {
    private int id;
    private double price;
    private String timestamp;

    private User user;

    public Order() {
    }

    public Order(double price, String timestamp) {
        this.price = price;
        this.timestamp = timestamp;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public int getId() {
        return id;
    }

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

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }
}

Hibernate类

src/main/java/com/demo/hibernate/one2many/Hibernate.java

package com.demo.hibernate.one2many;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;

import java.util.*;

public class Hibernate {
    private Configuration configuration;
    private StandardServiceRegistry standardServiceRegistry;
    private SessionFactory sessionFactory;
    protected Session session;
    protected Transaction transaction;

    public Hibernate() {
        try {
            configuration = new Configuration();
            configuration.configure("hibernate.cfg.xml");
            standardServiceRegistry = new StandardServiceRegistryBuilder().configure().build();
            sessionFactory = configuration.buildSessionFactory(standardServiceRegistry);
            session = sessionFactory.openSession();
            transaction = session.beginTransaction();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void insert(User user) {
        session.save(user);
        transaction.commit();
    }

    public static void main(String[] args) {
        Hibernate hibernate = new Hibernate();
        Date date = new Date();

        User user = new User("Tony", "123456");
        Set<Order> orders = new HashSet<Order>();
        orders.add(new Order(512.0, date.toString()));
        orders.add(new Order(1024.0, date.toString()));
        orders.add(new Order(2048.0, date.toString()));
        orders.add(new Order(4096.0, date.toString()));
        user.setOrders(orders);

        hibernate.insert(user);
    }
}

测试结果

select user.id user_id, user.username, `order`.id order_id, `order`.price, `order`.timestamp from user left join `order` on user.id = `order`.user_id;

最后

  • 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值