主鍵自增策略有問題
從一個異常說起
dao 層設(shè)置如下
@Table(name = "wxorder_product_category")
@Entity
@Data
public class ProductCategory{
@Id
@GeneratedValue
private Integer categoryId;
private String categoryName;
private Integer categoryType;
}
然后測試添加一條數(shù)據(jù)時蓖墅,拋出異常铣墨。
測試代碼
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductCategoryRepositoryTest{
@AutoWired
private ProductCategoryRepository repository;
@Test
public void saveTest(){
ProductCategory productCategory = new ProductCategory();
productCategory.setCategoryName("夏日甜品");
productCategory.setCategoryType(4);
repository.save(productCategory);
}
}
拋出的異常
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'portal.hibernate_sequence' doesn't exist
原因及解決方案
名稱 | 作用 |
---|---|
TABLE | 使用一個特定的數(shù)據(jù)庫表格來保存主鍵 |
SEQUENCE | 根據(jù)底層數(shù)據(jù)庫的序列來生成主鍵,條件是數(shù)據(jù)庫支持 |
IDENTITY | 主鍵由數(shù)據(jù)庫自動生成(主要是自動增長型) |
AUTO | 主鍵由程序控制 |
JPA 使用提供四種主鍵解決方案。
名稱 | 作用 |
---|---|
TABLE | 使用一個特定的數(shù)據(jù)庫表格來保存主鍵 |
SEQUENCE | 根據(jù)底層數(shù)據(jù)庫的序列來生成主鍵,條件是數(shù)據(jù)庫支持 |
IDENTITY | 主鍵由數(shù)據(jù)庫自動生成(主要是自動增長型) |
AUTO | 主鍵由程序控制 |
在指定主鍵時两芳,如果不指定主鍵的生成策略,默認為AUTO去枷。
@Id
相當于
@Id
@GenerateValue(strategy = GenerationType.AUTO)
也就是說怖辆,當表由Hibernate 創(chuàng)建時使用 AUTO
合適。
當表已存在并且設(shè)置主鍵auto_increment
時删顶,使用@GenerateValue(strategy = GenerationType.IDENTITY)