SpringBoot中JPA使⽤动态SQL查询
可以重点关注⽅法⼆,把原⽣sql传⼊数据库去查询
好处是:更加灵活坏处是:拼接sql⽐较痛苦,也容易出问题,⽐如拼接的sql某些字段不存在或者拼接后语法不符合sql语句package com.aircas.satellitemanagement.jpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import 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 = NativeEntityManagerFactory().createEntityManager();
StringBuilder sqljoint = new StringBuilder(300);
sqljoint.append("SELECT * FROM user");
String sql = String();
// User是我⾃⼰定义的entity bean
Query query = em.createNativeQuery(sql, User.class);
List<User> obj = ResultList();
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;
springboot是啥}
数据库表结构
查询结果,是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 = String();
// User是我⾃⼰定义的entity bean
Query query = ateNativeQuery(sql, User.class);
List<User> obj = ResultList();
return obj;
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论