首页 > 数据库技术 > 详细

spring data jpa 使用SQL语句查询

时间:2019-12-08 10:51:05      阅读:439      评论:0      收藏:0      [点我收藏+]
package com.ytkj.dao;

import com.ytkj.entity.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * JpaRepository<实体类类型,主键类型>:用来完成基本CRUD操作
 * JpaSpecificationExecutor<实体类类型>:用于复杂查询(分页等查询操作)
 */
public interface CustomerDao2 extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<Customer> {
    /**
     * 使用sql查询
     * nativeQuery = true:使用sql查询
     * nativeQuery = false:使用jpql查询,默认就是false
     */
    @Query(value = "select  * from cst_customer",nativeQuery = true)
    List<Customer> findAll();

    /**
     * 使用sql条件查询
     *  占位符
     *      方法参数顺序尽量和占位符位置一样
     * nativeQuery = true:使用sql查询
     * nativeQuery = false:使用jpql查询,默认就是false
     */
    @Query(value = "select  * from cst_customer where cust_name=? ",nativeQuery = true)
    Customer findByName(String name);

}

  

import com.ytkj.dao.CustomerDao2;
import com.ytkj.entity.Customer;
import jdk.nashorn.internal.parser.Lexer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)//声明spring提供的单元测试环境
@ContextConfiguration(locations = "classpath:applicationContext.xml")//指定spring容器的配置信息
public class SpringdatajpaSqlTest {

    @Autowired
    CustomerDao2 customerDao2;
    @Test
    public  void  findAll(){
        List<Customer> list = customerDao2.findAll();
        for (int i=0;i<list.size();i++){
            Customer customer = list.get(i);
            System.out.println(customer);
        }
    }

    @Test
    public void findByName(){
        Customer customer = customerDao2.findByName("中国人");
        System.out.println(customer);
    }
}

 

spring data jpa 使用SQL语句查询

原文:https://www.cnblogs.com/yscec/p/12004164.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!