SpringBoot中JPA使用动态SQL查询

https://www.jianshu.com/p/f72d82e90948

 

可以重点关注方法二,把原生sql传入数据库去查询

好处是:更加灵活
坏处是:拼接sql比较痛苦,也容易出问题,比如拼接的sql某些字段不存在或者拼接后语法不符合sql语句

package com.aircas.satellitemanagement.jpa;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    LocalContainerEntityManagerFactoryBean entityManagerFactory;

    @GetMapping(value = "/all/4")
    public List<User> exec() {
        EntityManager em = entityManagerFactory.getNativeEntityManagerFactory().createEntityManager();
        StringBuilder sqljoint = new StringBuilder(300);
        sqljoint.append("SELECT * FROM user");
        String sql = sqljoint.toString();
        em.getTransaction().begin();
// User是我自己定义的entity bean Query query
= em.createNativeQuery(sql, User.class); List<User> obj = query.getResultList(); return obj; } }
package com.aircas.satellitemanagement.jpa;

import lombok.Data;
import lombok.ToString;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "user")
@Data
@ToString
public class User {

    @Id
    private String id;

    private String name;

    private String startTime;


}

数据库表结构

 

查询结果,是get接口,我就直接用浏览器访问了

 

 注意:实际应用中,会比较复杂,一般来说前台会给后台传一些参数比如name=xxx,后台需要去拼接sql语句

 

----------------------------------------------------------------------------------------------------------------------------------------------------------

在后续的使用中发现 LocalContainerEntityManagerFactoryBean 会有并发问题,然后尝试了直接使用 EntityManager,发现可以用,目前没啥问题,修改后的如下

package com.aircas.satellitemanagement.jpa;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

@RestController
@RequestMapping(value = "/user")
public class UserController {

@Autowired
EntityManager entityManager;

@GetMapping(value = "/all/4")
public List<User> exec() {
StringBuilder sqljoint = new StringBuilder(300);
sqljoint.append("SELECT * FROM user");
String sql = sqljoint.toString();
// User是我自己定义的entity bean
Query query = entityManager.createNativeQuery(sql, User.class);
List<User> obj = query.getResultList();
return obj;
}


}

 

posted @ 2021-04-16 17:08  袁骞骞  阅读(5050)  评论(0编辑  收藏  举报