最近发觉 spring-data-jpa 比较好用。
我在springcloud的项目中使用后,也尝试在springmvc中增加 jpa。
一,创建moudle
选择父项目,设定子项目名。
二,创建文件夹
创建文件夹,并且转换文件夹类型
三,创建测试文件
在对应的java目录下,创建包和controller
我的包路径com.kintech.test.controller
Model
package com.kintech.model.domain.test; import lombok.Data; import org.hibernate.annotations.DynamicUpdate; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; /** * @author Tyler * @date 2020/4/20 */ @Data @Entity @Table(name="testtab" ,catalog="kintech_pd" ) @DynamicUpdate public class TestTab { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="id") private Integer id; private String name; }
Dao
@Repository("testtabdao") public interface TestTabDao extends JpaRepository<TestTab,Integer> { }
TestController(测试的话,直接略过service,调用dao。)
package com.kintech.test.controller; import com.kintech.dao.dao.test.TestTabDao; import com.kintech.dao.impl.sys.SysUserDaoImpl; import com.kintech.model.domain.sys.SysUser; import com.kintech.service.service.sys.SysUserService; import com.kintech.web.controller.SuperBaseController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; @Controller @RequestMapping("test") public class TestController{ @Autowired TestTabDao testTabDao; @Autowired SysUserService userService; //JPA : testTabDao @RequestMapping(value = "test.do", method = RequestMethod.GET) public @ResponseBody String test(ModelMap mode){ Integer count=testTabDao.findAll().size(); return count + " size"; } //hibernate : userService @Transactional @RequestMapping(value = "test1.do", method = RequestMethod.GET) public @ResponseBody String test1(){ List<SysUser> list=userService.findList(); Integer count=list.size(); return count + " size"; } }
四,所有配置文件
下面比较多,大家看自己需求选择对应的配置文件
然后我们一个个来看
①,jdbc.properties
注意自己的 mysql-connector-java 版本,
选择 com.mysql.jdbc.Driver 还是 com.mysql.cj.jdbc.Driver
②,applicationContext.xml
注意修改:属性文件,扫描包路径
③,spring-business.xml
注意<!-- JPA实体管理器工厂 -->开始的配置
由于老项目是hibernate4,然后我test模块是 5.xx 版本,因此注意spring-business.xml中是org.springframework.orm.hibernate4
如果你使用org.springframework.orm.hibernate5,会报错:Error creating bean with name 'entityManagerFactory' defined in class path resource.....
(但如果你的老项目也是5.xx版本,那可以用org.springframework.orm.hibernate5)
④,Web-INF中的web.xml添加(这一步,不是必须的)
<filter> <filter-name>hibernateFilter</filter-name> <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>sessionFactoryBeanName</param-name> <param-value>sessionFactory</param-value> </init-param> </filter>
PS:
1 sessionFactory --> packagesToScan 指向 com.kintech.model(这个是hibernate的model)
2 entityManagerFactory --> packagesToScan 指向 com.kintech.model.domain.test(这个是jpa的model)
3 jpa:repositories --> base-package 指向 com.kintech.dao.*(这个是jpa的dao)
我们看一下包
JPA和hibernate的model(test为JPA的,其他都是hiberante的)
JPA和hibernate的dao(dao.test为JPA的,impl都是hiberante的)
配置:
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd" default-lazy-init="true"> <!--配置数据源--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driver}" /> <!--数据库连接驱动--> <property name="jdbcUrl" value="${jdbc.jdbcUrl}" /> <!--数据库地址--> <property name="user" value="${jdbc.user}" /> <!--用户名--> <property name="password" value="${jdbc.password}" /> <!--密码--> <property name="maxPoolSize" value="${jdbc.maxPoolSize}" /> <!--最大连接数--> <property name="minPoolSize" value="${jdbc.miniPoolSize}" /> <!--最小连接数--> <property name="initialPoolSize" value="${jdbc.initialPoolSize}" /> <!--初始化连接池内的数据库连接--> <property name="maxIdleTime" value="${jdbc.maxIdleTime}" /> <!--最大空闲时间--> </bean> <!-- hibernate --> <!--配置session工厂--> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan" value="com.kintech.model" /> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <!--hibernate根据实体自动生成数据库表--> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <!--指定数据库方言--> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <!--在控制台显示执行的数据库操作语句--> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <!--在控制台显示执行的数据哭操作语句(格式)--> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <!-- 查询缓存 --> <prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop> <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop> </props> </property> </bean> <!-- 事物管理器配置 --> <bean id="transactionManager1" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:annotation-driven transaction-manager="transactionManager1" proxy-target-class="true" /> <!-- hibernate --> <!-- JPA --> <!-- JPA实体管理器工厂 --> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" /> <!-- 加入定制化包路径 --> <property name="packagesToScan" value="com.kintech.model.domain.*" /> <property name="jpaProperties"> <props> <prop key="hibernate.current_session_context_class">thread</prop> <prop key="hibernate.hbm2ddl.auto">update</prop><!-- validate/update/create --> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <!-- 建表的命名规则 --> <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop> </props> </property> </bean> <!-- 设置JPA实现厂商的特定属性 --> <bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="databasePlatform" value="${hibernate.dialect}"/> </bean> <!-- Jpa 事务配置 --> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <!-- Spring Data Jpa配置 --> <jpa:repositories base-package="com.kintech.dao.*" transaction-manager-ref="transactionManager" entity-manager-factory-ref="entityManagerFactory"/> <!-- 使用annotation定义事务 --> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> <!-- JPA --> </beans>
④,spring-redis.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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd" default-lazy-init="true" > <!--redis配置 --> <bean name="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig" lazy-init="true"> <property name="maxTotal" value="${redis.maxTotal}"/> <property name="maxIdle" value="${redis.maxIdle}"/> <property name="minIdle" value="${redis.minIdle}"/> <property name="maxWaitMillis" value="${redis.maxWaitMillis}"/> <property name="testOnBorrow" value="${redis.testOnBorrow}"/> <property name="testOnReturn" value="${redis.testOnReturn}"/> <property name="testWhileIdle" value="${redis.testWhileIdle}"/> <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/> <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/> <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/> </bean> <!-- Jedis ConnectionFactory 数据库连接配置--> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="${redis.host}" /> <property name="port" value="${redis.port}" /> <property name="password" value="${redis.password}" /> <property name="database" value="${redis.database}" /> <property name="poolConfig" ref="jedisPoolConfig" /> <property name="timeout" value="${redis.timeOut}" /> </bean> <!-- StringRedisTemplate 序列化方式 --> <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate" p:connection-factory-ref="jedisConnectionFactory" > <!--以String类型的方式 序列化 时间:2020年2月13日17:29:41 作者:陈翔宇 start --> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> </property> <property name="hashKeySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <property name="hashValueSerializer"> <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> </property> <!--以String类型的方式 序列化 时间:2020年2月13日17:29:41 作者:陈翔宇 end --> </bean> <!-- 设置Cookie domain 和 名称 --> <bean id="defaultCookieSerializer" class="com.kintech.web.CookieSerializer"> <property name="domainName" value="${sysHost}"/> <property name="cookieName" value="MYJSESSIONID"/> <!--<property name="domainNamePattern" value="^.+?\.(\w+\.[a-z]+)$"/>--> </bean> <!-- 将session放入redis --> <bean id="redisHttpSessionConfiguration" class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"> <property name="maxInactiveIntervalInSeconds" value="7200" /> <property name="cookieSerializer" ref="defaultCookieSerializer"/> </bean> <!--@Cacheable使用Redis缓存 : spring自己的缓存管理器,这里定义了缓存位置名称 ,即注解中的value --> <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager"> <property name="caches"> <set> <bean class="org.springframework.data.redis.cache.RedisCache"> <constructor-arg name="redisOperations" ref="redisTemplate"></constructor-arg> <constructor-arg name="name" value="menuAllList"></constructor-arg> <constructor-arg name="prefix" value="dbSYS:"></constructor-arg> <constructor-arg name="expiration" value="7200"></constructor-arg> </bean> <bean class="org.springframework.data.redis.cache.RedisCache"> <constructor-arg name="redisOperations" ref="redisTemplate"></constructor-arg> <constructor-arg name="name" value="accesscodeAllList"></constructor-arg> <constructor-arg name="prefix" value="dbSYS:"></constructor-arg> <constructor-arg name="expiration" value="7200"></constructor-arg> </bean> <bean class="org.springframework.data.redis.cache.RedisCache"> <constructor-arg name="redisOperations" ref="redisTemplate"></constructor-arg> <constructor-arg name="name" value="afTypeAllList"></constructor-arg> <constructor-arg name="prefix" value="dbAF:"></constructor-arg> <constructor-arg name="expiration" value="7200"></constructor-arg> </bean> </set> </property> </bean> </beans>
⑤,springmvc-servlet.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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd" default-lazy-init="true" > <!-- 默认的注解映射的支持 --> <mvc:annotation-driven /> <!--静态资源映射 --> <mvc:default-servlet-handler /> <!-- 扫描Controller --> <context:component-scan base-package="com.kintech" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.RestController" /> </context:component-scan> <!-- 引入属性文件 --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:properties/env.properties</value> </list> </property> </bean> <!-- JSP视图文件解析配置 --> <bean id="urlBasedViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> <!-- <property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView" /> --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> <!-- 上传文件拦截,设置最大上传文件大小 10M=10*1024*1024(B)=10485760 bytes --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize"> <value>104857600</value> </property> <property name="maxInMemorySize" value="20480" /> <property name="defaultEncoding" value="UTF-8" /> <property name="resolveLazily" value="true" /> </bean> <!-- 消息转换器 --> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="defaultCharset" value="UTF-8" /> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="com.kintech.common.MyObjectMapper" /> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- mvc Exception handler --> <bean id="handlerExceptionResolver" class="com.kintech.web.AnnotationHandlerMethodExceptionResolver"> <property name="defaultErrorView" value="error/500" /> <!--500错误页面 --> <property name="defaultErrorView403" value="error/403" /> <!--403错误页面 --> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" /> <!-- JSON转换器无需设置mediaType,由外部客户端调用时,手动设置相关mediaType --> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /> </list> </property> </bean> <!-- aop日志 --> <aop:aspectj-autoproxy proxy-target-class="true" /> <bean id="logAopAction" class="com.kintech.web.SysLog.LogAopAction" /> <!-- 配置国际化资源文件路径 --> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename"> <!-- 定义消息资源文件的相对路径 --> <value>languages/lang</value> </property> </bean> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"> <property name="cookieMaxAge" value="604800" /> <property name="defaultLocale" value="${defaultLocale}" /> <property name="cookieName" value="language"></property> </bean> </beans>
⑥,web.xml
没什么太大花头,就是呸呸呸。。。
<?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" version="3.1"> <display-name>test</display-name> <description>test</description> <context-param> <param-name>webAppRootKey</param-name> <param-value>test.root</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j/log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>6000</param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener </listener-class> </listener> <listener> <description>spring监听器</description> <listener-class>org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <listener> <description>防止内存泄露</description> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> <filter> <filter-name>springSessionRepositoryFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSessionRepositoryFilter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>ERROR</dispatcher> </filter-mapping> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>test</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc-servlet.xml</param-value> </init-param> <init-param> <param-name>detectAllHandlerExceptionResolvers</param-name> <param-value>false</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>test</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <session-config> <session-timeout>120</session-timeout> <tracking-mode>COOKIE</tracking-mode> </session-config> </web-app>
⑦,pom文件
主要是JPA注释这一块,注意顺序
<?xml version="1.0"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.kintech</groupId> <artifactId>kintech.parent</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <artifactId>kintech.test</artifactId> <packaging>war</packaging> <name>kintech.test</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>com.kintech</groupId> <artifactId>kintech.web</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <!-- JPA --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.4.12.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>5.4.12.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>5.4.12.Final</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.11.13.RELEASE</version> </dependency> <!-- JPA --> </dependencies> </project>
五,兼容jpa和hibernate的测试
hibernate: