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.many-to-many-hibernate</groupId> <artifactId>ManyToManyHibernate</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/many2many/User.hbm.xml"/>
        <mapping resource="com/demo/hibernate/many2many/Commodity.hbm.xml"/>

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

對映檔案

引數

  • set

    • key : 外來鍵
      • column : 外來鍵名
    • one-to-many :
      • class : 被參照類的包名和類名
  • name : 被參照類對應的Set物件

  • table : 聯絡表

  • cascade : 級聯儲存

  • many-to-one

    • name : 參照表名
    • class : 參照類的包名和類名
    • column : 外來鍵名

User類對映檔案

src/main/java/com/demo/hibernate/many2many/User.hbm.xml

<?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.many2many.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="commodities" table="`order`" cascade="save-update">
            <key column="user_id"></key>
            <many-to-many class="com.demo.hibernate.many2many.Commodity" column="commodity_id"></many-to-many>
        </set>
    </class>
</hibernate-mapping>

Commodity類對映檔案

src/main/java/com/demo/hibernate/many2many/Commodity.hbm.xml

<?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.many2many.Commodity" table="commodity" catalog="hibernate">
        <id name="id" column="id">
            <generator class="native" />
        </id>
        <property name="price" column="price"></property>
        <property name="name" column="name" length="128"></property>
        <property name="description" column="description" length="256"></property>
        <set name="users" table="`order`">
            <key column="commodity_id"></key>
            <many-to-many class="com.demo.hibernate.many2many.User" column="user_id"></many-to-many>
        </set>
    </class>
</hibernate-mapping>

Java程式碼

User類

src/main/java/com/demo/hibernate/many2many/Commodity.java

package com.demo.hibernate.many2many;

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

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

    private Set<Commodity> commodities;

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

    public User() {
    }

    public Set<Commodity> getCommodities() {
        return commodities;
    }

    public void setCommodities(Set<Commodity> commodities) {
        this.commodities = commodities;
    }

    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;
    }
}

Commodity類

src/main/java/com/demo/hibernate/many2many/Commodity.java

package com.demo.hibernate.many2many;

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

public class Commodity {
    private int id;
    private double price;
    private String name;
    private String description;

    private Set<User> users;

    public Commodity() {
    }

    public Commodity(double price, String name, String description) {
        this.price = price;
        this.name = name;
        this.description = description;
        users = new HashSet<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 getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Set<User> getUsers() {
        return users;
    }

    public void setUsers(Set<User> users) {
        this.users = users;
    }
}

Hibernate類

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

package com.demo.hibernate.many2many;

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

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 commit() {
        transaction.commit();
    }

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

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

        User user1 = new User("Tony", "123456");
        User user2 = new User("Tom", "123456");

        Commodity commodity1 = new Commodity(32.0, "Coke", "Coca Cola 24 cans");
        Commodity commodity2 = new Commodity(64.0, "Milk", "Milk 24 bottles");
        Commodity commodity3 = new Commodity(128.0, "T-shirt", "T-shirt");
        Commodity commodity4 = new Commodity(256.0, "Coat", "Coat");

        user1.getCommodities().add(commodity1);
        user1.getCommodities().add(commodity2);
        user1.getCommodities().add(commodity3);
        user1.getCommodities().add(commodity4);

        user2.getCommodities().add(commodity1);

        hibernate.insert(user1);
        hibernate.insert(user2);

        hibernate.commit();
    }
}


測試結果

select user.id user_id, username, commodity.id commodity_id, name commodity_name, price, description commodity_description from user left join `order` on `order`.user_id = user.id left join commodity on `order`.commodity_id = commodity.id;

最後

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