天天看點

SpringMVC +Hibernate JPA+Spring-data-jpa

公司用SpringMVC +Hibernate JPA+Spring-data-jpa 開發。之前沒有用過Spring-data-jpa 就想簡單用下。
          
           
applicationContext.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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd"
	default-lazy-init="true">

	<description>Spring公共配置 </description>
	<!-- 開啟AOP監聽,隻對目前配置檔案有效 -->
	<aop:config proxy-target-class="true" />

	<!-- 使用annotation 自動注冊bean, 并保證@Required、@Autowired的屬性被注入 <context:component-scan 
		base-package="com.csair"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> 
		</context:component-scan> -->

	<context:component-scan base-package="com.csair">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
		<context:exclude-filter type="annotation"
			expression="org.springframework.web.bind.annotation.ControllerAdvice" />
	</context:component-scan>

	<!-- 資料源配置, 使用DBCP資料庫連接配接池 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<!-- Connection Info -->
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />

		<!-- Connection Pooling Info -->
		<property name="maxActive" value="${dbcp.maxActive}" />
		<property name="maxIdle" value="${dbcp.maxIdle}" />
		<property name="defaultAutoCommit" value="false" />
		<!-- 連接配接Idle一個小時後逾時 -->
		<property name="timeBetweenEvictionRunsMillis" value="3600000" />
		<property name="minEvictableIdleTimeMillis" value="3600000" />
	</bean>



	<!-- 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.csair.entity" /><!--待掃描的實體類包,不再需要persistence.xml了 -->
		<property name="jpaProperties">
			<props>
				<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
			</props>
		</property>
	</bean>

	<!--指定實作JPA的擴充卡 -->
	<bean id="hibernateJpaVendorAdapter"
		class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
		<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
	</bean>

	<!-- Jpa 事務配置 -->
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>

	<!-- Spring Data Jpa 配置 Spring -->
	<!-- 初始化容器時将會掃描 base-package 指定的包目錄及其子目錄,為繼承 Repository 或其子接口的接口建立代理對象,并将代理對象注冊為 
		Spring Bean -->
	<!-- base-package 掃描的包 -->
	<!-- repository-impl-postfix 倉庫自定義實作類的字尾。自動掃描該名稱帶有該字尾的類,并添加到接口的實作 -->
	<!-- factory-class 倉庫接口的實作工廠 -->
	<jpa:repositories base-package="com.csair.repository"
		entity-manager-factory-ref="entityManagerFactory"
		transaction-manager-ref="transactionManager">
	</jpa:repositories>

	<!-- 使用annotation定義事務 -->
	<tx:annotation-driven transaction-manager="transactionManager"
		proxy-target-class="true" />
	<!-- JSR303 Validator定義 -->
	<bean id="validator"
		class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

	<!-- production環境 -->
	<beans profile="production">
		<context:property-placeholder
			ignore-unresolvable="true" location="classpath*:/db.properties" />
	</beans>
	<!-- local development環境 -->
	<beans profile="development">
		<context:property-placeholder
			ignore-resource-not-found="true"
			location="classpath*:/db.properties,
          			  classpath*:/db_dev.properties" />
	</beans>
	<!-- unit test環境 -->
	<beans profile="test">
		<context:property-placeholder
			ignore-resource-not-found="true" location="classpath*:/db_test.properties" />

	</beans>
</beans>
           

spring-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"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

     
     	<!-- 開啟AOP監聽,隻對目前配置檔案有效 -->
	<aop:config proxy-target-class="true" />

	<!-- 基于@AspectJ切面的驅動器 -->
	<aop:aspectj-autoproxy />
     
     
     <!-- 激活@Controller模式 -->
     <mvc:annotation-driven />
	<context:component-scan base-package="com.csair.controller" 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.ControllerAdvice" />
	</context:component-scan>
     
     
     <!-- 對包中的所有類進行掃描,以完成Bean建立和自動依賴注入的功能 需要更改 -->
     <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
 
     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
         <property name="prefix">
             <value>/WEB-INF/jsp/</value>
         </property>
         <property name="suffix">
             <value>.jsp</value>
         </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://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" metadata-complete="true" version="3.0">
  <display-name>Archetype Created Web Application</display-name>
  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath*:/log4j.xml</param-value>
  </context-param>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:/applicationContext*.xml</param-value>
  </context-param>
  
  <!-- 設定Spring Context的預設Profile -->
  <context-param>
	<param-name>spring.profiles.default</param-name>
	<param-value>development</param-value>
  </context-param>
  
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- 字元集編碼 -->
	<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>
	
  <!-- 配置spring mvc -->
  <servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
    	<param-name>contextConfigLocation</param-name>
    	<param-value>classpath*:/spring-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>/index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
           

實體User

package com.csair.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="i_user")
public class User {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Integer id;
	private String username;
	private String password;
	
	@Id
	@GeneratedValue(generator="system-uuid")
	@GenericGenerator(name="system-uuid",strategy="uuid")
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	
	@Column(name="username")
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	
	@Column(name="password")
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}
           

UserRepository 類如下:

package com.csair.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.csair.entity.User;

public interface UserRepository extends JpaRepository<User, Integer>{
	
}
           

UserService 接口

package com.csair.service;

import com.csair.entity.User;

public interface UserService {
    public User getUser(int id);
}
           

接口實作類

package com.csair.service.Impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.csair.entity.User;
import com.csair.repository.UserRepository;
import com.csair.service.UserService;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
	UserRepository repository;
	public UserRepository getRepository() {
		return repository;
	}
	@Override
	public User getUser(int id) {
		// TODO Auto-generated method stub
		return repository.findOne(id);
	}

}
           

Controller 類如下:

package com.csair.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.csair.entity.User;
import com.csair.service.UserService;

@Controller
@RequestMapping(value="/user")
public class UserController {
   @Autowired
   private UserService userSerivce;
   @RequestMapping(value="/welcome")
   public ModelAndView getUser(ModelAndView modelView)
   {
	   User user = userSerivce.getUser(1);
	    return new ModelAndView("welcome","user",user);
   }
}
           
</pre><pre>
           
關于jsp 頁面就不貼了 
以上基本就是 SpringMVC +Hibernate JPA+Spring-data-jpa 開發環境內建。
但是 問題來了:
java.lang.ClassNotFoundException: org.springframework.data.mapping.IdentifierAccessor
這個錯網上很難找到答案,多數是說程式或者配置有問題。這個我自己也糾結了很久。不過最終還是解決了。
這個問題主要是
spring-data-commons.jar
spring-data-jpa.jar 版本依賴問題。
一般很難發現這個問題,因為版本就算依賴有問題也編譯時代碼不會報錯,隻有在釋出的時候會報錯。
 我遇到這個問題是因為我知道要以上兩個包就去spring官網去下載下傳 ,下載下傳的時候沒有考慮到版本依賴問題,後來程式跑不起來,總以為是自己配置有問題。然後各種改配置仍然不行。最後想了很久用了maven來下載下傳包,依賴問題解決了。 這裡建議如果在依賴不明的情況下,用maven下載下傳包。這樣就不會出現因為包依賴問題導緻程式跑不起來,浪費自己的時間。
           
最後給一下執行個體位址
           
http://download.csdn.net/detail/lj1314ailj/8943455
           

繼續閱讀