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這個包是實體類所在包。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章