hibernate的单向多对一

例:省市城市之间的关系

Province.java

package www.csdn.net.blank.bean;

import java.io.Serializable;

public class Province  implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Integer id;
	private String name;

	public Province() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Province(Integer id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

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

}

City.java

package www.csdn.net.blank.bean;

import java.io.Serializable;

public class City implements Serializable{
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Integer id;
        private String  name;

        private Province province;
	public City() {
		super();
		// TODO Auto-generated constructor stub
	}
	public City(Integer id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	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 Province getProvince() {
		return province;
	}
	public void setProvince(Province province) {
		this.province = province;
	}
    
}

Provice的配置文件Provice.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="www.csdn.net.blank.bean">

	<class name="Province" table="pro">
		<id name="id" column="pro_id">
			<!-- 主键的生成策略 -->
			<generator class="native" />
		</id>
		<property name="name" column="pro_name" length="40"
			unique="true"/>
	</class>
</hibernate-mapping>

City 的配置文件City.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="www.csdn.net.blank.bean">

	<class name="City" table="city">
		<id name="id" column="city_id">
			<!-- 主键的生成策略 -->
			<generator class="native" />
		</id>
		<property name="name" column="city_name" length="40"
			unique="true" />
   

//Hibernate 使用 <many-to-one> 元素来映射多对一关联关系

many-to-one属性:

* name:设定待映射的持久化类的名字。

* column:设定和持久化类的属性对应的表的外键。

* class:设定持久化类的属性的类型。

* not-null:是否允许为空。

<many-to-one name="province" class="Province"> <column name="pro_id" not-null="false"></column> </many-to-one>  </class> </hibernate-mapping>

Hibernate封装BaseDao接口实现增删查改

package www.csdn.net.blank.dao;

import java.io.Serializable;
import java.util.List;


@SuppressWarnings("rawtypes")
public interface BaseDao {


	/**
	 * 保存实体对象
	 * 
	 * @param entity
	 */
	public void saveObject(Object entity);

	/**
	 * 更新实体对象
	 * 
	 * @param entity
	 */
	public void updateObject(Object entity);

	/**
	 * 删除实体对象
	 * 
	 * @param entity
	 */
	public void deleteObject(Object entity);

	/**
	 * 根据id删除实体对象
	 * 
	 * @param clazz
	 * @param id
	 */
	public void deleteObjectById(Class clazz,Serializable id);

	/**
	 * 根据id查询实体对象
	 * 
	 * @param clazz
	 * @param id
	 * @return
	 */
	public Object loadObjectById(Class clazz, Serializable id);

	/**
	 * 根据id查询实体对象
	 * 
	 * @param clazz
	 * @param id
	 * @return
	 */
	public Object getObjectById(Class clazz, Serializable id);

	/**
	 * 查询所有的操作
	 * 
	 * @param clazz
	 * @return
	 */
	public List getObjects(Class clazz);

}

实现 BaseDao接口的类BaseDaoImpl

package www.csdn.net.blank.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

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

import www.csdn.net.blank.dao.BaseDao;
import www.csdn.net.blank.util.BaseHibernateDaoImpl;

@SuppressWarnings("rawtypes")
public class BaseDaoImpl extends BaseHibernateDaoImpl implements BaseDao {

	@Override
	public void saveObject(Object entity) {

		// 获取session对象
		Session session = getSessionObject();
		// 打开事务
		Transaction ts = session.beginTransaction();
		try {
			// 保存
			session.save(entity);
			// 提交事务
			ts.commit();
		} catch (Exception e) {
			ts.rollback();
		}
	}

	@Override
	public void updateObject(Object entity) {
		// 获取session对象
		Session session = getSessionObject();
		// 打开事务
		Transaction ts = session.beginTransaction();
		try {
			// 保存
			session.update(entity);
			// 提交事务
			ts.commit();
		} catch (Exception e) {
			ts.rollback();
		}
	}

	@Override
	public void deleteObject(Object entity) {
		// 获取session对象
		Session session = getSessionObject();
		// 打开事务
		Transaction ts = session.beginTransaction();
		try {
			// 保存
			session.delete(entity);
			// 提交事务
			ts.commit();
		} catch (Exception e) {
			ts.rollback();
		}

	}

	@Override
	public void deleteObjectById(Class clazz, Serializable id) {
		// 获取session对象
		Session session = getSessionObject();
		// 打开事务
		Transaction ts = session.beginTransaction();
		try {
			// 保存
			session.delete(getObjectById(clazz, id));
			// 提交事务
			ts.commit();
		} catch (Exception e) {
			ts.rollback();
		}

	}

	@Override
	public Object loadObjectById(Class clazz, Serializable id) {
		return null;
	}

	@Override
	public Object getObjectById(Class clazz, Serializable id) {

		Object obj = null;
		Session session = getSessionObject();
		Transaction ts = session.beginTransaction();
		try {
			obj = session.get(clazz, id);
			ts.commit();
		} catch (Exception e) {
			ts.rollback();
		}finally{
			session.close();
		}
		return obj;
	}

	@Override
	public List getObjects(Class clazz) {
		List list =  new ArrayList();
		Session session = getSessionObject();
		Transaction ts = session.beginTransaction();
		try {
			list = session.createQuery("from "+clazz.getName()).list();
			ts.commit();
		} catch (Exception e) {
			ts.rollback();
		}
		return list;
	}

}

Hibernate封装的工具类HiberUtil.java

package www.csdn.net.blank.util;

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

public class HiberUtil {

	static Configuration cfg;
	static ServiceRegistry serviceRegistry;
	static SessionFactory sessionFactory;
	
	static{
		//创建Configuration对象  调用.configure()方法 ,默认class/hibernate.cfg.xml
		cfg = new Configuration().configure();
		
		//创建服务对象
		serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
		
		//创建sessionFactory工厂
		sessionFactory = cfg.buildSessionFactory(serviceRegistry);
	}
	
	
	/**
	 * 获取session对象
	 * @return
	 */
	public static Session openSession(){
		return sessionFactory.openSession();
	}
	
}
hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
	<!-- 数据库的驱动 -->
	<property name="connection.driver_class">
		com.mysql.jdbc.Driver
	</property>
	<!-- 数据库的URL -->
	<property name="connection.url">
		jdbc:mysql://localhost:3306/jd2?useUincode=true&characterEncoding=UTF-8
	</property>
	<!-- 数据库的用户名 -->
	<property name="connection.username">root</property>
	<!-- 数据库的密码 -->
	<property name="connection.password">root</property>
	<!-- 数据库的方言 -->
	<property name="hibernate.dialect">
		org.hibernate.dialect.MySQLDialect
	</property>

	<!-- Enable Hibernate's automatic session context management -->
	<property name="current_session_context_class">thread</property>

	<!-- 显示操作的sql语句 -->
	<property name="hibernate.show_sql">true</property>
	<!-- 格式sql语句 -->
	<property name="hibernate.format_sql">false</property>
	<!-- 自动创建和更新表结构 -->
	<property name="hibernate.hbm2ddl.auto">update</property>



	<!-- 映射文件引入 -->
	<mapping resource="www/csdn/net/blank/bean/City.hbm.xml" />
	<mapping resource="www/csdn/net/blank/bean/Provice.hbm.xml" />
</session-factory>

</hibernate-configuration>

测试类

package www.csdn.net.blank.junit;

import org.junit.Test;

import www.csdn.net.blank.bean.City;
import www.csdn.net.blank.bean.Province;
import www.csdn.net.blank.dao.BaseDao;
import www.csdn.net.blank.dao.impl.BaseDaoImpl;
import www.csdn.net.blank.util.HiberUtil;

public class Test1 {
	@Test
	public void test() {
		HiberUtil.openSession();
	}
	private BaseDao baseDao=new BaseDaoImpl();
	@Test
	public void save(){
		Province province=new Province();
		province.setName("河北省1");
		
		City entity=new City();
		entity.setName("石家庄");
		entity.setProvince(province);
		
		baseDao.saveObject(entity);
		
	}
	@Test
	public void  update(){
		City entity=(City) baseDao.getObjectById(City.class, 2);
		if(entity!=null){
			System.out.println(entity.getName());
		}else{
			System.out.println("xxxx");
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值