@DynamicInsert使用问题

在代码中,想让数据库中的一个字段在无数据插入时使用默认值
持久类代码如下

@Entity @Table(name = "dormitory") @DynamicInsert(true) @DynamicUpdate(true) public class Dormitory implements Serializable{ private int ID; private String adress; private Set students = new HashSet<>(); private int number; public Dormitory() { }public Dormitory(String adress, int number) { this.adress = adress; this.number = number; }public Dormitory(String adress) { this.adress = adress; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic public int getID() { return ID; }public void setID(int ID) { this.ID = ID; } @Column(name = "adress",nullable = false,length = 20) @Basic public String getAdress() { return adress; }public void setAdress(String adress) { this.adress = adress; } @OneToMany @JoinColumn(name = "dormitory_id") public Set getStudents() { return students; }public void setStudents(Set students) { this.students = students; } @Column(name = "number",columnDefinition = "INT default 4") @Basic public int getNumber() { return number; }public void setNumber(int number) { this.number = number; } }测试类如下
public class StuTest { @Test public void hello(){ Dormitory dormitory = new Dormitory("6#522"); DormitoryDao dormitoryDao = new DormitoryDao(HibernateUtils.getSessionFactory()); dormitoryDao.insertDormitory(dormitory); dormitoryDao.commit(); } }


输出的语句为
insert into dormitory (adress, number) values (?, ?)


这是因为持久化类中number属性用的是int,int未赋值时默认0,解决办法很简单,吧它改成Integer
修改后的持久化类
@Entity @Table(name = "dormitory") @DynamicInsert(true) @DynamicUpdate(true) public class Dormitory implements Serializable{ private int ID; private String adress; private Set students = new HashSet<>(); private Integer number; public Dormitory() { }public Dormitory(String adress, Integer number) { this.adress = adress; this.number = number; }public Dormitory(String adress) { this.adress = adress; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic public int getID() { return ID; }public void setID(int ID) { this.ID = ID; } @Column(name = "adress",nullable = false,length = 20) @Basic public String getAdress() { return adress; }public void setAdress(String adress) { this.adress = adress; } @OneToMany @JoinColumn(name = "dormitory_id") public Set getStudents() { return students; }public void setStudents(Set students) { this.students = students; } @Column(name = "number",columnDefinition = "INT default 4") @Basic public Integer getNumber() { return number; }public void setNumber(Integer number) { this.number = number; } }


依然使用上个测试

hibernate输出的SQL为
insert into dormitory (adress) values (?)


Integer是类,所以默认是null

【@DynamicInsert使用问题】

    推荐阅读