I am using Hibernate/Annotations 3.4.0GA.
I have a User object, which has a List of Address objects. There is a bidirectional association between them. When I save a User, I want hibernate to automatically save the associated Address objects.
I am getting an error when I try to save a User object that contains an Address object. The error is "
Cannot insert the value NULL into column 'USER_ID', table 'dbo.ADDRESS'; column does not allow nulls. INSERT fails.". I am hoping someone can show me what I'm doing wrong.
I'm trying to following the documentation for One-to-Many Bidirectional (2.2.5.3.1.1. Bidirectional) where the Troop class is the owning entity. (See
http://docs.jboss.org/hibernate/stable/ ... ssociation). I know my code is a little different. I also tried to apply the code from
viewtopic.php?p=2372242. Nothing has worked. I could really use some help.
User.javaCode:
@Entity
@Table(name = "USERS")
@Inheritance(strategy = InheritanceType.JOINED)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class User implements java.io.Serializable
{
protected static final long serialVersionUID = 5769515016671196464L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "USER_ID")
protected Integer id;
@Column(name = "USER_EMAIL", nullable = false, length = 200, unique = true)
protected String email;
@Column(name = "USER_FIRST_NAME", length = 100)
protected String firstName;
@Column(name = "USER_LAST_NAME", nullable = false, length = 100)
protected String lastName;
@Column(name = "USER_PASSWORD", nullable = false, length = 50)
protected String password;
@OneToMany(mappedBy="user", cascade=CascadeType.ALL)
@JoinColumn(name = "USER_ID", referencedColumnName="USER_ID")
protected Set<Address> addresses = new HashSet<Address>(0);
public Integer getId() {
return this.id;
}
public void setId(Integer userId) {
this.id = userId;
}
public String getEmail() {
return this.email;
}
public void setEmail(String userEmail) {
this.email = userEmail;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String userFirstName) {
this.firstName = userFirstName;
}
public String getPassword() {
return this.password;
}
public void setPassword(String userPassword) {
this.password = userPassword;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String userLastName) {
this.lastName = userLastName;
}
public Set<Address> getAddresses() {
return this.addresses;
}
public void setAddresses(Set<Address> addresses) {
this.addresses = addresses;
}
public void addAddress(Address a) {
addresses.add(a);
a.setUser(this);
}
public void removeAddress(Address a) {
addresses.remove(a);
a.setUser(null);
}
public boolean equals(Object o)
{
if (this == o) return true; // Referential Equality
if ((o instanceof User) == false) return false; // Type Equality
return this.hashCode() == o.hashCode();
}
public int hashCode() {
if (id != null) return id.hashCode();
return super.hashCode();
}
}
RMM.javaCode:
@Entity
@Table(name = "rmm_users")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class RMM extends User {
private static final long serialVersionUID = -3809450815523994529L;
}
Address.javaCode:
@Entity
@Table(name = "ADDRESS")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Address implements java.io.Serializable
{
private static final long serialVersionUID = -5152684995836286617L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ADDRESS_ID")
private Integer id;
@Column(name = "ADDRESS_LINE1", nullable = false, length = 100)
private String addressLine1;
@Column(name = "ADDRESS_LINE2", length = 100)
private String addressLine2;
@Column(name = "ADDRESS_CITY", length = 100)
private String city;
@Column(name = "ADDRESS_ZIP5", length = 5)
private String zip5;
@Column(name = "ADDRESS_ZIP4", length = 4)
private String zip4;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "USER_ID", referencedColumnName="USER_ID", insertable = false, updatable = false)
private User user;
public Integer getId() {
return this.id;
}
public void setId(Integer addressId) {
this.id = addressId;
}
public String getAddressLine1() {
return this.addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return this.addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getCity() {
return this.city;
}
public void setCity(String addressCity) {
this.city = addressCity;
}
public String getZip5() {
return this.zip5;
}
public void setZip5(String addressZip5) {
this.zip5 = addressZip5;
}
public String getZip4() {
return this.zip4;
}
public void setZip4(String addressZip4) {
this.zip4 = addressZip4;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Table Definitions (SQL Server 2005)Code:
CREATE TABLE [dbo].[USERS](
[USER_ID] [int] IDENTITY(1,1) NOT NULL,
[USER_EMAIL] [varchar](200) NOT NULL,
[USER_PASSWORD] [varchar](50) NOT NULL,
[USER_FIRST_NAME] [varchar](100) NULL,
[USER_LAST_NAME] [varchar](100) NULL,
CONSTRAINT [PK4] PRIMARY KEY NONCLUSTERED
(
[USER_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY];
CREATE TABLE [dbo].[RMM_USERS](
[USER_ID] [int] NOT NULL,
CONSTRAINT [PK67] PRIMARY KEY CLUSTERED
(
[USER_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY];
ALTER TABLE [dbo].[RMM_USERS] WITH CHECK ADD CONSTRAINT [RefUSERS128] FOREIGN KEY([USER_ID]) REFERENCES [dbo].[USERS] ([USER_ID]);
CREATE TABLE [dbo].[ADDRESS](
[ADDRESS_ID] [int] IDENTITY(1,1) NOT NULL,
[ADDRESS_LINE1] [varchar](100) NOT NULL,
[ADDRESS_LINE2] [varchar](100) NULL,
[ADDRESS_CITY] [varchar](100) NOT NULL,
[ADDRESS_ZIP5] [char](5) NOT NULL,
[ADDRESS_ZIP4] [char](4) NULL,
[USER_ID] [int] NOT NULL,
CONSTRAINT [PK15] PRIMARY KEY NONCLUSTERED
(
[ADDRESS_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY];
ALTER TABLE [dbo].[ADDRESS] WITH CHECK ADD CONSTRAINT [RefUSERS26] FOREIGN KEY([USER_ID]) REFERENCES [dbo].[USERS] ([USER_ID]);
UserService.javaCode:
User user = new RMM();
// set user properties...
Address address = new Address();
// set address properties...
user.addAddress(address);
session.saveOrUpdate(user); // Throws the exception below
// session.persist(user); // this throws the same exception
ErrorCode:
2010-07-22 12:27:03,336 DEBUG [org.hibernate.SQL] log -
insert
into
USERS
(USER_EMAIL, USER_FIRST_NAME, USER_LAST_NAME, USER_PASSWORD)
values
(?, ?, ?, ?)
2010-07-22 12:27:03,336 DEBUG [org.hibernate.SQL] log -
insert
into
rmm_users
(USER_ID)
values
(?)
2010-07-22 12:27:03,336 DEBUG [org.hibernate.SQL] log -
insert
into
ADDRESS
(ADDRESS_LINE1, ADDRESS_LINE2, ADDRESS_CITY, ADDRESS_ZIP4, ADDRESS_ZIP5)
values
(?, ?, ?, ?, ?)
2010-07-22 12:27:03,336 ERROR [org.hibernate.util.JDBCExceptionReporter] logExceptions - Cannot insert the value NULL into column 'USER_ID', table 'dbo.ADDRESS'; column does not allow nulls. INSERT fails.
org.hibernate.exception.ConstraintViolationException: could not insert: [platform.domain.Address]
2010-07-22 12:27:03,336 DEBUG [org.springframework.web.servlet.DispatcherServlet] processRequest - Could not complete request
org.hibernate.exception.ConstraintViolationException: could not insert: [platform.domain.Address]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:40)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2108)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2588)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:248)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:290)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:180)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:108)
at org.hibernate.event.def.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:131)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:87)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:609)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:601)
at org.hibernate.engine.CascadingAction$8.cascade(CascadingAction.java:295)
at org.hibernate.engine.Cascade.cascadeToOne(Cascade.java:268)
at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:216)
at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:169)
at org.hibernate.engine.Cascade.cascadeCollectionElements(Cascade.java:296)
at org.hibernate.engine.Cascade.cascadeCollection(Cascade.java:242)
at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:219)
at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:169)
at org.hibernate.engine.Cascade.cascade(Cascade.java:130)
at org.hibernate.event.def.AbstractSaveEventListener.cascadeAfterSave(AbstractSaveEventListener.java:437)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:326)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:180)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:108)
at org.hibernate.event.def.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:131)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:87)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:38)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:618)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:592)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:596)
at platform.persistence.hibernate.HibernateDAO.persist(HibernateDAO.java:207)
at platform.service.defaults.DefaultUserService.createUser(DefaultUserService.java:985)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:108)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy42.createUser(Unknown Source)
at mvc.controllers.common.AddUserController.doSubmitAction(AddUserController.java:137)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(HandlerMethodInvoker.java:710)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:167)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:414)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:402)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:563)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:343)
at org.springframework.security.web.authentication.switchuser.SwitchUserFilter.doFilter(SwitchUserFilter.java:177)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:188)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:149)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:174)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:544)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:151)
at org.apache.jk.server.JkCoyoteHandler.invoke(JkCoyoteHandler.java:200)
at org.apache.jk.common.HandlerRequest.invoke(HandlerRequest.java:283)
at org.apache.jk.common.ChannelSocket.invoke(ChannelSocket.java:773)
at org.apache.jk.common.ChannelSocket.processConnection(ChannelSocket.java:703)
at org.apache.jk.common.ChannelSocket$SocketConnection.runIt(ChannelSocket.java:895)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Thread.java:619)