JPA注解@GeneratedValue的理解---------使用JPA插入数据失败,Hibernate输出 select next_val as id_val from hibernate_sequence for update

  使用JPA插入数据

   实体类代码:

@Entity
@Table(name = "product_category")
public class ProductCategory {
    /**
     * 类目id.
     */
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer categoryId;
    /**
     * 类目名字.
     */
    private String categoryName;
    /**
     * 类目编号.
     */
    private Integer categoryType;
   // ...get set省略
}
测试代码:
@Test
public void saveTest01(){ ProductCategory productCategory = new ProductCategory(); productCategory.setCategoryName("过期商品111"); productCategory.setCategoryType(3); productCategoryDao.save(productCategory); }

出现com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'O2O.hibernate_sequence' doesn't exist错误,Hibernate输出语句为 select next_val as id_val from hibernate_sequence for update。

demo中获取数据库列表是没有问题的,进行数据修改增加就出现问题,经过排查发现是因为JPA注解@GeneratedValue主键策略选错了。

public enum GenerationType{    
    TABLE,    //使用一个特定的数据库表格来保存主键。
    SEQUENCE,    //根据底层数据库的序列来生成主键,条件是数据库支持序列。
    IDENTITY,    //主键由数据库自动生成(主要是自动增长型)
    AUTO   //主键由程序控制
}  

@GeneratedValue总共有四种策略,当数据表主键id设置为自增时,并不是选择 

@GeneratedValue(strategy = GenerationType.AUTO)

而是选择

@GeneratedValue(strategy = GenerationType.IDENTITY)

@GeneratedValue属性介绍参考文章https://blog.csdn.net/canot/article/details/51455967

这样数据就能插入了。

猜你喜欢

转载自www.cnblogs.com/app3306/p/9176575.html