springDataJpa——Sql查询

  • Post author:
  • Post category:其他




springDataJpa——Sql查询



一、环境搭建

springDataJpa的环境搭建在上篇已经讲到,这篇中所使用的entity与下面这个链接一致,这里不再赘述。

springDataJpa环境搭建



二、Dao层

package com.xsl.dao;
import com.xsl.entity.UserEntity;
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;

public interface UserDao extends JpaRepository<UserEntity,Long>, JpaSpecificationExecutor<UserEntity> {

    /**
     * sql查询
     * nativeQuery = true为sql查询,false为jpql查询,默认为false
     * 如果有多个参数规则与jpql一致
     */
    @Query(value = "select * from user", nativeQuery = true)
    public List<Object[]> findAll1();
}



三、测试

package com.xsl.test;

import com.xsl.dao.UserDao;
import com.xsl.entity.UserEntity;
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.Arrays;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SqlTest {
    @Autowired
    private UserDao userDao;

    @Test
    public void findAll1(){
        List<Object[]> all1 = userDao.findAll1();
        for (Object[] obj : all1) {
            System.out.println(Arrays.toString(obj));
        }
    }

}



版权声明:本文为qq_44132240原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。