1. 程式人生 > 其它 >Hibernate 一對多關係

Hibernate 一對多關係

技術標籤:JavaHibernatehibernatemysqljava

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;

最後

  • 由於博主水平有限,不免有疏漏之處,歡迎讀者隨時批評指正,以免造成不必要的誤解!