公司用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