springMVC+jpa配置之简单案例

时间:2024-01-02 10:49:26

  搭建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包,其实我也不知道具体要用哪些包(这点需要我去学习的),先弄个大概的然后根据出现的错误一个一个的添加。

  springMVC+jpa配置之简单案例springMVC+jpa配置之简单案例

  第二步:配置web.xml

  

 <?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- spring事物配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 全站编码过滤器 -->
<filter>
<filter-name>encodingFilter</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>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- springMVC配置器 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring-mvc.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>

第三步:配置跟hibernate相关的xml文件 spring-orm.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- 配置数据源 此段没用放到了persistence.xml-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean> <!-- 配置EntityManagerFactory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="test" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"></property>
</bean> <!-- 配置jpa的事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean> <tx:annotation-driven transaction-manager="transactionManager" />
</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---