搭建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.companysz.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為例。
@Entitypublic 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如下:
@Repositorypublic class UserDAO implements IUserDAO {@PersistenceContext(unitName="test")private EntityManager entityManager;@Transactional(rollbackFor = Exception.class)@Overridepublic 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); }}
測試輸出如下:
測試開始------2c92de9e4a340533014a340537290000Hibernate: insert into User (userName, userId) values (?, ?)測試over---
新聞熱點
疑難解答