Hibernate多對一,多對多的表映射關係

版權聲明:本文爲博主原創文章,未經博主容許不得轉載。java

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規範ide

/**
 * 
 */
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();

相關文章
相關標籤/搜索