Jpa的@Id和@GeneratedValue的使用

@Id和@GeneratedValue的使用

文章内容来自于:https://blog.csdn.net/rickesy/article/details/50788161,作者:Rickesy
文章主要用于自己学习SpringBoot,方便以后的查询

@Id:

  • @Id 语句之前,可与声明语句同行,也可写在单独行上。
  • @Id标注也可置于属性的getter方法之前。

@GeneratedValue:

  • @GeneratedValue 用于标注主键的生成策略,通过strategy 属性指定。默认情况下,JPA 自动选择一个最适合底层数据库的主键生成策略:SqlServer对应identity,MySQL 对应 auto increment。
    在javax.persistence.GenerationType中定义了以下几种可供选择的策略:

    • – IDENTITY:采用数据库ID自增长的方式来自增主键字段,Oracle 不支持这种方式;
    • –AUTO: JPA自动选择合适的策略,是默认选项;
    • –SEQUENCE:通过序列产生主键,通过@SequenceGenerator 注解指定序列名,MySql不支持这种方式
    • –TABLE:通过表产生主键,框架借由表模拟序列产生主键,使用该策略可以使应用更易于数据库移植。
@Entity(name = "user")
public class User {

    @Id
    @GeneratedValue
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private Integer age;


    //省略getter、setter、构造方法

@Entity默认会将实体类首字母小写,如果需要修改,则需要添加@Entity(name="entity name")进行自定义。

猜你喜欢

转载自blog.csdn.net/chimmhuang/article/details/80460311