數據表:
create table 'product_category'( 'category_id' int not null auto_increment, 'category_name' varchar(64) not null comment '類目名字', ......
domain:
@Entity public class ProductCategory { @Id @GeneratedValue private Integer categoryId; private String categoryName; private Integer categoryType; setter... getter...
Repository:
public interface ProductCategoryRepository extends JpaRepository<ProductCategory,Integer> { }
測試代碼:
@Test public void saveTest(){ ProductCategory productCategory = new ProductCategory(); productCategory.setCategoryName("測試b"); productCategory.setCategoryType(3); repository.save(productCategory); }
報錯:Caused by: java.sql.SQLSyntaxErrorException: Table 'sell.hibernate_sequence' doesn't exist
解決:在domain實體類指明主鍵生成策略,保持數據庫一致
@Entity public class ProductCategory { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer categoryId; private String categoryName; private Integer categoryType;
JPA四種生成策略了解下。
疑點:原文使用@GeneratedValue注解,即@GeneratedValue(strategy = GenerationType.AUTO),不是應該根據數據庫支持的主鍵生成策略自動選擇合適的嗎,數據庫中使用了auto_increment,為什么這邊沒有支持而報錯?