spring data jpa 无法自动创建表
问题描述
在spring配置文件applicationContext.xml中,配置了hibernate是否自动创建表。但是在运行测试案例时,无法创建表。其他地方配置无误。
<!-- 注入jpa的配置信息,就是把jpa单独配置时的某些信息,加到spring配置中来
配置jpa实现方(hibernate)的配置信息
hibernate.hbm2ddl.auto 自动创建数据库表:
create: 程序运行时创建数据库表(如果有表,先删除再创建表)
update: 程序运行时创建表(如果有表,不会创建表)
none: 不会创建表
-->
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
测试代码
/**
* 保存
* 保存一个客户,一个联系人,并建立关系
*/
@Test
@Transactional
@Rollback(false)
public void testAdd(){
LinkMan linkMan = new LinkMan();
linkMan.setLkmName("小李");
Customer customer = new Customer();
customer.setCustName("海大");
customerDao.save(customer);
linkManDao.save(linkMan);
}
报错
Hibernate: drop table if exists cst_customer
Hibernate: drop table if exists cst_linkman
Hibernate: create table cst_customer (cust_id bigint not null auto_increment, cust_address varchar(255), cust_industry varchar(255), cust_level varchar(255), cust_name varchar(255), cust_phone varchar(255), cust_source varchar(255), primary key (cust_id)) type=MyISAM
Hibernate: create table cst_linkman (lkm_id bigint not null auto_increment, lkm_email varchar(255), lkm_gender varchar(255), lkm_memo varchar(255), lkm_mobile varchar(255), lkm_name varchar(255), lkm_phone varchar(255), lkm_position varchar(255), lkm_cust_id bigint, primary key (lkm_id)) type=MyISAM
Hibernate: alter table cst_linkman add constraint FKh9yp1nql5227xxcopuxqx2e7q foreign key (lkm_cust_id) references cst_customer (cust_id)
Hibernate: insert into cst_customer (cust_address, cust_industry, cust_level, cust_name, cust_phone, cust_source) values (?, ?, ?, ?, ?, ?)
org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute statement
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:279)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:253)
...
解决方法
参考:https://www.codeleading.com/article/24801050615/
错误提示只显示hibernate异常,经过查询网上资料,不使用spring data jpa,只用hibernate时也有这种问题。
应该是mysql版本的问题
这里是因为我的数据库版本是MySQL8.0.16,而新版MySQL不支持type=MyISAM的写法,而是用engine=MyISAM替代了
解决方法:
将<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
中的数据库方言从原来的org.hibernate.dialect.MySQLDialect改为org.hibernate.dialect.MySQL5Dialect。