ヘルプ!、これを解決しようとしましたが、参照された ID の値を取得できません。保存時に null 値が返されます。
Error: Column 'p_id' cannot be null
org.hibernate.exception.ConstraintViolationException: Column 'p_id' cannot be null
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:74)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at $Proxy23.executeUpdate(Unknown Source)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2870)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3381)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:362)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:203)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:183)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:167)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:320)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:287)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:126)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:208)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:151)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:831)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:824)
at org.hibernate.engine.spi.CascadingAction$7.cascade(CascadingAction.java:315)
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:380)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:323)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:208)
at org.hibernate.engine.internal.Cascade.cascadeCollectionElements(Cascade.java:409)
at org.hibernate.engine.internal.Cascade.cascadeCollection(Cascade.java:350)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:326)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:208)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:165)
at org.hibernate.event.internal.AbstractSaveEventListener.cascadeAfterSave(AbstractSaveEventListener.java:448)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:293)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:126)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:208)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:151)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:78)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:840)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:815)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:819)
at nhtu.dao.UserDAOImpl.addPerson(UserDAOImpl.java:43)
at nhtu.controller.ApplicantForm.update(ApplicantForm.java:70)
at nhtu.controller.ApplicantForm.create(ApplicantForm.java:59)
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.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'p_id' cannot be null
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1040)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4074)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4006)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2468)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2629)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2719)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2450)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2371)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2355)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
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.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
... 70 more
これは私のモデルです
@Entity
@Table(name="personal_info")
public class Person {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="p_id")
private int personId;
@Column(name="l_name")
private String lastName;
@Column(name="f_name")
private String firstName;
@Column(name="m_name")
private String middleName;
@Temporal(TemporalType.DATE)
@Column(name="b_date")
private Date birthDate;
private String address;
@Column(name="gender")
private String gender;
@Column(name="ext_name")
private String nameExtension;
@Column(name="marital_status")
private String maritalStatus;
@Column(name="c_num")
private String contactNumber;
@Column(name="email")
private String emailAddress;
@Column(name="coll_grad")
private int isCollegeGraduate;
@Column(name="post_grad")
private int isPostGraduate;
@Column(name="undergrad")
private int isUnderGraduate;
@OneToMany(cascade={CascadeType.ALL}, mappedBy="person")
private Collection<Application> application = new ArrayList<Application>(); //
link to applications
@OneToMany(cascade={CascadeType.PERSIST},mappedBy="personId")
private Collection<EducationalDetails> educationalDetail = new
ArrayList<EducationalDetails>(); // link to educational attainments of a person
public Collection<EducationalDetails> getEducationalDetails(){
return educationalDetail;
}
public void setEducationalDetails(Collection<EducationalDetails> educationalDetail)
{
this.educationalDetail=educationalDetail;
}
public int getPersonId() {
return personId;
}
public void setPersonId(int personId) {
this.personId = personId;
}
@OneToMany(cascade={CascadeType.ALL}, mappedBy="person")
private Collection<Employment> employment = new ArrayList<Employment>(); // link to
employee
public Person() {}
public int getIsCollegeGraduate() {
return isCollegeGraduate;
}
public void setIsCollegeGraduate(int isCollegeGraduate) {
this.isCollegeGraduate = isCollegeGraduate;
}
public int getIsPostGraduate() {
return isPostGraduate;
}
public void setIsPostGraduate(int isPostGraduate) {
this.isPostGraduate = isPostGraduate;
}
public int getIsUnderGraduate() {
return isUnderGraduate;
}
public void setIsUnderGraduate(int isUnderGraduate) {
this.isUnderGraduate = isUnderGraduate;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getNameExtension() {
return nameExtension;
}
public void setNameExtension(String nameExtension) {
this.nameExtension = nameExtension;
}
public String getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(String maritalStatus) {
this.maritalStatus = maritalStatus;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public Collection<Application> getApplication() {
return application;
}
public void setApplication(Collection<Application> application) {
this.application = application;
}
public Collection<EducationalDetails> getEducationalDetail() {
return educationalDetail;
}
public void setEducationalDetail(
Collection<EducationalDetails> educationalDetail) {
this.educationalDetail = educationalDetail;
}
public Collection<Employment> getEmployment() {
return employment;
}
public void setEmployment(Collection<Employment> employment) {
this.employment = employment;
}
}
@Entity
@Table(name="educ_detail")
public class EducationalDetails {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="ed_id")
private int educDetailsId;
@ManyToOne(targetEntity=Person.class)
@JoinColumn(name ="p_id",referencedColumnName="p_id")
private Person personId;
@Column(name="level")
private int educationalLevel;
@Column(name="name_school")
private String nameOfSchool;
@Column(name="inc_date")
private String inclusiveDates;
@Column(name="course")
private String course;
@Column(name="year_graduated")
private int yearGraduated;
@Column(name="units_earned")
private int unitsEarned;
public EducationalDetails(){}
/*public EducationalDetails(Person person){
this.person = person;
}*/
public int getEducDetailsId() {
return educDetailsId;
}
public void setEducDetailsId(int educDetailsId) {
this.educDetailsId = educDetailsId;
}
public int getEducationalLevel() {
return educationalLevel;
}
public void setEducationalLevel(int educationalLevel) {
this.educationalLevel = educationalLevel;
}
public String getNameOfSchool() {
return nameOfSchool;
}
public void setNameOfSchool(String nameOfSchool) {
this.nameOfSchool = nameOfSchool;
}
public String getInclusiveDates() {
return inclusiveDates;
}
public void setInclusiveDates(String inclusiveDates) {
this.inclusiveDates = inclusiveDates;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public int getYearGraduated() {
return yearGraduated;
}
public void setYearGraduated(int yearGraduated) {
this.yearGraduated = yearGraduated;
}
public int getUnitsEarned() {
return unitsEarned;
}
public void setUnitsEarned(int unitsEarned) {
this.unitsEarned = unitsEarned;
}
public Person getPersonId(){
return personId;
}
public void setPersonId(Person personId) {
// TODO Auto-generated method stub
this.personId = personId;
}
}
@Controller
@RequestMapping("/applicantForm.html")
public class ApplicantForm {
@Autowired
private UserDAO userdao;
//private EducationalDetails educDetail = new EducationalDetails();
public void initBinder(WebDataBinder dataBinder) {
System.out.println("dataBinder");
dataBinder.setRequiredFields(new String[] { "firstName", "lastName",
"middleName", "address", "gender" });
dataBinder.registerCustomEditor(String.class, new
StringTrimmerEditor(false));
}
@RequestMapping(method = RequestMethod.GET)
public Person setUpForm(@RequestParam(value = "id", required = false) Integer
personID) {
System.out.println("setup form");
if (personID == null) {
Person person = new Person();
EducationalDetails educ1 = new EducationalDetails();
EducationalDetails educ2 = new EducationalDetails();
EducationalDetails educ3 = new EducationalDetails();
System.out.println(person.getLastName());
person.getEducationalDetail().add(educ1);
person.getEducationalDetail().add(educ2);
person.getEducationalDetail().add(educ3);
educ3.setPersonId(person);
educ2.setPersonId(person);
educ1.setPersonId(person);
return person;
} else {
return userdao.getPersonById(personID);
}
}
@RequestMapping(params = "create", method = RequestMethod.POST)
public String create(Person person, BindingResult result,
SessionStatus status) {
System.out.println("create");
return update(person,result, status);
}
@RequestMapping(params = "update", method = RequestMethod.POST)
public String update(Person person,BindingResult result, SessionStatus status) {
//employeeValidator.validate(emp, result);
System.out.println("update");
if (result.hasErrors()) {
System.out.println("has errors");
return "applicantForm";
} else {
userdao.addPerson(person);
status.setComplete();
return "redirect:applicantForm.html";
}
}
}
@Repository
public class UserDAOImpl implements UserDAO {
@Autowired
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Person addPerson(Person person) {
Session session = sessionFactory.openSession();
System.out.println(session);
try {
session.beginTransaction();
session.persist(person);
session.getTransaction().commit();
} catch (HibernateException ex) {
ex.printStackTrace();
session.getTransaction().rollback();
} finally {
session.close();
}
return person;
}
public interface UserDAO {
public Person addPerson(Person person);
public void modifyPersonDetails(int personId, String lastName, String firstName,
String middleName, String nameExtension,
Date birthDate, String address, String gender, String
maritalStatus, String contactNumber, String emailAddress,
boolean isCollegeGraduate, boolean isPostGraduate, boolean
isUnderGraduate);
public Collection<Person> listAllPersons();
public Collection<Person> searchByName(String firstName, String lastName);