代码布局
使用Spring Data Jpa 框架操作MySql数据库时,写了一个Blog实体类,属性如下:
@Entity
public class Blog {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
private String title;
private String content;
@Temporal(TemporalType.DATE) // date (只有日期)
private Date createTime;
}
一个操作数据MySql数据库的接口:
public interface BlogService extends PagingAndSortingRepository {
Page findAll(Pageable pageable);
List findAll();
Blog findOne(Long id);
}
调用findAll()方法:
List blogs = blogService.findAll();
数据库表
执行结果
执行findAll()方法时发生异常:Unknown column 'blog0_.create_time' in 'field list'
查看了一下Hibernate生成的执行语句:
select blog0_.id as id1_0_, blog0_.content as content2_0_, blog0_.create_time as create_t3_0_, blog0_.title as title4_0_ from blog blog0
原来,我的createTime自动被转换成了create_time字段,即使在createTime字段上加上Column,name属性设置成createTime还是出现同样的错误。
由此推断,Hibernate在生成字段时,会将单词中间大写字母变成小写,并且中间加上下划线。
代码改成如下就没有问题了:
@Entity
public class Blog {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
private String title;
private String content;
@Temporal(TemporalType.DATE) // date (只有日期)
@Column()
private Date createtime;
}
或者将数据库的createTime字段改成create_time字段,也能解决问题。