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