文档章节

Hibernate4.3+Spring4.2 整合问题

Mr_K
 Mr_K
发布于 2016/07/12 00:21
字数 1347
阅读 180
收藏 4

其实Spring+Hibernate的整合非常简单,只需要配置一个xml文件就可以将spring+hibernate整合起来。下面就以为一个添加用户的例子来整合这个:

首先实体必不可少的:

package com.hh.bean;

import java.io.Serializable;

public class Student implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private int id;
	private String name;
	private String sex;
	private int age;
	private int cardid;

	public Student() {
	}

	public int getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public String getSex() {
		return sex;
	}

	public int getAge() {
		return age;
	}

	public int getCardid() {
		return cardid;
	}

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

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

	public void setSex(String sex) {
		this.sex = sex;
	}

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

	public void setCardid(int cardid) {
		this.cardid = cardid;
	}

	
}

然后是实体对应的hbm文件(当然如果使用注解这个文件就不需要了):

<?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>
 <class name="com.hh.bean.Student" table="student">
     <id name="id" column="id" type="int">
         <generator class="native" />
     </id>
     <property name="name" column="name" type="string" />
     <property name="sex" column="sex" type="string" />
     <property name="age" column="age" type="int" />
     <property name="cardid" column="cardid" type="int" />
 </class>
</hibernate-mapping>

 

其次我们需要一个数据访问的DAO接口:

package com.hh.dao.impl;

import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import com.hh.bean.Student;
import com.hh.dao.StudentDao;

public class StudentDaoImpl extends HibernateDaoSupport implements StudentDao {

	public StudentDaoImpl() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public boolean addStudent(Student student) {
		try {
			this.getHibernateTemplate().save(student);
			System.out.println("保存Student信息");
			return true;	
		} catch (Exception e) {
			System.out.println("添加失败!");
			e.printStackTrace();
		}
		return false;
		
	}

}

当这写写后以后,我们建立一个访问控制器接口:

package com.hh.controller;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.hh.bean.Student;
import com.hh.dao.StudentDao;

public class StudentController extends AbstractController {

	private StudentDao studentDao;

	public StudentDao getStudentDao() {
		return studentDao;
	}

	public void setStudentDao(StudentDao studentDao) {
		this.studentDao = studentDao;
	}

	public StudentController() {
		// TODO Auto-generated constructor stub
	}

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		request.setCharacterEncoding("utf-8");

		String name = request.getParameter("name");
		int age = Integer.valueOf(request.getParameter("age"));
		String sex = request.getParameter("sex");
		System.out.println("name:" + name + ",age:" + age + ",sex:" + sex);
		Student student = new Student();
		student.setAge(age);
		student.setCardid(1);
		student.setName(name);
		student.setSex(sex);
		Map<String, String> msg = new HashMap<String, String>();
		if (this.studentDao.addStudent(student)) {
			System.out.println("name:" + name);
			msg.put("name", name);
			return new ModelAndView("welcome.jsp", msg);
		}
		msg.put("errorMsg", "添加失败!");
		return new ModelAndView("error.jsp", msg);
	}

}

现在就是配置文件了,首先在web.xml里加上srping的DispatcherServlet:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	id="WebApp_ID" version="3.1">
	<display-name>Hibernate-Spring01</display-name>
	<welcome-file-list>
		<welcome-file>login.jsp</welcome-file>
	</welcome-file-list>

	<servlet>
		<servlet-name>dispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/applicationContext.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcherServlet</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
</web-app>

现在就是需要配置spring和hibernate的整合xml文件:这个文件名称就是在web.xml里面配置的contextConfigLocation的:

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">


	<!-- 数据源配置 -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName">
			<value>com.mysql.jdbc.Driver</value>
		</property>
		<property name="url">
			<value>jdbc:mysql://localhost:3306/student?characterEncoding=utf8</value>
		</property>
		<property name="username">
			<value>sa</value>
		</property>
		<property name="password">
			<value>123</value>
		</property>
	</bean>

	<!-- 配置hibernate的sessionFactory -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<property name="hibernateProperties">
			<props>
				<!-- 数据库官方语言 -->
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<!-- 是否输出sql -->
				<prop key="hibernate.show_sql">true</prop>
				<!-- 是否格式化sql -->
				<prop key="hibernate.format_sql">true</prop>
			</props>
		</property>
		<!-- Hibernate实体映射文件 -->
		<property name="mappingResources">
			<list>
				<value>com/hh/bean/Student.hbm.xml</value>
			</list>
		</property>
	</bean>
    
	<!-- 定义DAO -->
	<bean id="studentDao" class="com.hh.dao.impl.StudentDaoImpl">
		<property name="sessionFactory">
			<ref bean="sessionFactory" />
		</property>

	</bean>

	<!-- 映射的do -->
	<bean name="/addStudent.do" class="com.hh.controller.StudentController">
		<property name="studentDao">
			<ref bean="studentDao" />
		</property>
	</bean>

</beans>

 

这样差不多就配置好了,我们只需要添加一个jsp然后访问 /addStudent.do就可以了··

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="addStudent.do" method="post">
	Name:<input type="text" name="name"/><br />
	Age:<input type="text"  name="age"/><br />
	Sex:<input type="radio" name="sex" value="男" />男&nbsp;<input type="radio" name="sex" value="女" />女<br />
	<input type="submit" value="GO!">
</form>
</body>
</html>

到这里就基本完成了。

但是我在测试的时候,查询没的问题。在增加的时候,报错如下:

添加失败!
org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
	at org.springframework.orm.hibernate4.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1128)
	at org.springframework.orm.hibernate4.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:621)
	at org.springframework.orm.hibernate4.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:618)
	at org.springframework.orm.hibernate4.HibernateTemplate.doExecute(HibernateTemplate.java:341)
	at org.springframework.orm.hibernate4.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:309)
	at org.springframework.orm.hibernate4.HibernateTemplate.save(HibernateTemplate.java:618)
	at com.hh.dao.impl.StudentDaoImpl.addStudent(StudentDaoImpl.java:17)
	at com.hh.controller.StudentController.handleRequestInternal(StudentController.java:47)
	at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:147)
	at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:50)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
	at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:871)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
	at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Unknown Source)
Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.

只读模式下(FlushMode.NEVER/MANUAL)写操作不被允许:把你的Session改成FlushMode.COMMIT/AUTO或者清除事务定义中的readOnly标记。

 

我的处理方式是: 配置Spring的事务处理 

在applicationContext中加入如下:

<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED" />
		</tx:attributes>
	</tx:advice>

	<aop:config>
		<aop:pointcut id="interceptorPointCuts" expression="execution(* com.hh.dao.*.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" />
	</aop:config>

关于事务不清楚的话,那就把spring重学一遍吧~o(∩_∩)o 哈哈~

别说,我看过spring第一遍之后,只明白了ioc,aop还晕晕呼呼~好在有官网的文档~但是英文的看着头疼~~~0.0

© 著作权归作者所有

Mr_K

Mr_K

粉丝 34
博文 15
码字总数 7517
作品 0
成都
高级程序员
私信 提问
加载中

评论(2)

Mr_K
Mr_K

引用来自“小兵成长记”的评论

效率极低的框架
但是这个三大框架再怎么也应该去了解下吧~
魔法王者安琪拉
魔法王者安琪拉
效率极低的框架
vSphere 5.5 VM整合磁盘失败之—文件被锁定无法访问

vSphere 5.5 VM整合磁盘失败之—文件被锁定无法访问 环境:vSPhere 5.5u3,虚机使用EMC的networker备份 问题现象:在vc上发现,晚上经过networker的备份之后,虚机提示需要整合磁盘 解决前相...

Makka_Pakka
2018/07/06
0
0
cmlbeliever/SpringBootLearning

SpringBoot Learning 此项目主要作为SpringBoot学习,和根据实际项目对SpringBoot进行配置改造主要使用框架:SpringBoot(Spring,SpringMVC),MyBatis,Ehcache,Rabbitmq,JavaMail。项目持续维护...

cmlbeliever
2016/11/03
0
0
springboot从入门到精通教程分享, 深度掌握Springboot实践技术教程

深度掌握Springboot实践技术教程,共22个课时,需要的可回复邮箱。 课程简介 day1 01springboot简介-曾经开发中的问题 02springboot解决的问题-优势以及弊端 03springboot环境准备 04spring...

小小倾听
2018/12/06
0
0
Tipask 2.5 正式版本发布,PHP 问答系统

Tipask 2.5 正式版本发布,更新内如如下: 1、加入关注、问答动态模块,用户可关注用户以及问题 2、加入推荐问题模块 3、追问模块调整 4、ucenter整合重新调整,由fopen方式改为数据库连接方...

宋登峰
2014/05/12
3.2K
12
Tipask 2.5 Beta 版本发布

tipask 2.5 beta 版本主要更新内容如下: 1、搜索模块去掉了mysql的fulltext方式,改为整合xunsearch 2、模板整体更新 3、问题加入评论模块和赞同 4、标签模块重新设计 5、添加活跃用户模块 ...

宋登峰
2014/02/21
817
2

没有更多内容

加载失败,请刷新页面

加载更多

利用mybatis generator生成实体类、Mapper接口以及对应的XML文件

项目中通常会遇到数据的持久化,如果是采用mybatis的orm,就会涉及到生成xml的问题,刚好mybatis官网提供了这么个插件MyBatis Generator,效果简直是棒呆。 1. 首先需要在build.gradle文件中...

啊哈关关
今天
2
0
SpringSocial相关的知识点

使用SprigSocial开发第三方登录 核心类 ServiceProvider(AbstractOauth2ServiceProvider):主要负责实现server提供商(例如QQ,微信等共有的东西),默认实现类是AbstractOauth2ServiceProvider...

chendom
今天
2
0
Java并发之AQS详解

一、概述   谈到并发,不得不谈ReentrantLock;而谈到ReentrantLock,不得不谈AbstractQueuedSynchronizer(AQS)!   类如其名,抽象的队列式的同步器,AQS定义了一套多线程访问共享资源...

群星纪元
昨天
2
0
Fabric-sdk-java最新教程

Fabric Java SDK是Fabric区块链官方提供的用于Java应用开发的SDK,全称为Fabric-sdk-java,网上可用资料不多,本文列出了精心整理的针对Fabric Java SDK的最新精选教程。 如果希望快速掌握F...

汇智网教程
昨天
3
0
react 子组件监听props 变化

componentWillReceiveProps //已经被废弃 getDerivedStateFromProps// 推荐使用//如果条件不存在必须要返回null static getDerivedStateFromProps(props, current_stat...

一箭落旄头
昨天
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部