this is my User.java
@Entity
@Table(name = "user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private int id;
@Column(name = "FIRST_NAME")
private String firstName;
@Column(name = "LAST_NAME")
private String lastName;
@Column(name = "EMAIL")
private String email;
@OneToMany(cascade={CascadeType.ALL})
@JoinColumn(name="USER_ID")
private Collection<Address> addresses;
}
and this is my Address.java
@Entity
@Table(name = "address")
public class Address implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private int id;
@Column(name = "TOWN")
private String town;
@Column(name = "DISTRICT")
private String district;
@Column(name = "COUNTRY")
private String country;
@ManyToOne
@JoinColumn(name = "USER_ID", insertable=false, updatable=false, nullable=false)
private User user;
}
but while I'm trying to persist the object I'm getting this exception
javax.servlet.ServletException: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not insert: [com.kpowd.model.Address]
javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
root cause
javax.faces.el.EvaluationException: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not insert: [com.kpowd.model.Address]
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:101)
javax.faces.component.UICommand.broadcast(UICommand.java:315)
javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:798)
javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1331)
com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:181)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:645)
root cause
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not insert: [com.kpowd.model.Address]
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1387)
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1315)
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1321)
org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:843)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
com.sun.proxy.$Proxy19.persist(Unknown Source)
com.kpowd.dao.basedao.GenericDaoImpl.create(GenericDaoImpl.java:47)
com.kpowd.service.impl.UserServiceImpl.registerUser(UserServiceImpl.java:34)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
com.sun.proxy.$Proxy20.registerUser(Unknown Source)
com.kpowd.controller.UserRegistrationBean.register(UserRegistrationBean.java:80)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.apache.el.parser.AstValue.invoke(AstValue.java:278)
org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:101)
javax.faces.component.UICommand.broadcast(UICommand.java:315)
javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:798)
javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1331)
com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:181)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:645)
root cause
org.hibernate.exception.GenericJDBCException: could not insert: [com.kpowd.model.Address]
org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:140)
org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:128)
org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2345)
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2852)
org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
org.hibernate.ejb.event.EJB3PersistEventListener.saveWithGeneratedId(EJB3PersistEventListener.java:69)
org.hibernate.event.def.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:179)
org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:135)
org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:799)
org.hibernate.impl.SessionImpl.persist(SessionImpl.java:791)
org.hibernate.engine.EJB3CascadingAction$1.cascade(EJB3CascadingAction.java:48)
org.hibernate.engine.Cascade.cascadeToOne(Cascade.java:392)
org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:335)
org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:204)
org.hibernate.engine.Cascade.cascadeCollectionElements(Cascade.java:425)
org.hibernate.engine.Cascade.cascadeCollection(Cascade.java:362)
org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:338)
org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:204)
org.hibernate.engine.Cascade.cascade(Cascade.java:161)
org.hibernate.event.def.AbstractSaveEventListener.cascadeAfterSave(AbstractSaveEventListener.java:475)
org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:353)
org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
org.hibernate.ejb.event.EJB3PersistEventListener.saveWithGeneratedId(EJB3PersistEventListener.java:69)
org.hibernate.event.def.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:179)
org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:135)
org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:61)
org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:808)
org.hibernate.impl.SessionImpl.persist(SessionImpl.java:782)
org.hibernate.impl.SessionImpl.persist(SessionImpl.java:786)
org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:837)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
com.sun.proxy.$Proxy19.persist(Unknown Source)
com.kpowd.dao.basedao.GenericDaoImpl.create(GenericDaoImpl.java:47)
com.kpowd.service.impl.UserServiceImpl.registerUser(UserServiceImpl.java:34)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
com.sun.proxy.$Proxy20.registerUser(Unknown Source)
com.kpowd.controller.UserRegistrationBean.register(UserRegistrationBean.java:80)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.apache.el.parser.AstValue.invoke(AstValue.java:278)
org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:101)
javax.faces.component.UICommand.broadcast(UICommand.java:315)
javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:798)
javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1331)
com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:181)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:645)
root cause
java.sql.SQLException: Field 'USER_ID' doesn't have a default value
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490)
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109)
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2648)
com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2077)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2362)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2280)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2265)
org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:94)
org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57)
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2345)
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2852)
org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
org.hibernate.ejb.event.EJB3PersistEventListener.saveWithGeneratedId(EJB3PersistEventListener.java:69)
org.hibernate.event.def.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:179)
org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:135)
org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:799)
org.hibernate.impl.SessionImpl.persist(SessionImpl.java:791)
org.hibernate.engine.EJB3CascadingAction$1.cascade(EJB3CascadingAction.java:48)
org.hibernate.engine.Cascade.cascadeToOne(Cascade.java:392)
org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:335)
org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:204)
org.hibernate.engine.Cascade.cascadeCollectionElements(Cascade.java:425)
org.hibernate.engine.Cascade.cascadeCollection(Cascade.java:362)
org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:338)
org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:204)
org.hibernate.engine.Cascade.cascade(Cascade.java:161)
org.hibernate.event.def.AbstractSaveEventListener.cascadeAfterSave(AbstractSaveEventListener.java:475)
org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:353)
org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
org.hibernate.ejb.event.EJB3PersistEventListener.saveWithGeneratedId(EJB3PersistEventListener.java:69)
org.hibernate.event.def.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:179)
org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:135)
org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:61)
org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:808)
org.hibernate.impl.SessionImpl.persist(SessionImpl.java:782)
org.hibernate.impl.SessionImpl.persist(SessionImpl.java:786)
org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:837)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
com.sun.proxy.$Proxy19.persist(Unknown Source)
com.kpowd.dao.basedao.GenericDaoImpl.create(GenericDaoImpl.java:47)
com.kpowd.service.impl.UserServiceImpl.registerUser(UserServiceImpl.java:34)
Error wont come if i remove the "NOTNULL" Constraint from the FORIGN_KEY "USER_ID" but i need to make it as a NOTNULL Column how should i want to do that. please help me??
this is my register methode
public String register() {
// Output some info
Address a = new Address();
a.setCountry("country1");
a.setDistrict("district1");
a.setTown("town");
Address b = new Address();
b.setCountry("country2");
b.setDistrict("district2");
b.setTown("town2");
List<Address> adrlist=new ArrayList<Address>();
adrlist.add(a);
adrlist.add(b);
User user = new User();
user.setFirstName("firstname");
user.setLastName("lastname");
user.setEmail("email");
user.setAddresses(adrlist);
// Call the business object to register the user
userService.registerUser(user);
// Set the message here
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Registration success", "success");
FacesContext.getCurrentInstance().addMessage(null, msg);
System.out.println("befor redirect");
return "index?faces-redirect=true";
}
and this is my SQL Script
CREATE DATABASE IF NOT EXISTS `myshop`;
USE `myshop`;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`FIRST_NAME` varchar(45) DEFAULT NULL,
`LAST_NAME` varchar(45) DEFAULT NULL,
`EMAIL` varchar(45) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=46 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `address`;
CREATE TABLE `address` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`TOWN` varchar(45) DEFAULT NULL,
`DISTRICT` varchar(45) DEFAULT NULL,
`COUNTRY` varchar(45) DEFAULT NULL,
`USER_ID` int(11) NOT NULL,
PRIMARY KEY (`ID`),
KEY `FK_USER_idx` (`USER_ID`),
CONSTRAINT `FK_USER` FOREIGN KEY (`USER_ID`) REFERENCES `user` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
To me, it looks like you have specified your relationship wrong. Have a look my Q&A here . You specifically want to be looking at the uni-directional 1 to many example. With your current configuration I think Hibernate is trying to create 2 uni-directional 1 to many relationships and that is causing issues.
Specifying insertable = false, updateable = false, nullable = false
on your @JoinColumn
annotation won't be doing anything. Those modifiers only do something if you are using Hibernate to create your database schema based on your annotations. Since you already have a schema, it doesn't do anything.
It would be helpful for debugging purposes if you could post your registerUser
method.
public class Address implements Serializable {
....
@ManyToOne
@JoinColumn(name = "USER_ID")
private User user;
}
public class User implements Serializable{
....
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private Collection<Address> addresses;
}
As the exception you are getting is java.sql.SQLException: Field 'USER_ID' doesn't have a default value
You can set a default value for your column in Hibernate using annotation like @JoinColumn(name = "USER_ID", insertable=false, updatable=false, nullable=false), columnDefinition = “int default 100"
You can give any value in spite of 100 what you want to be your default value.
Second thing, may be you would like to add somewhere referencedColumnName = "SOME_COLUMN"
when you are making foreign keys.
Hope it helps.
Edit:
Please let me explain a bit, the referencedColumnName can be used to specify another column as the default id column of the other table.
Table1
id int identity
tableb_key varchar
Table2
id int identity
key varchar unique
// in class for Table1
@Joincolumn(column="tableb_key", referencedColumnName="key")
When doing OneToMany and ManyToOne, you have to do add Parent object in you Chilid object as well Child in Parent Ojbect I mean you need to do a.setUser(user); b.setUser(user);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.