Hibernate多对一,多对多的表映射关系

Posted 那爱多情

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hibernate多对一,多对多的表映射关系相关的知识,希望对你有一定的参考价值。

版权声明:本文为博主原创文章,未经博主允许不得转载。

package com.huangchao.model;

import java.io.Serializable;
import java.util.Date;

/**
 * @author huangchao
 *
 */
public class User implements Serializable{
    private Integer uid ;
    private String uname ;
    private String password ;
    private String gender ;
    private Integer age ;
    private Date birth ;
    private Contact contact ;
    private Date createtime ;
    private Department dept ;
    
    /**
     * 
     */
    public User() {}

    public User(String uname, String password, String gender, Integer age, Date birth, Contact contact, Date createtime,
            Department dept) {
        super();
        this.uname = uname;
        this.password = password;
        this.gender = gender;
        this.age = age;
        this.birth = birth;
        this.contact = contact;
        this.createtime = createtime;
        this.dept = dept;
    }

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public Contact getContact() {
        return contact;
    }

    public void setContact(Contact contact) {
        this.contact = contact;
    }

    public Date getCreatetime() {
        return createtime;
    }

    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }

    public Department getDept() {
        return dept;
    }

    public void setDept(Department dept) {
        this.dept = dept;
    }

    @Override
    public String toString() {
        return "User [uid=" + uid + ", uname=" + uname + ", password=" + password + ", gender=" + gender + ", age="
                + age + ", birth=" + birth + ", createtime=" + createtime + ", dept=" + dept + "]";
    }
    
}

 各位小伙伴一定要注意:在书写实体类时,最好让实体类实现Serilizable序列化接口,并且实体类代码一定要符合JavaBean规范

/**
 * 
 */
package com.huangchao.model;

/**
 * @author huangchao
 *
 */
public class Contact {
    private String email ;
    private String province ;
    private String city ;
    private String country ;     //
    private String town ;        //
    private String street ;        //街道
    
    /**
     * 
     */
    public Contact(){}

    public Contact(String email, String province, String city, String country, String town, String street) {
        super();
        this.email = email;
        this.province = province;
        this.city = city;
        this.country = country;
        this.town = town;
        this.street = street;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getTown() {
        return town;
    }

    public void setTown(String town) {
        this.town = town;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    @Override
    public String toString() {
        return "Contact [email=" + email + ", province=" + province + ", city=" + city + ", country=" + country
                + ", town=" + town + ", street=" + street + "]";
    }
    
    
}

 Department.java

/**
 * 
 */
package com.huangchao.model;

import java.io.Serializable;

/**
 * @author Huangchao
 *
 */
public class Department implements Serializable{
    private Integer deptid ;
    private Integer dname ;
    
    
    public Department() {
    }


    public Department(Integer dname) {
        super();
        this.dname = dname;
    }


    public Integer getDeptid() {
        return deptid;
    }


    public void setDeptid(Integer deptid) {
        this.deptid = deptid;
    }


    public Integer getDname() {
        return dname;
    }


    public void setDname(Integer dname) {
        this.dname = dname;
    }
    
}

写完实体类,现在就要开始.hbm.xml文件的创建了,大家可以手写,也可以使用hibernate tools自动创建,,,,,初学都建议自己动手写,这样也可以加深影响,也可以更好的熟悉有hibernate是如何将实体类自动转化为hbm文件的

下面是User.hbm.xml的详细代码 :

<?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-8-28 12:23:47 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="com.huangchao.model.User" table="USER">  //设置数据库表为user
        <id name="uid" type="java.lang.Integer">
            <column name="UID" />
            <generator class="native" />  //主键生成策略,native表示让底层数据库自动选择,mysql默认为主键自增
        </id>

<!-- 多对一的表关系映射-->
        <many-to-one name="dept" class="com.huangchao.model.Department" >  //对应的关联外键的生成表的类
            <column name="DEPT" />  //对应的外键
        </many-to-one>
        <property name="uname" type="java.lang.String">
            <column name="UNAME" />
        </property>
        <property name="password" type="java.lang.String">
            <column name="PASSWORD" />
        </property>
        <property name="gender" type="java.lang.String">
            <column name="GENDER" />
        </property>
        <property name="age" type="java.lang.Integer">
            <column name="AGE" />
        </property>
        <property name="birth" type="java.util.Date">
            <column name="BIRTH" />
        </property>

  //以组件的形式添加Contact,该Contact通过component表示后不会自动生成数据库中的表,它会以user数据表的字段的形式添加进数据库user表中
        <component name="contact"  class="com.huangchao.model.Contact">
         <property name="province" column="PROVINCE" type="string" />
         <property name="city" column="CITY" type="string" />
         <property name="country" column="COUNTRY" type="string" />
         <property name="town" column="TOWN" type="string" />
         <property name="street" column="STREET" type="string" />
        </component>
 
        <property name="createtime" type="java.util.Date">
            <column name="CREATETIME" />
        </property>
    </class>
</hibernate-mapping>

Department.hbm.xml

 

<?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-8-28 0:41:06 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="com.huangchao.model.Department" table="DEPARTMENT">
        <id name="deptid" type="java.lang.Integer">
            <column name="DEPTID" />
            <generator class="native" />
        </id>
        <property name="dname" type="java.lang.Integer">
            <column name="DNAME" />
        </property>
    </class>
</hibernate-mapping>

 

至此,重启服务器,sessionFactory会自动为我们创建数据库表.

多对多关系映射

Event ---------------------事件 表

Person--------------------用户 表

Person_Event_Relation-----------用户事件关系表

创建实体类

Event.java

 

/**
 * 
 */
package com.huangchao.model;

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

/**
 * @author Administrator
 *
 */
public class Events implements Serializable {

        private Integer eid ;    //Primary key
        private Date date ;
        private String title ;
        
        private Set<Person> person = new HashSet<Person>();

        public Integer getEid() {
            return eid;
        }

        public void setEid(Integer eid) {
            this.eid = eid;
        }

        public Date getDate() {
            return date;
        }

        public void setDate(Date date) {
            this.date = date;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public Set<Person> getPerson() {
            return person;
        }

        public void setPerson(Set<Person> person) {
            this.person = person;
        }
        
}

 

Person.java

 

/**
 * 
 */
package com.huangchao.model;

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

/**
 * @author Administrator
 *
 */
public class Person implements Serializable {

    private Integer id; // Primary Key
    private String firstname;
    private String lastname;

    private Set<Events> events = new HashSet<Events>();


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public Set<Events> getEvents() {
        return events;
    }

    public void setEvents(Set<Events> events) {
        this.events = events;
    }

}

 

添加实体类所对应的hbm.xml文件

Event.hbm.xml

 

<?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-8-28 0:41:06 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping >
  <class name="com.huangchao.model.Events" table="EVENT">
      <id name="eid" column="EVENT_ID" type="int">
          <generator class="native" />
      </id>
      <property name="title" column="TITLE" type="string" />
      <property name="date" column="DATE" type="date" />
      
      <set name="person" table="PERSON_EVENT">
          <key column="EVENT_ID" />
          <many-to-many class="com.huangchao.model.Person" column="PERSON_ID" />
      </set>
  </class>
</hibernate-mapping>

 

Person.hbm.xml

 

<?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-8-28 0:41:06 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping >
  <class name="com.huangchao.model.Person" table="PERSON">
      <id name="id" column="PERSON_ID" type="int">
          <generator class="native"/>
      </id>
      <property name="firstname" column="FIRST_NAME" type="string" />
      <property name="lastname" column="LAST_NAME" type="string" />
      <set name="events" table="PERSON_EVENT" inverse="false">
          <key column="PERSON_ID" />
          <many-to-many class="com.huangchao.model.Events" column="EVENT_ID" />
      </set>
  </class>
</hibernate-mapping>

 

注意:inverse=true是将控制权交给对方,inverse=false是默认的,即Person掌握控制权

至此,所有的多对多关系配置成功,

添加测试文件测试工.

Configuration config = new Configuration().configure();

ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySetting(config.getProperties()).build();//注册服务,hibernate从4.3开始新添的一个方法,废弃了之前的方法,该 方法更安全更方便.

SessionFactory sessionFactory = config.buildSessinFactory(serviceRegistry);

Session session = sessionFactory.getCurrentSession();  //getCurrentSession()相比于openSession()前者是基于当前线程的,是线程 安全的,前都不用关心session的关闭,更人性化,后者的话是每次服务启动,sessionFActory都 会创建一个session 的实例,这样对服务器的消耗更大,而且需要关心session的关闭

Transaction tx = session.beginTransaction();

 

以上是关于Hibernate多对一,多对多的表映射关系的主要内容,如果未能解决你的问题,请参考以下文章

hibernate 关联关系(多对多对多一对一)的配置

hibernate多对多映射中间表有多余字段问题该如何映射

Hibernate的关联关系映射

Hibernate框架学习之注解配置关系映射

Hibernate映射关系:一对一对多和多对多

hibernate映射的 关联关系:有 一对多关联关系,一对一关联关系,多对多关联关系,继承关系