- 问题场景
在用Hibernate过程中,MySQL数据库中datetime属性字段,设置默认值为0000-00-00 00:00:00,not null。 - 解决办法
在用bean插入数据时无法设置Date类型的时间为0000-00-00 00:00:00,并且对象属性默认为null,无法执行保存。考虑用数据库中的默认值来实现插入时的字段值设置。
用到Hibernate的注解@DynamicInsert(true)和@DynamicUpdate(true)
user table
id | int |
---|---|
name | varchar |
joindate | datetime |
user bean
@Entity
@DynamicInsert(true)
@DynamicUpdate(true)
@Table(name = "user")
public class MyUserBo implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GenericGenerator(name = "idGenerator", strategy = "increment")
@GeneratedValue(generator = "idGenerator")
private int id;
@Column(name = "name")
private String name;
@Column(name = "joindate")
private Date joinDate;
......
Test
@Test
public void foo() {
MyUserBo user = new MyUserBo();
user.setName("张三");
serverService.save(user);
MyUserBo user2 = new MyUserBo();
user2.setName("李四");
user2.setJoinDate(new Date());
serverService.save(user2);
MyUserBo userBo = serverService.find(MyUserBo.class, 2);
System.out.println(userBo);
userBo.setName("王五");
serverService.save(userBo);
}
result
Hibernate: select max(id) from my_user
Hibernate: insert into my_user (name, id) values (?, ?)
Hibernate: insert into my_user (joindate, name, id) values (?, ?, ?)
Hibernate: select myuserbo0_.id as id1_3_0_, myuserbo0_.joindate as joindate2_3_0_, myuserbo0_.name as name3_3_0_ from my_user myuserbo0_ where myuserbo0_.id=?
MyUserBo [id=1, name=张三, joinDate=null]
Hibernate: select myuserbo0_.id as id1_3_0_, myuserbo0_.joindate as joindate2_3_0_, myuserbo0_.name as name3_3_0_ from my_user myuserbo0_ where myuserbo0_.id=?
Hibernate: update my_user set name=? where id=?