Spring Data JPA 入門使用

官方的實例,加本身的小總結:

關鍵字

The following table describes the keywords supported for JPA and what a method containing that keyword translates to:java

下表描述了JPA支持的關鍵字以及包含該關鍵字的方法:sql

使用開始

#JPA 2 introduces a criteria API that you can use to build queries programmatically.
# JpaSpecificationExecutor用來構建動態查詢
public interface UserRepository extends JpaRepository<User, Long>,JpaSpecificationExecutor<User> {

  List<User> findByLastname(String lastname);

  User findByEmailAddress(String emailAddress);
}
複製代碼
使用 @Query 手動定義查詢,查詢返回結果須要是一個對象,不能使用 *
public interface UserRepository extends JpaRepository<User, Long> {
  @Query("select u from User u where u.emailAddress = ?1")
  User findByEmailAddress(String emailAddress);
}
複製代碼
public interface UserRepository extends JpaRepository<User, Long> {
 // 使用nativeQuery =ture  能夠標識該sql是原生的sql查詢,
  @Query(value = "SELECT * FROM USERS WHERE EMAIL_ADDRESS = ?1", nativeQuery = true)
  User findByEmailAddress(String emailAddress);
}
複製代碼

JPA 分頁對象

public interface UserRepository extends JpaRepository<User, Long> {

  @Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1",
    countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
    nativeQuery = true)
  Page<User> findByLastname(String lastname, Pageable pageable);
}
#——————————————————————
#Pageable對象是分頁構造對象,用來傳入page,size,Sort
  # Sort.Direction.DESC 排序規則
  # "id" 排序 字段
  Sort sort=new Sort(Sort.Direction.DESC,"id");
  Page<User>  UserPage=UserDao.findByLastname(lastname,new PageRequest(0,10,sort));
複製代碼

自定義查詢中調用排序

public interface UserRepository extends JpaRepository<User, Long> {

  @Query("select u from User u where u.lastname like ?1%")
  List<User> findByAndSort(String lastname, Sort sort);

}

#_____________
    測試:

        String lastname="白";
        List<User> users= userDao.findByAndSort(lastname,new Sort(Sort.Direction.DESC,"id"));
        for (User a: users) {
            System.out.println(a);
        }

複製代碼

Jpa默認使用位置?1,給自定義sql中的參數傳值,也能夠使用參數名稱傳值

By default, Spring Data JPA uses position-based parameter binding, as described in all the preceding examples. This makes query methods a little error-prone when refactoring regarding the parameter position. To solve this issue, you can use @Param annotation to give a method parameter a concrete name and bind the name in the query, as shown in the following example:數據庫

public interface UserRepository extends JpaRepository<User, Long> {
  @Query("select u from User u where u.firstname = :firstname or u.lastname = :lastname")
  User findByLastnameOrFirstname(@Param("lastname") String lastname, @Param("firstname") String firstname);
}
複製代碼

註釋

  1. @Entity 實體類標識
  2. @Table ( name ="user" ) 代表映射
  3. @Id id 標識
  4. @GeneratedValue(strategy=GenerationType.AUTO)||@GeneratedValue(strategy=GenerationType.IDENTITY) 主鍵自增
  5. @Column(name = "song_id" ) 跟表字段的映射
  6. @Transient 忽略字段和數據庫對應

增,刪,改

# 對
    @Modifying
    @Query(value = "update User set User.title=?1 where User.id=?2",nativeQuery = true)
    int setTitle(String title,Integer id);
    
    調用時須要在方法上添加事務註解
    @Test
    @Transactional
    public  void index4_3(){
        String title="白居易";
        int count  =wangyiyunDao.setTitle(title,823);
        System.out.println("成功修改了"+count+"條");
    }
    
    
   <!--______________錯誤_____________________-->
    # 錯
    #@Query(value = "update Wangyiyun set Wangyiyun.title=?1 where Wangyiyun.id=?2",nativeQuery = true)
    #int setTitle2(String title,Integer id);

    # 錯
    #@Modifying
    #@Query(value = "update Wangyiyun set Wangyiyun.title=?1 where Wangyiyun.id=?2")
    #int setTitle3(String title,Integer id);

複製代碼

其餘

Its usage is select x from #{#entityName} x. It inserts the entityName of the domain type associated with the given repository. 它的用法是從#{#entityName} x中選擇x。它插入與給定存儲庫關聯的域類型的entityName。 The entityName is resolved as follows: If the domain type has set the name property on the @Entity annotation, it is used. entityName解析以下:若是域類型在@Entity註釋上設置了name屬性,則使用它。bash

public interface UserRepository extends JpaRepository<User,Long> {

 // #{#entityName} 至關於 User
 // 既 當前

  @Query("select u from #{#entityName} u where u.lastname = ?1")
  List<User> findByLastname(String lastname);
}
複製代碼
相關文章
相關標籤/搜索