我正在关注gontuseries中的教程。因此,我有这段代码可在数据库中保留两条记录。
我的测试班:
public class Test {
private HibernateUtility util;
private Session session;
private Transaction tx;
public Test() {
util = HibernateUtility.getInstance();
session = util.getSessionFactory().openSession();
tx = session.beginTransaction();
}
public void simpleSaving() {
List<StudentInfo> students = new ArrayList<StudentInfo>();
StudentInfo student = new StudentInfo();
student.setRollNo(1);
student.setName("Jo");
student.setBirthdate(new Date());
StudentInfo student2 = new StudentInfo();
student.setRollNo(2);
student.setName("JC");
student.setBirthdate(new Date());
students.add(student);
students.add(student2);
for(StudentInfo s : students) {
session.save(s);
}
tx.commit();
session.close();
util.getSessionFactory().close();
}
}
这是我的POJO:
@Entity
@Table(name="student_info")
public class StudentInfo implements Serializable{
@Id
private int rollNo;
@Column(name="name")
private String name;
@Temporal(TemporalType.DATE)
@Column(name="birth_date")
private Date birthdate;
public StudentInfo(){};
public StudentInfo(int rollNo, String name) {
this.rollNo = rollNo;
this.name = name;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthdate() {
return birthdate;
}
public void setBirthdate(Date birthdate) {
this.birthdate = birthdate;
}
}
但是它给我一个错误:
造成原因:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
列“ birth_date”不能为空
为什么呢?非常感谢你!
最佳答案
您实例化student2
,然后再次在student
上设置所有属性,这意味着student2
的属性永远不会被设置并且不会使数据库约束失效。设置student2
的属性,就可以了。
StudentInfo student = new StudentInfo();
student.setRollNo(1);
student.setName("Jo");
student.setBirthdate(new Date());
StudentInfo student2 = new StudentInfo();
student.setRollNo(2); # this isn't student2
student.setName("JC"); # this isn't student2
student.setBirthdate(new Date()); # this isn't student2