spring,springMVC,Hibernate,RESTfull,no transaction is in progress

来源:互联网 发布:数码暴龙网络侦探骇客 编辑:程序博客网 时间:2024/05/23 02:02

最近搭建了一个基于spring+springwebMVC+hibernate的基础架构,基于rest的后端javaAPI,分享一下过程,附源码。

我参考了官方给出的文档https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html

最开始的时候因为不太了解pring的context和springMVC的context之间到底是什么关系,凭感觉配置了一波,然后数据访问层的事物处理就出了问题,要不就是什么flusmodle什么的是read-Only,要不 就是no transaction is in progress的异常,哎,头疼,后来才发现是spring和springMVC整合的时候没有处理好两个context之间的系,导致老是数据库被初始化两次,有的带注解的bean也是被初始话了两次,后来看到了这个图,好像是明白了一些东西。



以下就是正确的配置步骤了。

jdk1.8

maven
servlet3.1
tomcat9
spring5
springMVC5

hibernate5

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.gingkocash.gccDemo</groupId><artifactId>gccDemo</artifactId><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><properties><spring.version>5.0.0.RELEASE</spring.version><hibernate.version>5.2.12.Final</hibernate.version></properties><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.1</version><configuration><source>1.8</source><target>1.8</target></configuration></plugin></plugins></build><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>${spring.version}</version></dependency><!-- https://mvnrepository.com/artifact/org.springframework/spring-orm --><dependency><groupId>org.springframework</groupId><artifactId>spring-orm</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-core</artifactId><version>${hibernate.version}</version></dependency><!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator --><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-validator</artifactId><version>5.2.1.Final</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency><!-- https://mvnrepository.com/artifact/com.mchange/c3p0 --><dependency><groupId>com.mchange</groupId><artifactId>c3p0</artifactId><version>0.9.5.2</version></dependency><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.34</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.8</version></dependency><!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.9.1</version></dependency><!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.1</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.9.1</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.6</version></dependency></dependencies></project>
web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"id="WebApp_ID" version="3.0"><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/classes/root-context.xml</param-value></context-param><servlet><servlet-name>app</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/classes/app-context.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>app</servlet-name><url-pattern>/v1/*</url-pattern></servlet-mapping></web-app>

spring配置文件

db

<?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:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="                http://www.springframework.org/schema/context                http://www.springframework.org/schema/context/spring-context.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                http://www.springframework.org/schema/beans                http://www.springframework.org/schema/beans/spring-beans.xsd"><context:property-placeholder location="classpath:hibernate.properties" /><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${hibernate.connection.driver_class}" /><property name="jdbcUrl" value="${hibernate.connection.url}" /><property name="user" value="${hibernate.connection.username}" /><property name="password" value="${hibernate.connection.password}" /></bean><bean id="sessionFactory"class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"scope="singleton"><property name="dataSource" ref="dataSource" /><property name="hibernateProperties"><props><prop key="hibernate.c3p0.max_size">${hibernate.c3p0.max_size}</prop><prop key="hibernate.c3p0.min_size">${hibernate.c3p0.min_size}</prop><prop key="hibernate.c3p0.timeout">${hibernate.c3p0.timeout}</prop><prop key="hibernate.c3p0.max_statements">${hibernate.c3p0.max_statements}</prop><prop key="hibernate.c3p0.idle_test_period">${hibernate.c3p0.idle_test_period}</prop><prop key="hibernate.c3p0.acquire_increment">${hibernate.c3p0.acquire_increment}</prop><prop key="hibernate.c3p0.validate">${hibernate.c3p0.validate}</prop><prop key="hibernate.show_sql">${hibernate.show_sql}</prop><prop key="hibernate.format_sql">${hibernate.format_sql}</prop><prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop></props></property><property name="packagesToScan"><list><value>com.gingkocash.gcc</value></list></property></bean><bean id = "hibernateTemplate" class = "org.springframework.orm.hibernate5.HibernateTemplate"><property name="sessionFactory" ref="sessionFactory" /></bean><bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" /><bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager" scope="singleton"><property name="sessionFactory" ref="sessionFactory" /></bean><tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="save*" propagation="REQUIRED" /><tx:method name="update*" propagation="REQUIRED" /><tx:method name="del*" propagation="REQUIRED" /><tx:method name="*" propagation="NOT_SUPPORTED" read-only="true" /></tx:attributes></tx:advice><aop:config><aop:pointcut id="serviceOperation" expression="(execution(* com.gingkocash.gcc.base.dao.*.*(..)))" /><aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" /></aop:config></beans>

root-context.xml

<?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:mvc="http://www.springframework.org/schema/mvc"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.xsd                http://www.springframework.org/schema/mvc                http://www.springframework.org/schema/mvc/spring-mvc.xsd">        <context:component-scan base-package="com.gingkocash.gcc">            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>        </context:component-scan>        <import resource="root-db.xml"/> </beans>

app-context.xml

<?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:mvc="http://www.springframework.org/schema/mvc"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.xsd                http://www.springframework.org/schema/mvc                http://www.springframework.org/schema/mvc/spring-mvc.xsd"><context:component-scan base-package="com.gingkocash.gcc.*.resource"></context:component-scan><mvc:annotation-driven><mvc:message-converters><bean class="org.springframework.http.converter.StringHttpMessageConverter" /><bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /></mvc:message-converters></mvc:annotation-driven></beans>
因为该工程是基于rest风格的api,所以这里就不用配置视图解析器什么了,况且我也没看那部分的文档。

baseDao.java

package com.gingkocash.gcc.base.dao;import java.lang.reflect.ParameterizedType;import java.util.List;import javax.annotation.Resource;import org.apache.commons.lang3.StringUtils;import org.hibernate.SessionFactory;import org.springframework.orm.hibernate5.support.HibernateDaoSupport;public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T>{private Class<T> entityClass;@Resource      public void setSessionFacotry(SessionFactory sessionFacotry) {          super.setSessionFactory(sessionFacotry);      } @SuppressWarnings("unchecked")public BaseDaoImpl(){entityClass = (Class<T>) ((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];}@Overridepublic T find(Long id) {return this.getHibernateTemplate().get(entityClass, id);}@Overridepublic void save(T entity) {this.getHibernateTemplate().save(entity);}@Overridepublic void delete(T entity) {this.getHibernateTemplate().delete(entity);}@Overridepublic void update(T entity) {this.getHibernateTemplate().update(entity);}@SuppressWarnings("unchecked")@Overridepublic List<T> find(String whereStr) {String hqlStr = "from "+entityClass.getSimpleName();hqlStr += StringUtils.isBlank(whereStr)?"":whereStr;return (List<T>) this.getHibernateTemplate().find(hqlStr);}}
UserServiceImpl.java

package com.gingkocash.gcc.Tuser.service;import javax.validation.Valid;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.gingkocash.gcc.Tuser.dao.Tuser;import com.gingkocash.gcc.Tuser.dao.UserDao;@Servicepublic class UserServiceImpl implements UserService{@AutowiredUserDao userDao;@Overridepublic Tuser getUser(Long id) {return userDao.find(id);}@Overridepublic void add(@Valid Tuser tuser) {userDao.save(tuser);}@Overridepublic void delete(Long id) {Tuser find = userDao.find(id);if(find != null) {userDao.delete(find);}}@Overridepublic void update(Tuser tuser) {userDao.update(tuser);}}
controller

package com.gingkocash.gcc.Tuser.resource;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import com.gingkocash.gcc.Tuser.dao.Tuser;import com.gingkocash.gcc.Tuser.service.UserService;import com.gingkocash.gcc.base.ResponseMsg;import com.gingkocash.gcc.base.Responser;@RestController@RequestMapping("/user")public class UserResource {@AutowiredUserService userService;@GetMapping("/{id}")public ResponseMsg getUser(@PathVariable Long id) {return Responser.success(userService.getUser(id));}@PostMapping("/addUser")public ResponseMsg add(@RequestBody Tuser tuser) {try {userService.add(tuser);}catch (Exception e) {e.getMessage();return Responser.failed(e.getMessage());}return Responser.success();}@DeleteMapping("/deleteUser/{id}")public ResponseMsg delete(@PathVariable Long id) {userService.delete(id);return Responser.success();}@PutMapping("/updateUser")public ResponseMsg update(@RequestBody Tuser tuser) {return Responser.success();}}
运行结果:get方式


delete方式:


最后留个源码吧。只有源码,大概10来KB左右,需要的话自己编译吧。

点我下载源代码

http://download.csdn.net/download/u012516603/10041666





阅读全文
0 0
原创粉丝点击