hibernate's many-to-many example

hibernate's many-to-many example


———— Regardless of success or failure, I just want to live my life seriously!
I am struggling for java engineers!

The younger brother has just ended struts2 in the three major frameworks, so sloppy, I don't know how to master it. Then it's over. I started the second framework two days ago, hibernate! Amount, I have learned it for almost three days, and the doorway inside can be seen a little. So, a small example is still needed. Ha ha.

This is a hibernate mapping problem, 1-N, N-1, 1-1, NN, so many kinds. I personally think that the previous ones should not be difficult. The difficulty is still nn. At first, it was a little mixed. Later, it is quite simple to think about it. Let's start below.


The same example uses the architecture of mvc. First post two javabeans.

package com.gang.entity;

import java.util.HashSet;
import java.util.Set;
//这是一个人类
public class Person {

    private int pid;
    private String name;
    private String sex;
    private Set<Address> addresses=new HashSet<Address>();
    //省略各元素的setter,getter方法
    ...
    //构造器
    public Person(String name, String sex) {
        super();
        this.name = name;
        this.sex = sex;
    }
    public Person(int pid, String name, String sex) {
        super();
        this.pid = pid;
        this.name = name;
        this.sex = sex;
    }

}

//这是一个地址类
package com.gang.entity;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

public class Address implements Serializable{
    private  int aid;
    private  String aname;
    private  String adesc;
    private  Set<Person> persons=new HashSet<Person>();
    //省略个元素的setter,getter方法
    ...
    //构造器
    public Address(int aid, String aname, String adesc) {
        super();
        this.aid = aid;
        this.aname = aname;
        this.adesc = adesc;
    }
    public Address(String aname, String adesc) {
        super();
        this.aname = aname;
        this.adesc = adesc;
    }


}

ok! Get two javabeans, of course this is pediatrics. Hibernate can use annotations for table mapping, or use the hbm.xml configuration file for configuration. I still use the latter.

<!--这是地址的配置文件-->
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-5-28 0:17:19 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.gang.entity.Address" table="address">
        <id name="aid" type="int">
            <column name="aid" />
            <generator class="increment" />
        </id>
        <property name="aname" type="java.lang.String">
            <column name="aname" />
        </property>
        <property name="adesc" type="java.lang.String">
            <column name="adesc" />
        </property>
       <!--这是地址类里的人类,他们是主外键关系,并将这两个类的id分别作为各自的外键,保存在p_a数据表里-->
        <set name="persons" table="p_a" inverse="false" cascade="all">
            <key>
                <column name="aid" />
            </key>
            <many-to-many class="com.imooc.entity.Person" column="pid"/>
        </set>
    </class>
</hibernate-mapping>

<!--这是人类的配置文件-->
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-5-28 0:17:19 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.imooc.entity.Person" table="person">
        <id name="pid" type="int">
            <column name="pid" />
            <generator class="increment" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" />
        </property>
        <property name="sex" type="java.lang.String">
            <column name="sex" />
        </property>
        <!--这是人类里的地址类,他们是主外键关系,并将这两个类的id分别作为各自的外键,保存在p_a数据表里-->
        <set name="addresses" table="p_a" cascade="save-update" inverse="true">
            <key>
                <column name="pid" />
            </key>
            <many-to-many class="com.imooc.entity.Address" column="aid"/>
        </set>
    </class>
</hibernate-mapping>

Two javabeans and two configuration files are very clear. Next is the hibernate configuration file. This file should be very clear after learning hibernate.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">chen*****</property>
        <property name="hibernate.connection.url">
            <![CDATA[
                jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=utf8
            ]]>
        </property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>

        <!-- 指定映射文件的路径 -->
        <mapping resource="com/gang/entity/Address.hbm.xml"/>
        <mapping resource="com/gang/entity/Person.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

Finally, we test him.
First write a tool class, used to obtain the necessary objects before testing.

package com.gang.util;

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

public class HibernateUtil {
    private static SessionFactory sessionFactory;
    private static Session session;

    static {
        // 创建Configuration对象,读取hibernate.cfg.xml文件,完成初始化
        Configuration config = new Configuration().configure();
        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder()
                .applySettings(config.getProperties());
        StandardServiceRegistry ssr=ssrb.build();
        sessionFactory=config.buildSessionFactory(ssr);
    }

    //获取SessionFactory
    public static SessionFactory getSessionFactory(){
        return sessionFactory;
    }

    //获取Session
    public static Session getSession(){
        session=sessionFactory.openSession();
        return session;
    }

    //关闭Session
    public static void closeSession(Session session){
        if(session!=null){
            session.close();
        }
    }
}

Finally, the test:

package com.gang.test;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.imooc.entity.Address;
import com.imooc.entity.Person;
import com.imooc.util.HibernateUtil;

public class test {

    private static Session session;
    public static void save(){
        Person p1=new Person("张三", "男");
        Person p2=new Person("李四", "男");
        Address a1=new Address("浙江", "德清");
        Address a2=new Address("浙江", "yuyue");
        p1.getAddresses().add(a1);
        p1.getAddresses().add(a2);
        p2.getAddresses().add(a1);
        a2.getPersons().add(p1);
        a1.getPersons().add(p2);
        a1.getPersons().add(p1);
        session=HibernateUtil.getSession();
        Transaction tx=session.beginTransaction();
        session.save(p1);
        session.save(p2);
        tx.commit();
        HibernateUtil.closeSession(session);

    }

    public static void main(String[] args) {
        save();
    }
}

. Running the above code, we found three more tables in the database

Write a picture description here

Write a picture description here

Write a picture description here

Not bad, consistent with the settings in the source code. (Zhang San is in Deqing and Yuyue, while Li Si is only in Deqing).


The three frameworks are simple and simple, and difficult to say. Ha ha! Come on. Step him under his feet.
2016/5/28 1:48 am

Published 26 original articles · received 1 · views 9795

Guess you like

Origin blog.csdn.net/qq_31884013/article/details/51521028