首页 > 解决方案 > 在 Spring Boot 中处理本机查询时获取混乱的数据或错误的数据

问题描述

我正在使用左连接在 jpa 存储库中编写本机查询并获​​得混乱的输出并向查询添加更多列正在生成从 java.object 到我的模型类的转换错误。此外,当我尝试从 join 的输出中返回所有内容时,它作为 id 使用别名的重复给出

我尝试制作不同的类和接口来存储查询结果但没有发生

这是存储库

@Repository

public interface GroupRepository extends JpaRepository<Groups, Long> {

@Query (value="SELECT gad.id ,gha.id as groupattributeid , gad.group_id ,gad.value , gad.attribute_id, gha.hierarchy_id  FROM group_attr_data gad JOIN group_hierarchy_attributes gha ON  gad.attribute_id = gha.id where gad.group_id = ?1",nativeQuery = true)

 Collection<GroupAttData> viewGroupAttData(Long group_id);

 }

这是我的控制器

    public class GroupController {

    @Autowired
GroupRepository groupRepository;
@RequestMapping(value="/view-group-attr-data", method = RequestMethod.POST, consumes="application/json" , produces = "application/json")

public Collection<GroupAttData> ViewGroupAttData(@RequestBody GroupAttrData request) throws ResourceNotFoundException{

    if(groupRepository.viewGroupAttData(request.getGroup_id()).isEmpty()) {

        throw new ResourceNotFoundException("groups not found " );

    }   else {

        return (List<GroupAttData>) groupRepository.viewGroupAttData(request.getGroup_id());

    }

}
}

这是我的 GroupAttData 模型接口

 public interface GroupAttData {

public Long getid();
public Long getgroup_id() ;
public Long getattribute_id();
public String getvalue();
public Long getgroupattributeid();
public Long gethierarchy_id();

}

实际结果应该是

 SELECT gad.id ,gha.id as groupattributeid , gad.group_id ,gad.value ,gad.attribute_id, gha.hierarchy_id FROM group_attr_data gad JOIN group_hierarchy_attributes gha ON  gad.attribute_id = gha.id where gad.group_id = 1;

 # id, groupattributeid, group_id, value, attribute_id, hierarchy_id
  '299'       '7'            '1'     '33'      '7',        '1'

即将到来的结果是

 [
  {
    "hierarchy_id": 33,
    "groupattributeid": 1,
    "id": 7,
    "value": "1",
    "group_id": 7,
    "attribute_id": 299
  }
 ]

与对于 hierarchy_id 它应该是 1 ,其中即将到来的输出数据是 33 并且对于值它应该是 33 ,其中结果数据在 spring boot 中是 1 。

标签: mysqlspring-bootjoinnativequery

解决方案


尝试使用 camelCase 命名法

public interface GroupAttData {

  Long getId();
  Long getGroupId() ;
  Long getAttributeId();
  String getValue();
  Long getGroupattributeid();
  Long getHierarchyId();

}

推荐阅读