SpringBoot集成JPA配置实体类自动创建表

  牢记检查以下四步,我们就可以通过注解的形式配置实体类,来自动创建数据库表。

 1. pom.xml中引入jpa的包

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

2. 配置文件application.yml

spring:
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: update  #必须要有(如果没有,即使启动项目,也不会生成相应的表)

3. 编写实体类(添加对应注解

@Entity
@Table(name = "t_user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    @NotNull(message = "用户名不能为空")
    @Column(length = 30)
    private String username;
    @Column(length = 200)
    private String password;
    @NotNull(message = "真实姓名不能为空")
    @Column(length = 200)
    private String trueName; //真实姓名

    @ManyToOne
    @JoinColumn(name = "roleId")
    private Role role; //角色

    @Column(length = 200)
    private String remark;

    @NotNull(message = "排序号不能为空")
    @Column(length = 10)
    private Integer orderNo;

    @Temporal(TemporalType.TIMESTAMP)
    private Date createDateTime; //创建时间
    @Temporal(TemporalType.TIMESTAMP)
    private Date updateDateTime; //修改时间

    ……
    …… 
    //省略setter和getter方法以及toString方法

}

4. 在项目的启动类Application中添加MapperScan注解

@SpringBootApplication
@MapperScan("zqq.trys.model")
public class TesthttpApplication {

    public static void main(String[] args) {
        SpringApplication.run(TesthttpApplication.class, args);
    }

}

注意:zqq.trys.model这个包是实体类所在包。

发布了83 篇原创文章 · 获赞 63 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/zqq_2016/article/details/104971858
今日推荐