1. 程式人生 > >SpringBoot使用Jpa連線資料庫

SpringBoot使用Jpa連線資料庫

目錄

1、springboots使用Jpa連線資料需要的依賴:

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

<!-- Mysql依賴 -->
 <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
     <scope>runtime</scope>
 </dependency>

2、建立實體Bean

@Entity
@Table(name="t_user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column
    private int age;

    @Column
    private int sex;

    @Column
    private String address;

    省略get...set方法
  • @Entity:表明是一個實體Bean
  • @Table:自定義表名
  • @Id:標明主鍵
  • @GeneratedValue:主鍵自增,使用該註解在建立bi表的時候會同步建立一個hibernate-sequence表來記錄下一個主鍵
  • @Column:定義列,可以自定義列名,指定列的型別以及一些約束

3、建立一個Repository

建立的所有的Repository都要繼承JpaRepository,因為JpaRepository中已經給我們封裝一系列的增刪改查方法

public interface UserRepository extends JpaRepository<User,Long> {

    User findByName(String name);

    User findByNameAndAge(String name,int age);

    @Query(value = "select * from t_user t where t.id =?1",nativeQuery = true)
    User findUserForSql(Long id);

    @Query(value = "select t from User t where t.id =?1")
    User findUserForHql(Long id);

    @Query(value = "select t from User t where t.id = :id")
    User findUserForHql2(@Param("id")Long id);

    @Modifying
    @Query(value = "delete from User where id = ?1")
    void deleteUser(Long id);

    @Modifying
    @Query(value = "update User set name = ?1 where id = ?2")
    void updateUser(String name,Long id);
    
}

4、配置連線資料庫的配置檔案

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/test?useSSL=false
    username: root
    password: ****
    driver-class-name: com.mysql.jdbc.Driver
  jpa:
    database: mysql
    show-sql: true
    hibernate:
      ddl-auto: update

以上就完成了springboot使用jpa連線資料庫的基本操作