Hibernate4.3+Spring4.2 整合问题

2017-01-05 11:11:07来源:oschina作者:Mr_K人点击

其实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"?>
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">










其次我们需要一个数据访问的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 msg = new HashMap();
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"?>
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">
Hibernate-Spring01

login.jsp


dispatcherServlet
org.springframework.web.servlet.DispatcherServlet

contextConfigLocation
/WEB-INF/applicationContext.xml

1


dispatcherServlet
*.do


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


<?xml version="1.0" encoding="UTF-8"?>
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">
class="org.springframework.jdbc.datasource.DriverManagerDataSource">

com.mysql.jdbc.Driver


jdbc:mysql://localhost:3306/student?characterEncoding=utf8


sa


123



class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">






org.hibernate.dialect.MySQLDialect

true

true





com/hh/bean/Student.hbm.xml














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


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>




Insert title here



Name:

Age:

Sex:男 





到这里就基本完成了。


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


添加失败!
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中加入如下:











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


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

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台