我有三个实体,一个存储库扩展了CrudRepository,我想进行下一个查询,但是我不能。我上半身或附近有语法错误。我认为问题出在查询中使用了多个表,并且/或者我没有在实体中使用任何标签或声明。
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import com.companyname.springapp.business.entities.TableA;
public interface TableARepository extends CrudRepository<TableA, Integer>{
@Query(value = "SELECT DISTINCT a.*"
+"FROM TableB AS b, TableA_TableB AS ab, TableA AS a"
+"WHERE upper(b.nick_name) like upper(concat('%',:name,'%'))"
+"AND b.nick_name_id=ab.nick_name_id"
+"AND ab.id=a.id",
nativeQuery = true)
List<tableA> test(
@Param("name") String name);
我的实体:
TableA
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import com.companyname.springapp.web.Views;
import com.fasterxml.jackson.annotation.JsonView;
@Entity
@Table(name="TableA")
public class TableA{
@Id
@JsonView(Views.Public.class)
private Integer id;
//more columns, constructs and getters and setters
TableB
//... imports
@Entity
@Table(name="TableB")
public class TableB{
@Id
@JsonView(Views.Public.class)
private Integer nick_name_id;
@JsonView(Views.Public.class)
private String nick_name;
//more columns, constructs and getters and setters
TableA_TableB
//... imports
@Entity
@Table(name="TableA_TableB")
public class TableA_TableB{
@Id
@JsonView(Views.Public.class)
private Integer id;
@JsonView(Views.Public.class)
private Integer nick_name_id;
//more columns, constructs and getters and setters
我有TableAManager
import java.util.List;
import com.companyname.springapp.business.entities.TableA;
public interface TableAManager {
public List<TableA> test(String name);
}
实现JPATableAManager
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.companyname.springapp.business.entities.TableA;
import com.companyname.springapp.business.repositories.TableARepository;
@Service
public class JPATableAManager implements TableAManager {
@Autowired
private TableARepository tableARepository;
public List<TableA> getTableA() {
return (List<TableA>) tableARepository.test();
}
PD:请问我的英语
答案 0 :(得分:0)
您的SQL语句缺少空格。
"SELECT DISTINCT a.*"
+"FROM TableB AS b, TableA_TableB AS ab, TableA AS a"
+"WHERE upper(b.nick_name) like upper(concat('%',:name,'%'))"
+"AND b.nick_name_id=ab.nick_name_id"
+"AND ab.id=a.id"
串联时
"SELECT DISTINCT a.*FROM TableB AS b, TableA_TableB AS ab, TableA AS aWHERE upper(b.nick_name) like upper(concat('%',:name,'%'))AND b.nick_name_id=ab.nick_name_idAND ab.id=a.id"
这导致aWhere
成为TableA
的别名,而where子句没有被解析。
以这种方式构造SQL语句时,每行以空格结尾:
"SELECT DISTINCT a.* "
+"FROM TableB AS b, TableA_TableB AS ab, TableA AS a "
+"WHERE upper(b.nick_name) like upper(concat('%',:name,'%')) "
+"AND b.nick_name_id=ab.nick_name_id "
+"AND ab.id=a.id"