hibernate映射(三) 之Hibernate双向一对多(多对一)映射

数据库sql

DROP TABLE IF EXISTS `father`;
CREATE TABLE `father` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `son`;
CREATE TABLE `son` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `father_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

实体类

Father.java

package org.lei.model;

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

public class Father implements Serializable{
	private Integer id;							//主键id属性变量
	private String name;						//姓名属性变量
	private Set<Son>sons =new HashSet<>();		//set集合属性变量
	public Father(){}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Set<Son> getSons() {
		return sons;
	}
	public void setSons(Set<Son> sons) {
		this.sons = sons;
	}
	
	
	public void addSon(Son son){
		sons.add(son);
	}
	public void removeSon(Son son){
		sons.remove(son);
	}
}

Son.java

package org.lei.model;

import java.io.Serializable;

public class Son implements Serializable{
		private Integer id;    //主键id属性变量
		private String name;   //姓名属性变量
		private Father father;//父亲属性变量
		
		public Son(){}

		public Integer getId() {
			return id;
		}

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

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public Father getFather() {
			return father;
		}

		public void setFather(Father father) {
			this.father = father;
		}
		
		
}

映射文件

father.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"> 
    <hibernate-mapping>
        <class name="org.lei.model.Father" table="father">
            <id name="id" type="java.lang.Integer">
                <generator class="native"></generator>
            </id><!-- 配置主键映射 -->
            <property name="name" type="java.lang.String">
                <column name="name" length="20"></column>
            </property>
            <set name="sons" table="son" cascade="all" inverse="true">
                <key column="father_id"></key>
                <!-- 配置一对多映射关系 -->
                <one-to-many class="org.lei.model.Son"></one-to-many>
            </set>
        </class>
    </hibernate-mapping>

son.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"> 
    <hibernate-mapping>
   			<class name="org.lei.model.Son" table="son" >
   			    <id name="id" type="java.lang.Integer">
   			        <column name="id"></column>
   			        <generator class="native"></generator>
   			    </id>
   			    <property name="name" type="java.lang.String">
   			        <column name="name" length="20"/>
   			    </property>
   			    <!-- 配置多对一关系映射 -->
   			    <many-to-one name="father" column="father_id" cascade="save-update"
   			        outer-join="true">
   			    </many-to-one>
   			</class>
    </hibernate-mapping>

测试类Test.java

package com.test;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.lei.model.Father;
import org.lei.model.Son;

public class Test {
	public static void main(String [] args){
		//Configuration管理hibernate配置
		Configuration configuration = new Configuration().configure();
		 //2 创建一个Configuration对象,默认去加载 src 下 hibernate.cfg.xml文件  
        Configuration config=new Configuration().configure("hibernate.cfg.xml");   
        //3 得到一个SessionFactory对象(从工厂中造session)  
        SessionFactory sessionFactory=config.buildSessionFactory();  
           Father f1 = new Father();
           f1.setName("father1");
           
           Son son1 = new Son();
           son1.setName("son1");
           Son son2 = new Son();
           son2.setName("son2");
           f1.addSon(son1);
           f1.addSon(son2);
           son1.setFather(f1);
           son2.setFather(f1);
           
           Integer pid;//定义主键变量
           Session session = sessionFactory.openSession();
           Transaction tx = null;
           
           try {
			tx = session.beginTransaction();
			pid = (Integer) session.save(son2);
			tx.commit();
		} catch (HibernateException e) {  
            e.printStackTrace();  
            tx.rollback();//遇异常用回滚事务  
        } finally{
        	session.close();
        } 
           
	}
}


总结:

注意数据库的建立和映射文件的配置




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值