Spring MVC“org.hibernate.PropertyAccessException”中的休眠注释映射异常
Posted
技术标签:
【中文标题】Spring MVC“org.hibernate.PropertyAccessException”中的休眠注释映射异常【英文标题】:Hibernate Annotation Mapping Exception in Spring MVC "org.hibernate.PropertyAccessException" 【发布时间】:2015-01-20 17:13:18 【问题描述】:我是 Spring MVC 和 Hibernate 的新手。我尝试在 Spring MVC 中实现基于 Hibernate 注释的映射,以使用 @OneToMany 双向注释将列添加到表 Users 和 Address 中。但是我得到了以下异常'org.hibernate.PropertyAccessException'
SEVERE: Servlet.service() for servlet [mvc-dispatcher] in context with path [/UserRegistration] threw exception [Request processing failed; nested exception is org.hibernate.PropertyAccessException: could not set a field value by reflection setter of com.ram.model.domain.Address.userId] with root cause
java.lang.IllegalArgumentException: Can not set java.lang.Integer field com.ram.model.domain.Address.userId to org.hibernate.id.IdentifierGeneratorHelper$2
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeObjectFieldAccessorImpl.set(Unknown Source)
at java.lang.reflect.Field.set(Unknown Source)
at org.hibernate.property.DirectPropertyAccessor$DirectSetter.set(DirectPropertyAccessor.java:122)
at org.hibernate.mapping.Component$ValueGenerationPlan.execute(Component.java:441)
at org.hibernate.id.CompositeNestedGeneratedValueGenerator.generate(CompositeNestedGeneratedValueGenerator.java:121)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:114)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:684)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:676)
at org.hibernate.engine.spi.CascadingActions$5.cascade(CascadingActions.java:235)
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:350)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:293)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:161)
at org.hibernate.engine.internal.Cascade.cascadeCollectionElements(Cascade.java:379)
at org.hibernate.engine.internal.Cascade.cascadeCollection(Cascade.java:319)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:296)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:161)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:118)
at org.hibernate.event.internal.AbstractSaveEventListener.cascadeAfterSave(AbstractSaveEventListener.java:460)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:294)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at com.ram.model.dao.HibernateUsersDAO.store(HibernateUsersDAO.java:24)
at com.ram.service.SimpleUsersManager.storeUsers(SimpleUsersManager.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy33.storeUsers(Unknown Source)
at com.ram.web.UsersFormController.listPersons1(UsersFormController.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
这里是示例代码
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ram</groupId>
<artifactId>UserRegistration</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>UserRegistration Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<java-version>1.6</java-version>
<org.springframework-version>4.0.3.RELEASE</org.springframework-version>
<org.aspectj-version>1.7.4</org.aspectj-version>
<org.slf4j-version>1.7.5</org.slf4j-version>
<hibernate.version>4.3.5.Final</hibernate.version>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>$org.springframework-version</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>$org.springframework-version</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>$org.springframework-version</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>$org.springframework-version</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>$hibernate.version</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>$hibernate.version</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.0.Final</version>
</dependency>
<!-- Apache Commons DBCP -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>$org.aspectj-version</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>$org.slf4j-version</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>$org.slf4j-version</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>$org.slf4j-version</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>
<!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- Apache Commons IO -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.11.0</version>
</dependency>
</dependencies>
<build>
<finalName>UserRegistration</finalName>
</build>
</project>
mvc-dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<annotation-driven />
<context:component-scan base-package="com.ram" />
<resources mapping="/resources/**" location="/resources/screen/" />
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/pages/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://localhost:8080/database" />
<beans:property name="username" value="user1" />
<beans:property name="password" value="root" />
</beans:bean>
<beans:bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:packagesToScan="com.aram.spring.emr">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>com.ram.model.domain.Users</beans:value>
<beans:value>com.ram.model.domain.Address</beans:value>
</beans:list>
</beans:property>
</beans:bean>
<beans:bean id="userDAO" class="com.ram.model.dao.HibernateUsersDAO"/>
<beans:bean id="userService" class="com.ram.service.SimpleUsersManager"/>
<beans:bean id="addressDAO" class="com.ram.model.dao.HibernateAddressDAO"/>
<beans:bean id="addressService" class="com.ram.service.SimpleAddressManager"/>
<beans:bean class="org.springframework.context.support.ResourceBundleMessageSource"
id="messageSource">
<beans:property name="basename" value="messages" />
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<beans:property name="maxUploadSize" value="10000000" />
</beans:bean>
</beans:beans>
Users.java
@Entity
@Table(name = "Users")
public class Users implements Serializable
private static final long serialVersionUID = 1L;
@Id
@Column(name = "UserID")
@GeneratedValue
private Integer id;
@Column(name = "FirstName")
private String firstName;
@Column(name = "LastName")
private String lastName;
@OneToMany(targetEntity= Address.class, mappedBy="user", fetch= FetchType.EAGER, cascade=CascadeType.ALL)
private Set<Address> address;
// corresponding getters and setters
Address.java
@Entity
@Table(name = "Address")
public class Address implements Serializable
private static final long serialVersionUID = 1L;
@Id
@Column(name = "AddressID")
@GeneratedValue
private Integer addressId;
@Id
@Column(name = "UserID")
@GeneratedValue
private Integer userId;
@Column(name = "AddressLine1")
private String addressLine1;
@Column(name = "AddressLine2")
private String addressLine2;
@ManyToOne
@JoinColumn(name="UserID")
private Users user;
// corresponding getters and setters
SimpleUserManager.java
@Service
public class SimpleUsersManager implements UsersManager
@Autowired
private UsersDAO userDAO;
@Transactional
public void storeUsers(Users user)
this.userDAO.store(user);
SimpleAddressManager.java
public class SimpleAddressManager implements AddressManager
@Autowired
private AddressDAO addressDAO;
@Transactional
public void storeAddress(Address address)
this.addressDAO.store(address);
HibernateUsersDAO.java
@Repository
public class HibernateUsersDAO implements UsersDAO
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf)
this.sessionFactory = sf;
public void store(Users user)
Session session = this.sessionFactory.getCurrentSession();
session.save(user);
HibernateAddressDAO.java
public class HibernateAddressDAO implements AddressDAO
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf)
this.sessionFactory = sf;
public void store(Address address)
Session session = this.sessionFactory.getCurrentSession();
session.save(address);
UserController.java
@Controller
@SessionAttributes
public class UsersFormController
@Autowired(required=true)
private UsersManager userService;
@Autowired(required=true)
private AddressManager addressService;
@Qualifier(value="userService")
public void setUsersService(UsersManager userService)
this.userService =userService;
@Qualifier(value="addressService")
public void setAddressService(AddressManager addressService)
this.addressService =addressService;
@RequestMapping(value = "/Registration", method = RequestMethod.GET)
public String addPersons()
return "Registration";
@RequestMapping(value = "/Registration", method = RequestMethod.POST)
public String addUser(@ModelAttribute ("user") Users user, @ModelAttribute ("address") Address address)
address.setUser(user);
Set<Address> address1 = new HashSet<Address>();
address1.add(address);
user.setAddress(address1);
this.userService.storeUsers(user);
this.addressService.storeAddress(address);
return "Success";
Registration.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ page session="false"%>
<html>
<head>
<title>User Registration</title>
</head>
<body>
<h1>User Registration</h1>
<c:url var="addAction" value="Registration"></c:url>
<form:form action="$addAction" method="POST">
<table>
<tr>
<td>First Name</td>
<td><input class="input" type="text" name="firstName"></td>
</tr>
<tr>
<td>Last Name</td>
<td><input class="input" type="text" name="lastName"></td>
</tr>
<tr>
<td>Address Line 1</td>
<td><input class="input" type="text" name="addressLine1"></td>
</tr>
<tr>
<td>Address Line 1</td>
<td><input class="input" type="text" name="addressLine2"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" Class="regButton" value="Register"></td>
</tr>
</table>
</form:form>
</body>
</html>
我已经为此异常搜索了很多答案,但我无法找到正确的解决方案。请帮助我。提前谢谢..
【问题讨论】:
为什么在同一个地址表中有两个列名UserID
?
【参考方案1】:
据我所知,Address
不应该有这个字段:
@Id
@Column(name = "UserID")
@GeneratedValue
private Integer userId;
为了从Address
映射User
,拥有@ManyToOne
字段就足够了。
【讨论】:
感谢您的帮助...:)以上是关于Spring MVC“org.hibernate.PropertyAccessException”中的休眠注释映射异常的主要内容,如果未能解决你的问题,请参考以下文章
关于spring mvc 请求参数校验使用中的坑 。 maven 生命周期,线程池杂识
org.hibernate.LazyInitializationException:无法初始化代理 - 没有会话。 Spring + Hibernate + HSQLDB
org.hibernate.LazyInitializationException:懒惰初始化角色集合失败(Hibernate + Spring)
Spring Hibernate:Generic Dao 添加原因 - org.hibernate.TransactionException:不支持嵌套事务
升级到 hibernate 4 和 spring 4 jars 但仍然得到 org.hibernate.engine.FilterDefinition classnotfoundexception
在spring boot集成测试中获取org.hibernate.LazyInitializationException