在Hibernate里遇到Mysql的datetime类型怎么搞
2015-05-29 13:43
591 查看
情景:有一个叫Person类的JavaBean,有个birth属性,类型为java.util.Date,而且要设置Mysql数据库得有一个birth字段且类型为datetime(Mysql的datetime类型的日期格式:YYYY-MM-DD HH:MM:SS ),怎么搞?
第一步:要在Person.hbm.xml文件为这birthday属性配置,代码片段如下:
<property name="birth" type="timestamp">
<column name="birth"></column>
</property>
注意:<property...>标签的type属性要设置为timestamp
第二步:.......省略.......代码片段如下:
@Test
public void add(){
Configuration config = new Configuration();
config.configure();
SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
Person person = new Person();
person.setName("abc");
SimpleDateFormat ss = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String dateStr = "2002-07-11 11:27:13";
try {
Date date = ss.parse(dateStr);
person.setBirth(date);
} catch (ParseException e) {
e.printStackTrace();
}
session.save(person);
tx.commit();
session.close();
}
junit运行一下,然后用desc Person命令查看一下Person表的结构:
眼神好的小伙伴们第一眼就能发现birth字段已经是datetime类型了
总结:…………
温馨提示:我第一次把Person.hbm.xml文件的<property...>标签的type属性要设置为date,结果到数据库一查,发现person表的birth字段是date类型(Mysql的date类型的日期格式:YYYY-MM-DD),木有了时间部分的内容,然后我浅浅一笑,把type的属性值改为timestamp,达到了想要的效果
第一步:要在Person.hbm.xml文件为这birthday属性配置,代码片段如下:
<property name="birth" type="timestamp">
<column name="birth"></column>
</property>
注意:<property...>标签的type属性要设置为timestamp
第二步:.......省略.......代码片段如下:
@Test
public void add(){
Configuration config = new Configuration();
config.configure();
SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
Person person = new Person();
person.setName("abc");
SimpleDateFormat ss = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String dateStr = "2002-07-11 11:27:13";
try {
Date date = ss.parse(dateStr);
person.setBirth(date);
} catch (ParseException e) {
e.printStackTrace();
}
session.save(person);
tx.commit();
session.close();
}
junit运行一下,然后用desc Person命令查看一下Person表的结构:
眼神好的小伙伴们第一眼就能发现birth字段已经是datetime类型了
总结:…………
温馨提示:我第一次把Person.hbm.xml文件的<property...>标签的type属性要设置为date,结果到数据库一查,发现person表的birth字段是date类型(Mysql的date类型的日期格式:YYYY-MM-DD),木有了时间部分的内容,然后我浅浅一笑,把type的属性值改为timestamp,达到了想要的效果
相关文章推荐
- 在 MySQL 中查找含有目标字段的表
- MySQL实现SQLServer ROW_NUMBER() OVER ORDER BY
- MySQL视图的使用
- MySQL视图的使用
- MySQL Semisynchronous Replication介绍
- order by优化-mysql
- MySQL开发规范
- MySQL延迟关联性能优化方法
- (1)mysql优化之sql性能问题定位
- mysql联合查询更新数据库例子
- MySQL语句
- MySQL 加锁处理分析
- Win8安装MySQL程序出现2502、2503错误解决方法
- MySQL 5.7增强版Semisync Replication性能优化
- mysql: Cannot load from mysql.proc. The table is probably corrupted
- 遭遇一次MySQL猜解注入攻击
- MySQL Index Condition Pushdown(ICP)性能优化方法实例
- MySQL order by性能优化方法实例
- MySQL slave_net_timeout参数解决的一个集群问题案例
- 使用innodb_force_recovery解决MySQL崩溃无法重启问题