其實Spring+Hibernate的整合很是簡單,只須要配置一個xml文件就能夠將spring+hibernate整合起來。下面就覺得一個添加用戶的例子來整合這個:html
首先實體必不可少的:java
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文件(固然若是使用註解這個文件就不須要了):mysql
<?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接口:web
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; } }
當這寫寫後之後,咱們創建一個訪問控制器接口:spring
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:sql
<?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就能夠了··express
<%@ 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="男" />男 <input type="radio" name="sex" value="女" />女<br /> <input type="submit" value="GO!"> </form> </body> </html>
到這裏就基本完成了。apache
可是我在測試的時候,查詢沒的問題。在增長的時候,報錯以下:tomcat
添加失敗! 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