SpringMVC+JPA+Mysql框架搭建

eclipse中新建maven项目,搭建springmvc+jpa+mysql环境步骤:使用druid数据连接池,开启ehcache二级缓存

步骤一:.先搭建Springmvc环境

   /WEB-INF/目录中,有springmvc-servlet.xml,web.xml文件

  a、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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	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">
		<display-name>Archetype Created Web Application</display-name>

		<!-- Spring Servlet,由于把bean全部交给了SpringJap,所以Spring-mvc里面现在为空 -->
		<servlet>
			<servlet-name>springmvc</servlet-name>
			<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
			<init-param>
				<param-name>contextConfigLocation</param-name>
				<param-value>/WEB-INF/springmvc-servlet.xml</param-value>
			</init-param>
			<load-on-startup>1</load-on-startup>
		</servlet>
		<servlet-mapping>
			<servlet-name>springmvc</servlet-name>
			<url-pattern>/</url-pattern>
		</servlet-mapping>
	</web-app>
 b、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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context" 
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc 
	http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    
    <description>Spring MVC Configuration</description>
    <context:component-scan base-package="com.controller" />
    <mvc:annotation-driven/>
    <!-- 配置前后缀 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/" />
		<property name="suffix" value=".jsp" />
	</bean>
	
</beans>

步骤二:

     加入spring配置,并整合Jpa,将jpa交给spring管理,使用druid连接池

     1.web.xml中加入以下代码

        配置druid过滤器,配置spring全局监听

<!-- 同时加载多个spring配置文件可用 -->
		<context-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
            classpath*:/applicationContext.xml
        </param-value>
		</context-param>

		<!-- spring全局监听 -->
		<listener>
			<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
		</listener>

		<!-- 下面为Druid默认配置,过滤掉多余的url地址 -->
		<filter>
			<filter-name>DruidWebStatFilter</filter-name>
			<filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
			<init-param>
				<param-name>exclusions</param-name>
				<param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
			</init-param>
			<init-param>
				<param-name>principalSessionName</param-name>
				<param-value>_dest_login_</param-value>
			</init-param>
		</filter>
		<filter-mapping>
			<filter-name>DruidWebStatFilter</filter-name>
			<url-pattern>/*</url-pattern>
		</filter-mapping>

		<!-- StatViewServlet是一个标准的Servlet -->
		<servlet>
			<servlet-name>DruidStatView</servlet-name>
			<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
		</servlet>
		<servlet-mapping>
			<servlet-name>DruidStatView</servlet-name>
			<url-pattern>/druid/*</url-pattern>
		</servlet-mapping>
  2.在/src/main/resources中添加applicationContext.xml配置文件,用来管理JPA,bean等

      

<?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:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:task="http://www.springframework.org/schema/task"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
	default-lazy-init="true">

	<description>SpringJpa配置</description>
		<!-- 启动spring的注解功能 -->
	<context:component-scan base-package="com"><!-- base-package 如果多个,用“,”分隔 -->
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>
	<!-- 加载数据库连接配置文件 -->
	<bean id="propertyPlaceholderConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:db.properties</value>
			</list>
		</property>
	</bean>	
	
	<!-- Hibernate对Jpa的实现 即配置JPA的厂商类-->
<!-- 	<bean id="hibernateJpaVendorAdapter"
		class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" /> -->
			<bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
	    <property name="generateDdl" value="${jpa.generateDdl}"/>
	    <property name="database" value="${jpa.database}"/>
	    <property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
	    <property name="showSql" value="${jpa.showSql}"/>
	</bean>
	
	<!-- 配置  Jpa 事务管理器 -->
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
            <tx:method name="get*" propagation="REQUIRED" read-only="true"/>
			<tx:method name="save*" propagation="REQUIRED" read-only="true"/>
			<tx:method name="insert*" propagation="REQUIRED" read-only="true"/>
			<tx:method name="add*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="find*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="list*" propagation="REQUIRED" read-only="true"/>
			<tx:method name="update*" propagation="REQUIRED" read-only="true"/>
			<tx:method name="delete*" propagation="REQUIRED" read-only="true"/>
			<tx:method name="remove*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
		</tx:attributes>
	</tx:advice>
		<!-- 缓存配置 -->
	<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
		<property name="configLocation" value="classpath:${ehcache.configFile}" />
	</bean>
	
	<!-- 配置entityManagerFactory -->
	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<!-- 指定数据源 -->
		<property name="dataSource" ref="dataSource" />
		<!-- 指定Jpa持久化实现厂商类,这里以Hibernate为例 -->
		<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />
		<!-- 指定Entity实体类包路径 -->
		<property name="packagesToScan" value="com.entity"/>
		<!-- 指定JPA属性;如Hibernate中指定是否显示SQL的是否显示、方言等 -->
		 <property name="jpaDialect">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
        </property>
		<property name="jpaProperties">
			<props>
				<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
				<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
				<prop key="net.sf.ehcache.configurationResourceName">${hibernate.ehcache.configFile}</prop>
				<prop key="hibernate.cache.use_second_level_cache">true</prop>
				<prop key="hibernate.cache.use_query_cache">true</prop>
				<prop key="hibernate.search.default.directory_provider">filesystem</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
			</props>
		</property>
	</bean>
	
	<!-- 数据源配置,使用应用内的druid数据库连接池 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> 
		    <!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->
		    <property name="driverClassName" value="${jdbc.driver}" />
		    
			<!-- 基本属性 url、user、password -->
			<property name="url" value="${jdbc.url}" />
			<property name="username" value="${jdbc.user}" />
			<property name="password" value="${jdbc.password}" />
			
			<!-- 配置初始化大小、最小、最大 -->
			<property name="initialSize" value="${jdbc.pool.minIdle}" />
			<property name="minIdle" value="${jdbc.pool.minIdle}" />
			<property name="maxActive" value="${jdbc.pool.maxActive}" />
			
			<!-- 配置获取连接等待超时的时间 -->
			<property name="maxWait" value="${jdbc.pool.maxActive}" />
			
			<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
			<property name="timeBetweenEvictionRunsMillis" value="${jdbc.pool.timeBetweenEvictionRunsMillis}" />
			
			<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
			<property name="minEvictableIdleTimeMillis" value="${jdbc.pool.minEvictableIdleTimeMillis}" />
			
			<property name="validationQuery" value="SELECT 'x'" />
			<property name="testWhileIdle" value="${jdbc.pool.testWhileIdle}" />
			<property name="testOnBorrow" value="${jdbc.pool.testOnBorrow}" />
			<property name="testOnReturn" value="${jdbc.pool.testOnReturn}" />
			
			<!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用)
			<property name="poolPreparedStatements" value="true" />
			<property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> -->
			
			<!-- 配置监控统计拦截的filters -->
		    <property name="filters" value="${jdbc.pool.filters}" /> 
		</bean>
	
	
	<!-- 开启扫描 -->
	<!-- 如果spring用了jpa,并且类型为LocalContainerEntityManagerFactoryBean,则组件注册在此配置文件出现即可,其余配置文件可忽略 
		使用component来替代annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入\ 
	<context:component-scan base-package="com.spring.jpa" />-->
		<!-- 重要配置:启用扫描并自动创建代理的功能 -->
	<jpa:repositories base-package="com.spring.jpa"
		transaction-manager-ref="transactionManager"
		entity-manager-factory-ref="entityManagerFactory" />
		
	<!-- 开启注解事务 -->
	<tx:annotation-driven transaction-manager="transactionManager"
		proxy-target-class="true" />
	<aop:aspectj-autoproxy />

</beans>
 3. 在/src/main/resources中添加配置文件db.properties

     

#mysql database setting
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.1.104:3306/yyw?useUnicode=true&characterEncoding=utf-8
jdbc.user=guest
jdbc.password=123456

 # jpa settings
jpa.generateDdl=false
jpa.database=MYSQL
jpa.showSql=true
 
 #cache settings
hibernate.ehcache.configFile=cache/ehcache-hibernate-local.xml
#hibernate.ehcache.configFile=cache/ehcache-hibernate-rmi.xml
ehcache.configFile=cache/ehcache-local.xml
#ehcache.configFile=cache/ehcache-rmi.xml
hibernate.show_sql=true
 
jdbc.pool.minIdle=10
jdbc.pool.maxActive=20
jdbc.pool.maxWait=60000
jdbc.pool.minIdle=10

#maxIdle=15
 
jdbc.pool.timeBetweenEvictionRunsMillis=60000
jdbc.pool.minEvictableIdleTimeMillis=300000
 
jdbc.pool.testWhileIdle=true
jdbc.pool.testOnBorrow=false
jdbc.pool.testOnReturn=false
jdbc.pool.filters=stat
#poolPreparedStatements=true
db.maxOpenPreparedStatements=20

#\u5BF9\u4E8E\u5EFA\u7ACB\u8FDE\u63A5\u8FC7\u957F\u7684\u8FDE\u63A5\u5F3A\u5236\u5173\u95ED
db.removeAbandoned=true
#\u5982\u679C\u8FDE\u63A5\u5EFA\u7ACB\u65F6\u95F4\u8D85\u8FC7\u4E8630\u5206\u949F\uFF0C\u5219\u5F3A\u5236\u5C06\u5176\u5173\u95ED
db.removeAbandonedTimeout=1800
#\u5C06\u5F53\u524D\u5173\u95ED\u52A8\u4F5C\u8BB0\u5F55\u5230\u65E5\u5FD7
db.logAbandoned=true
4.ehcache配置

  在/src/main/resources新建cache目录,并将ehcache-hibernate-local.xml,ehcache-hibernate-rmi.xml,ehcache-local.xml,ehcache-rmi.xml四个配置文件放入其中


步骤三:相应的写spring要扫描的包以及对应的entity,service,dao即可


测试项目下载路径http://pan.baidu.com/s/1eQ1XSHk













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值