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配置文件


<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.0modelVersion>

    <groupId>com.demo.many-to-many-hibernategroupId>
    <artifactId>ManyToManyHibernateartifactId>
    <version>1.0-SNAPSHOTversion>

    <dependencies>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.hibernategroupId>
            <artifactId>hibernate-agroalartifactId>
            <version>5.4.27.Finalversion>
            <type>pomtype>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.21version>
        dependency>
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.17version>
        dependency>
    dependencies>

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

project>

Hibernate核心配置文件

src/main/resources/hibernate.cfg.xml

数据库参数

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

配置文件




<hibernate-configuration>
    <session-factory>
        
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialectproperty>
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driverproperty>

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

        

        <property name="hibernate.show_sql">trueproperty>
        
        
        <property name="hibernate.hbm2ddl.auto">updateproperty>
		
		
        <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



<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



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

最后

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

你可能感兴趣的:(Java,Hibernate,hibernate,mysql,java)