最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringData如何通過@Query注解支持JPA語句和原生SQL語句

 更新時間:2021年11月25日 16:13:59   作者:qq_36722039  
這篇文章主要介紹了SpringData如何通過@Query注解支持JPA語句和原生SQL語句,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

通過@Query注解支持JPA語句和原生SQL語句

在SpringData中們可是使用繼承接口直接按照規(guī)則寫方法名即可完成查詢的方法,不需要寫具體的實現(xiàn),但是這樣寫又是不能滿足我們的需求,比如子查詢,SpringData中提供了@Query注解可以讓我們寫JPA的語句和原生的SQL語句,那接下來看看怎么寫JPA的查詢語句和原生的SQL語句。

package com.springdata.study.repository; 
import java.util.List; 
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param; 
import com.springdata.study.entitys.Person;
 
//1.實際上Repository是一個口接口,沒有提供任何方法,是一個標記接口
//2.實現(xiàn)了Repository接口就會被spring IOC容器識別為Repository Bean
//  會被納入IOC容器中
//3.Repository接口也可以同@RepositoryDefinition 注解代替,效果是一樣的
//4.接口中的泛型:第一個是那個實體類的Repository,第二個是實體類的主鍵的類型
//@RepositoryDefinition(domainClass=Person.class,idClass=Integer.class)
 
/**
 * 在Repository接口中申明方法 1.申明方法需要符合一定的規(guī)范 2.查詢方法需要以 find | read | get開頭 3.涉及查詢條件時
 * 需要用條件關鍵字連接 4.屬性首字母大寫 5.支持級聯(lián)屬性
 * 6.AddressId若當前實體類中有屬性,則優(yōu)先使用該屬性,若想要使用級聯(lián)屬性,需要用下劃線隔開Address_Id
 */ 
public interface PersonRepositoiry extends Repository<Person, Integer> {
 // select p from Person where p.name = ?
 Person getByName(String name);
 
 List<Person> findByNameStartingWithAndIdLessThan(String name, Integer id);
 
 // where name like %? and id < ?
 List<Person> findByNameEndingWithAndIdLessThan(String name, Integer id);
 
 // where email in ? age < ?
 List<Person> readByEmailInOrAgeLessThan(List<String> emails, int age);
 
 // 級聯(lián)屬性查詢
 // where address.id > ?
 List<Person> findByAddress_IdGreaterThan(Integer is);
 
 // 可以使用@Query注解在其value屬性中寫JPA語句靈活查詢
 @Query("SELECT p FROM Person p WHERE p.id = (SELECT max(p2.id) FROM Person p2)")
 Person getMaxIdPerson();
 
 // 在@Query注解中使用占位符
 @Query(value = "SELECT p FROM Person p where p.name = ?1 and p.email = ?2")
 List<Person> queryAnnotationParam1(String name, String email);
 
 // 使用命名參數(shù)傳遞參數(shù)
 @Query(value = "SELECT p FROM Person p where p.name = :name")
 List<Person> queryAnnotationParam2(@Param("name") String name);
 
 // SpringData可以在參數(shù)上添加%
 @Query("SELECT p FROM Person p WHERE p.name LIKE %?1%")
 List<Person> queryAnnotationLikeParam(String name);
 
 // SpringData可以在參數(shù)上添加%
 @Query("SELECT p FROM Person p WHERE p.name LIKE %:name%")
 List<Person> queryAnnotationLikeParam2(@Param("name")String name);
 
 //在@Query注解中添加nativeQuery=true屬性可以使用原生的SQL查詢
 @Query(value="SELECT count(*) FROM jpa_person", nativeQuery=true)
 long getTotalRow(); 
}

下面是這個類的測試類

package com.springdata.study.test; 
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List; 
import javax.sql.DataSource; 
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.springdata.study.entitys.Person;
import com.springdata.study.repository.PersonRepositoiry;
import com.springdata.study.service.PersonService;
 
public class DataSourceTest { 
 private ApplicationContext applicationContext;
 private PersonService personService;
 private PersonRepositoiry personRepositoiry;
 
 {
  applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  personRepositoiry = applicationContext.getBean(PersonRepositoiry.class);
  personService = applicationContext.getBean(PersonService.class);
 }
 
 @SuppressWarnings("resource")
 @Test
 public void testDataSource() throws SQLException {
  ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  DataSource dataSource = applicationContext.getBean(DataSource.class);
  System.out.println(dataSource.getConnection());
 }
 
 @Test
 public void testSpringdata() {
  Object person = personService.getPerson("LQF");
  System.out.println(person);
 }
 
 @Test
 public void testFindByNameStartingWithAndIdLessThan() {
  List<Person> persons = personRepositoiry.findByNameStartingWithAndIdLessThan("g", 6);
  persons = personRepositoiry.findByNameEndingWithAndIdLessThan("g", 6);
  System.out.println(persons);
 }
 
 @Test
 public void testReadByEmailInOrAgeLessThan() {
  List<Person> persons = personRepositoiry.readByEmailInOrAgeLessThan(Arrays.asList("123@qq.com"), 25);
  System.out.println(persons);
 }
 
 @Test
 public void testFindByAddressIdGreaterThan() {
  personRepositoiry.findByAddress_IdGreaterThan(1);
 }
 
 @Test
 public void testGetMaxIdPerson() {
  Person person = personRepositoiry.getMaxIdPerson();
  System.out.println(person);
 }
 
 @Test
 public void testQueryAnnotationParam() {
  List<Person> persons = personRepositoiry.queryAnnotationParam1("liqingfeng", "123@qq.com");
  System.out.println(persons);
 }
 
 @Test
 public void testQueryAnnotationParam2() {
  List<Person> persons = personRepositoiry.queryAnnotationParam2("lqf");
  System.out.println(persons);
 }
 
 @Test
 public void testQueryAnnotationLikeParam() {
  List<Person> persons = personRepositoiry.queryAnnotationLikeParam2("li");
  System.out.println(persons);
 }
 
 @Test
 public void testGetTotalRow() {
  long count = personRepositoiry.getTotalRow();
  System.out.println(count);
 } 
}

@Query注解的用法(Spring Data JPA)

1.一個使用@Query注解的簡單例子

@Query(value = "select name,author,price from Book b where b.price>?1 and b.price<?2")
List<Book> findByPriceRange(long price1, long price2);

2.Like表達式

@Query(value = "select name,author,price from Book b where b.name like %:name%")
List<Book> findByNameMatch(@Param("name") String name);

3.使用Native SQL Query

所謂本地查詢,就是使用原生的sql語句(根據(jù)數(shù)據(jù)庫的不同,在sql的語法或結構方面可能有所區(qū)別)進行查詢數(shù)據(jù)庫的操作。

@Query(value = "select * from book b where b.name=?1", nativeQuery = true)
List<Book> findByName(String name);

4.使用@Param注解注入?yún)?shù)

@Query(value = "select name,author,price from Book b where b.name = :name AND b.author=:author AND b.price=:price")
List<Book> findByNamedParam(@Param("name") String name, @Param("author") String author,
        @Param("price") long price);

5.SPEL表達式(使用時請參考最后的補充說明)

'#{#entityName}'值為'Book'對象對應的數(shù)據(jù)表名稱(book)。

public interface BookQueryRepositoryExample extends Repository<Book, Long>{
       @Query(value = "select * from #{#entityName} b where b.name=?1", nativeQuery = true)
       List<Book> findByName(String name);
}

6.一個較完整的例子

public interface BookQueryRepositoryExample extends Repository<Book, Long> {
    @Query(value = "select * from Book b where b.name=?1", nativeQuery = true) 
    List<Book> findByName(String name);// 此方法sql將會報錯(java.lang.IllegalArgumentException),看出原因了嗎,若沒看出來,請看下一個例子
    @Query(value = "select name,author,price from Book b where b.price>?1 and b.price<?2")
    List<Book> findByPriceRange(long price1, long price2);
    @Query(value = "select name,author,price from Book b where b.name like %:name%")
    List<Book> findByNameMatch(@Param("name") String name);
    @Query(value = "select name,author,price from Book b where b.name = :name AND b.author=:author AND b.price=:price")
    List<Book> findByNamedParam(@Param("name") String name, @Param("author") String author,
            @Param("price") long price);
}

7.解釋例6中錯誤的原因

因為指定了nativeQuery = true,即使用原生的sql語句查詢。使用java對象'Book'作為表名來查自然是不對的。只需將Book替換為表名book。

@Query(value = "select * from book b where b.name=?1", nativeQuery = true)
List<Book> findByName(String name);

補充說明:

有同學提出來了,例子5中用'#{#entityName}'為啥取不到值?。?/p>

先來說一說'#{#entityName}'到底是個啥。從字面來看,'#{#entityName}'不就是實體類的名稱么,對,他就是。

實體類Book,使用@Entity注解后,spring會將實體類Book納入管理。默認'#{#entityName}'的值就是'Book'。

但是如果使用了@Entity(name = "book")來注解實體類Book,此時'#{#entityName}'的值就變成了'book'。

到此,事情就明了了,只需要在用@Entity來注解實體類時指定name為此實體類對應的表名。在原生sql語句中,就可以把'#{#entityName}'來作為數(shù)據(jù)表名使用。

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • springboot整合cxf發(fā)布webservice以及調用的方法

    springboot整合cxf發(fā)布webservice以及調用的方法

    這篇文章主要介紹了springboot整合cxf發(fā)布webservice以及調用的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-08-08
  • Java 操作Properties配置文件詳解

    Java 操作Properties配置文件詳解

    這篇文章主要介紹了Java 操作Properties配置文件詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-07-07
  • 解決Springboot項目報錯:java:錯誤:不支持發(fā)行版本?17

    解決Springboot項目報錯:java:錯誤:不支持發(fā)行版本?17

    這篇文章主要給大家介紹了關于解決Springboot項目報錯:java:錯誤:不支持發(fā)行版本17的相關資料,這個錯誤意味著你的Spring Boot項目正在使用Java 17這個版本,但是你的項目中未配置正確的Java版本,需要的朋友可以參考下
    2023-08-08
  • Java中ThreadLocal的使用

    Java中ThreadLocal的使用

    這篇文章主要介紹了Java中ThreadLocal的使用,靜態(tài)內部類的加載是在程序中調用靜態(tài)內部類的時候加載的,和外部類的加載沒有必然關系, 但是在加載靜態(tài)內部類的時候 發(fā)現(xiàn)外部類還沒有加載,那么就會先加載外部類 ,加載完外部類之后,再加載靜態(tài)內部類,需要的朋友可以參考下
    2023-09-09
  • Java 實例解析單例模式

    Java 實例解析單例模式

    單例模式(Singleton Pattern)是 Java 中最簡單的設計模式之一。這種類型的設計模式屬于創(chuàng)建型模式,它提供了一種創(chuàng)建對象的最佳方式,這種模式涉及到一個單一的類,該類負責創(chuàng)建自己的對象,同時確保只有單個對象被創(chuàng)建
    2021-11-11
  • SpringMVC 中配置 Swagger 插件的教程(分享)

    SpringMVC 中配置 Swagger 插件的教程(分享)

    下面小編就為大家分享一篇SpringMVC 中配置 Swagger 插件的教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2017-12-12
  • Java上傳下載文件并實現(xiàn)加密解密

    Java上傳下載文件并實現(xiàn)加密解密

    這篇文章主要介紹了Java上傳下載文件并實現(xiàn)加密解密,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-04-04
  • SpringBoot項目在IntelliJ IDEA中如何實現(xiàn)熱部署

    SpringBoot項目在IntelliJ IDEA中如何實現(xiàn)熱部署

    spring-boot-devtools是一個為開發(fā)者服務的一個模塊,其中最重要的功能就是自動應用代碼更改到最新的App上面去。,這篇文章主要介紹了SpringBoot項目在IntelliJ IDEA中如何實現(xiàn)熱部署,感興趣的小伙伴們可以參考一下
    2018-07-07
  • SSH框架網(wǎng)上商城項目第8戰(zhàn)之查詢和刪除商品類別功能實現(xiàn)

    SSH框架網(wǎng)上商城項目第8戰(zhàn)之查詢和刪除商品類別功能實現(xiàn)

    SSH框架網(wǎng)上商城項目第8戰(zhàn)之查詢和刪除商品類別功能實現(xiàn),為項目增加功能,添加、更新、刪除和查詢操作,感興趣的小伙伴們可以參考一下
    2016-05-05
  • Spring Boot修改內置Tomcat默認端口號的示例

    Spring Boot修改內置Tomcat默認端口號的示例

    本篇文章主要介紹了Spring Boot修改內置Tomcat端口號的示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-08-08

最新評論

阳原县| 建宁县| 仙居县| 湘阴县| 青州市| 扬州市| 元谋县| 瓦房店市| 深泽县| 杭州市| 塔城市| 田阳县| 台江县| 博野县| 铁岭县| 偏关县| 额尔古纳市| 清水县| 南投市| 洱源县| 深泽县| 苍南县| 吉林省| 安阳市| 安达市| 中西区| 封开县| 贵溪市| 福鼎市| 卓资县| 阿克苏市| 独山县| 长丰县| 武夷山市| 乐昌市| 平乡县| 绥江县| 交口县| 宝兴县| 侯马市| 克拉玛依市|