zoukankan      html  css  js  c++  java
  • jpa自定义sql语句

     /**
         * 查询还没生成索引的帖子
         * @return
         */
        @Query(value = "SELECT * FROM t_article WHERE index_state=0",nativeQuery = true)
        public List<Article> getArticleNoIndex();
    
        /**
         * 更改索引为true
         */
        @Transactional
        @Modifying
        @Query(value = "UPDATE t_article SET index_state = TRUE  WHERE id =?1",nativeQuery = true)
        public void updateArticleIndex(Integer id);

    简单例子:

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

    Like表达式:

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

    使用Native SQL Query(nativeQuery=true则使用原生SQL默认HQL)[/b][/color][/size]
    所谓本地查询,就是使用原生的sql语句(根据数据库的不同,在sql的语法或结构方面可能有所区别)进行查询数据库的操作

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

    使用@Param注解注入参数

    @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);

    SPEL表达式(使用时请参考最后的补充说明)[/b]
    '#{#entityName}'值为'Book'对象对应的数据表名称(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);
    
    }

    注:

    1)update或delete时必须使用@Modifying和@Transactional对方法进行注解,才能使得ORM知道现在要执行的是写操作

    2)有时候不加@Param注解参数,可能会报如下异常:

    org.springframework.dao.InvalidDataAccessApiUsageException: Name must not be null or empty!; nested exception is java.lang.IllegalArgumentException: Name must not be null or empty!

    3)当使用集合作为条件时,可参考此处的ids

    @Transactional
    @Modifying
    @Query("update ShopCoupon sc set sc.deleted = true where sc.id in :ids")
    public void deleteByIds(@Param(value = "ids") List<String> ids);

    摘自其他文章,如有侵权,请立即联系我

  • 相关阅读:
    HA: Chakravyuh Vulnhub Walkthrough
    HA Rudra: Vulnhub Walkthrough
    关于Fastjson 1.2.24 反序列化导致任意命令执行漏洞
    关于MySQL注入漏洞到获取webshell
    Windows宏病毒利用
    常规高危端口
    HA Joker Vulnhub Walkthrough
    面试题:对Vue的响应式数据/双向数据绑定原理的理解
    面试题: 对MVVN的理解
    面试题:localStorage、sessionStorage、Cookie的区别详解
  • 原文地址:https://www.cnblogs.com/share-record/p/12262127.html
Copyright © 2011-2022 走看看