整合hibernate4到spring4mvc框架

二次信任 提交于 2019-12-01 14:20:05

1.总体设计思路  

写一个HibernateDao的公共接口HibernateCommonDao,实现基本的增删改查HibernateCommonDaoImpl,所有的具体业务类*DaoImpl都继承自HibernateCommonDaoImpl并且implements它自己的*Dao接口,这样一来基本的增删改查都用公共的,只针对具体业务实现自己的接口方法,业务类Service调用query对象方法的时候需要进行强制类型转换

2.springmvc管理hibernate的配置问题

2.1pom.xml配置仍然是http://my.oschina.net/u/555061/blog/506049,只不过增加Spring4Framework框架

2.2SpringHibernate4.xml--解决sessionFactory注册为SpringBean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-4.0.xsd">

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="packagesToScan">
            <list>
                <value>com.zhxjz.model.hibernateEmployee</value>
            </list>
        </property>
		<property name="hibernateProperties">
			<props>
				<prop key="dialect">${hibernate.dialect}</prop>
				<prop key="show_sql">${hibernate.show_sql}</prop>
				<!-- <prop key="hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> -->
			</props>
		</property>
	</bean>
	
	<!-- 配置Hibernate事务管理器(由于在SpringDatasource.xml已经配置了事务,因此这里不能再次配置)
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean> -->
</beans>

2.3 SpringDatasource.xml事务管理配置如下,这个事务管理对Hibernate的SessionFactory事务生效,同时对JdbcTemplate的事务管理生效

2.4 关于事务管理

需要在*ServiceImpl添加注解@Transactional,然后测试事务生效过程,

public void add(Object newObj) {
	Session session = getCurrentSession();
	session.save(newObj);
	SQLQuery query = getCurrentSession().createSQLQuery(
			"update hibernateemployee set employeeId=2 where uuid='uuid2'");
	query.executeUpdate();
}

这个sqlquery就是用来测试回滚的,修改主键违反主键唯一性原则导致update操作失败,测试是否先进行的save插入操作是否成功,结果是不成功,证明事务生效。

2.5 hibernate.properties,这里的含义可以参考http://my.oschina.net/u/555061/blog/506049

hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
#hibernate.hbm2ddl.auto=create

3.公共Dao/DaoImpl结构如下,

这里HibernateEmployeeDao/HibernateEmployeeDaoImpl是具体业务,HibernateCommonDao和HibernateCommonDaoImpl是公共接口方法(也就是增删改查ORM实现)

4.给出类源码

4.1HibernateCommonDao.java

package com.zhxjz.dao;

import java.util.List;

public interface HibernateCommonDao {
	public void add(Object newObj);
	public void del(Class<?> clazz, int id);
	public void update(Object updObj);
	public Object queryById(Class<?> clazz, int id);
	public List queryList(String sql);
}

4.2HibernateCommonDaoImpl.java

package com.zhxjz.dao.impl;

import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.zhxjz.dao.HibernateCommonDao;

@Component
public class HibernateCommonDaoImpl implements HibernateCommonDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	@Override
	public void add(Object newObj) {
		Session session = getCurrentSession();
		session.save(newObj);
		SQLQuery query = getCurrentSession().createSQLQuery(
				"update hibernateemployee set employeeId=2 where uuid='uuid2'");
		query.executeUpdate();
	}
	@Override
	public void del(Class<?> clazz, int id) {
		Session session = getCurrentSession();
		Object delObj = session.get(clazz, id);
		session.delete(delObj);
	}
	@Override
	public void update(Object updObj) {
		getCurrentSession().update(updObj);
	}
	@Override
	public Object queryById(Class<?> clazz, int id) {
		return getCurrentSession().get(clazz, id);
	}
	@Override
	public List queryList(String sql) {
		SQLQuery query = getCurrentSession().createSQLQuery(sql);
		return query.list();
	}
	protected Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}
}

4.3HibernateEmployeeDao.java

package com.zhxjz.dao.hibernateEmployee;

import com.zhxjz.dao.HibernateCommonDao;

public interface HibernateEmployeeDao extends HibernateCommonDao {
	public void ownBusiness();
}

4.4HibernateEmployeeDaoImpl.java

package com.zhxjz.dao.hibernateEmployee.impl;

import org.springframework.stereotype.Repository;

import com.zhxjz.dao.hibernateEmployee.HibernateEmployeeDao;
import com.zhxjz.dao.impl.HibernateCommonDaoImpl;

@Repository("hibernateEmployeeDao")
public class HibernateEmployeeDaoImpl extends HibernateCommonDaoImpl implements
		HibernateEmployeeDao {
	@Override
	public void ownBusiness() {
		
	}
}

4.5HibernateEmployeeService.java

package com.zhxjz.service.hibernateEmployee;

import java.util.List;

import com.zhxjz.model.hibernateEmployee.HibernateEmployee;

public interface HibernateEmployeeService {
	public void add(HibernateEmployee hibernateEmployee);
	public void del(int id);
	public void update(HibernateEmployee updObj);
	public HibernateEmployee queryById(int id);
	public List<HibernateEmployee> queryList(String sql);
}

4.6HibernateEmployeeServiceImpl.java

package com.zhxjz.service.hibernateEmployee.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zhxjz.dao.hibernateEmployee.HibernateEmployeeDao;
import com.zhxjz.model.hibernateEmployee.HibernateEmployee;
import com.zhxjz.service.hibernateEmployee.HibernateEmployeeService;

@Service
@Transactional
public class HibernateEmployeeServiceImpl implements HibernateEmployeeService {

	@Autowired
	private HibernateEmployeeDao hibernateEmployeeDao;
	
	@Override
	public void add(HibernateEmployee hibernateEmployee) {
		hibernateEmployeeDao.add(hibernateEmployee);
	}
	@Override
	public void del(int id) {
		hibernateEmployeeDao.del(HibernateEmployee.class, id);
	}
	@Override
	public void update(HibernateEmployee hibernateEmployee) {
		hibernateEmployeeDao.update(hibernateEmployee);
	}
	@Override
	public HibernateEmployee queryById(int id) {
		return (HibernateEmployee) hibernateEmployeeDao.queryById(
				HibernateEmployee.class, id);
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<HibernateEmployee> queryList(String sql) {
		return hibernateEmployeeDao.queryList(sql);
	}
}

4.7model类--HibernateEmployee.java

package com.zhxjz.model.hibernateEmployee;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "HIBERNATEEMPLOYEE")
public class HibernateEmployee {

	private String uuid;

	@Id
	@Column(name = "EMPLOYEEID")
	private int employeeId;

	private String employeeName;
	
	private boolean isOnjob;
	
	public HibernateEmployee() {
		
	}
	
	public HibernateEmployee(String uuid, int employeeId, String employeeName, boolean isOnjob) {
		this.uuid = uuid;
		this.employeeId = employeeId;
		this.employeeName = employeeName;
		this.isOnjob = isOnjob;
	}
	省略getter和setter。。。
}

4.8HibernateEmployeeController.java

package com.zhxjz.controller.hibernateEmployee;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.zhxjz.framework.model.json.JsonResult;
import com.zhxjz.model.hibernateEmployee.HibernateEmployee;
import com.zhxjz.service.hibernateEmployee.HibernateEmployeeService;

@Controller
@RequestMapping("/hibernateemployee")
public class HibernateEmployeeController {
	@Autowired
	HibernateEmployeeService hibernateEmployeeService;

	@RequestMapping("/add.do")
	public String add(HibernateEmployee hibernateEmployee, ModelMap model) {
		hibernateEmployee.setUuid("uuid1");
		hibernateEmployeeService.add(hibernateEmployee);
		String message = new JsonResult().toJson();
		model.put("message", message);
		return "message";
	}

	@RequestMapping("/del.do")
	public String del(int employeeId, ModelMap model) {
		hibernateEmployeeService.del(employeeId);
		String message = new JsonResult().toJson();
		model.put("message", message);
		return "message";
	}

	@RequestMapping("/update.do")
	public String update(int employeeId, String field, Object value,
			ModelMap model) {
		Map<String, Object> updInfo = new HashMap<String, Object>();
		updInfo.put(field, value);
		HibernateEmployee hibernateEmployee = new HibernateEmployee("uuid2", employeeId, "testemployee2", false);
		hibernateEmployeeService.update(hibernateEmployee);
		String message = new JsonResult().toJson();
		model.put("message", message);
		return "message";
	}
	
	@RequestMapping("/queryOne.do")
	public String queryOne(int employeeId, ModelMap model) {
		HibernateEmployee obj = (HibernateEmployee) hibernateEmployeeService
				.queryById(employeeId);
		String message = new JsonResult(obj).toJson();
		model.put("message", message);
		return "message";
	}

	@RequestMapping("/querylist.do")
	public String querylist(ModelMap model) {
		String sql = "select * from hibernateemployee limit 0,2";
		List<HibernateEmployee> employeeList = hibernateEmployeeService.queryList(sql);
		String message = new JsonResult(employeeList).toJson();
		model.put("message", message);
		return "message";
	}
}

5.推荐博客(Spring4 MVC Hibernate4集成 Annotation)

http://www.cnblogs.com/leiOOlei/p/3780290.html

http://gongm-24.iteye.com/blog/1539110 (这篇创建接口设计比我的全,有空再研究下)

http://blog.csdn.net/shan9liang/article/details/9117233 (帖子不错有水平,springmvc整合hibernate4到位)

6.hqsql查询语言(HQL: Hibernate查询语言)

http://www.cnblogs.com/bobomail/archive/2005/09/20/240352.html

http://itlab.idcquan.com/Java/Hibernate/809957.html

http://itlab.idcquan.com/Java/Hibernate/953976.html (增删改查)


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!