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

最后

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值