springMVC+jpa配置之简单案例
搭建springMVC+jpa的亲身经历,看着网上的博客,自己摸索着搭建框架结果错误一大堆。现在把流程走一遍,方便以后查看。
其中我遇到这样的一个问题:直接启动tomcat运行保存实体能通过,但是通过单元测试就报一下错误:
Caused by: javax.validation.ValidationException: Unable to instantiate Configuration.
解决方法:
在persistence.xml中添加这个<property name="javax.persistence.validation.mode" value="none" /> 还是不行,然后百度了下,
myeclipse 安装目录下找到 EE_6这个目录把bean-validator.jar去掉了结果成功了。
但是我还是想不通,为啥删除那个就行了,而启动tomcat就不会,为啥tomcat会忽略这个问题。看到的大神还请指教。以下是行的通的,如有问题还请指教。(http://www.cnblogs.com/yuanfy008/p/4156287.html)
第一步:准备相对应的jar包,其实我也不知道具体要用哪些包(这点需要我去学习的),先弄个大概的然后根据出现的错误一个一个的添加。
第二步:配置web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="3.0" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 6 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> 7 <display-name></display-name> 8 <welcome-file-list> 9 <welcome-file>index.jsp</welcome-file> 10 </welcome-file-list> 11 <!-- spring事物配置 --> 12 <context-param> 13 <param-name>contextConfigLocation</param-name> 14 <param-value>classpath*:spring-*.xml</param-value> 15 </context-param> 16 <listener> 17 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 18 </listener> 19 <!-- 全站编码过滤器 --> 20 <filter> 21 <filter-name>encodingFilter</filter-name> 22 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 23 <init-param> 24 <param-name>encoding</param-name> 25 <param-value>UTF-8</param-value> 26 </init-param> 27 <init-param> 28 <param-name>forceEncoding</param-name> 29 <param-value>true</param-value> 30 </init-param> 31 </filter> 32 <filter-mapping> 33 <filter-name>encodingFilter</filter-name> 34 <url-pattern>/*</url-pattern> 35 </filter-mapping> 36 37 <!-- springMVC配置器 --> 38 <servlet> 39 <servlet-name>springMVC</servlet-name> 40 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 41 <init-param> 42 <param-name>contextConfigLocation</param-name> 43 <param-value>classpath*:spring-mvc.xml</param-value> 44 </init-param> 45 <load-on-startup>1</load-on-startup> 46 </servlet> 47 <servlet-mapping> 48 <servlet-name>springMVC</servlet-name> 49 <url-pattern>/</url-pattern> 50 </servlet-mapping> 51 </web-app>
第三步:配置跟hibernate相关的xml文件 spring-orm.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:aop="http://www.springframework.org/schema/aop" 6 xmlns:tx="http://www.springframework.org/schema/tx" 7 xsi:schemaLocation="http://www.springframework.org/schema/beans 8 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 9 http://www.springframework.org/schema/context 10 http://www.springframework.org/schema/context/spring-context-3.0.xsd 11 http://www.springframework.org/schema/tx 12 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 13 http://www.springframework.org/schema/aop 14 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> 15 16 <!-- 配置数据源 此段没用放到了persistence.xml--> 17 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 18 <property name="driverClassName" value="com.mysql.jdbc.Driver"/> 19 <property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8"/> 20 <property name="username" value="root"/> 21 <property name="password" value="root"/> 22 </bean> 23 24 <!-- 配置EntityManagerFactory --> 25 <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 26 <property name="persistenceUnitName" value="test" /> 27 <property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"></property> 28 </bean> 29 30 <!-- 配置jpa的事务管理器 --> 31 <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> 32 <property name="entityManagerFactory" ref="entityManagerFactory"></property> 33 </bean> 34 35 <tx:annotation-driven transaction-manager="transactionManager" /> 36 </beans>
第四步:配置jpa的配置文件 persistence.xml
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="test" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" /> <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/test" /> <property name="hibernate.connection.username" value="root" /> <property name="hibernate.connection.password" value="root" /> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.format_sql" value="false" /> <property name="hibernate.hbm2ddl.auto" value="update" /> <property name="javax.persistence.validation.mode" value="none" /> </properties> </persistence-unit> </persistence>
第五步:配置springMVC相关的配置文件,spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.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-3.0.xsd"> <!-- 引入注解类 下面两个都可以注释 --> <mvc:annotation-driven/> <!-- 文件上传配置 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8" /> <property name="maxUploadSize" value="10485760000" /> <property name="maxInMemorySize" value="40960" /> </bean> <!-- 静态资源访问配置 --> <mvc:resources location="/img/" mapping="/img/**"/> <mvc:resources location="/topui/" mapping="/topui/**"/> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
第六步:然后用一个总的文件囊括这个几个配置文件,单元测试的时候就少些很多这些配置文件。spring-sevlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.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-3.0.xsd"> <context:annotation-config /> <!-- 注解扫描包 --> <context:component-scan base-package="com.bank.*"/> <import resource="spring-mvc.xml"/> <import resource="spring-orm.xml"/> </beans>
相应的配置完了,然后我们写个实体类,进行单元测试。我们这就以用户user为例。
@Entity public class User { @Id @GeneratedValue(generator = "uuidGenerator") @GenericGenerator(name = "uuidGenerator", strategy = "uuid") @Column(length = 32, nullable = false) private String userId; private String userName; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }
对应的dao层IUserDAO如下:
public interface IUserDAO { public void save(User user); }
对应的UserDAO如下:
@Repository public class UserDAO implements IUserDAO { @PersistenceContext(unitName="test") private EntityManager entityManager; @Transactional(rollbackFor = Exception.class) @Override public void save(User user) { //System.out.println(entityManagerFactory); this.entityManager.persist(user); System.out.println("---"+user.getUserId()); } }
然后经典的单元测试来了,如下:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:spring-servlet.xml"}) @TransactionConfiguration(defaultRollback = false) public class UserTest { @Resource private IUserDAO userDAO ; @Before public void start(){ System.out.println("测试开始---"); } @After public void end(){ System.out.println("测试over---"); } @Test public void test1(){ User user = new User(); user.setUserName("test"); userDAO.save(user); //System.out.println(userDAO); } }
测试输出如下:
测试开始---
---2c92de9e4a340533014a340537290000
Hibernate: insert into User (userName, userId) values (?, ?)
测试over---