将hashmap转换为字符串

时间:2018-05-19 11:02:57

标签: java rest arraylist hashmap spring-data-jpa

我正在处理遗留数据库,其中不能修改表模式。大多数记录都是唯一的,但有一些重复的条目。出于这个原因,我修改了RecordRepository.java接口以使用map()执行@Query。否则,如果JPA认为它是相同的记录,JPA将返回相同的数据。

RecordRepository.java:

@Query("select new map(field1 as field1, field2 as field2) from Record where year = ?1")
List<Record> findByYear(String year);

RecordController.java:

@RestController
public class RecordController {
    @Autowired
    private RecordRepository recordRepository;

    @RequestMapping(value = "/record/{year}", method = RequestMethod.GET)
    public List<Record> recordByYear(@PathVariable("year") String year) {
        List<Record> l = recordRepository.findByYear(year);

        System.out.println(l.getClass());
        System.out.println(l.get(1967));

        return l;
    }
}

getClass()的输出为class java.util.ArrayList。从ArrayList打印项目1967是{field1=2018-01-15, field2=201801}

但是当我尝试使用String tmp_r = l.get(1967).getField1()获取field1的字符串值时,我收到错误java.util.HashMap cannot be cast to Record

我尝试了SO的各种建议。我的头在旋转,我必须忽略一些简单的解释。

此致 克劳斯

2 个答案:

答案 0 :(得分:0)

l.getClass()是一个ArrayList,但这并不意味着它的所有元素都是Record-s(可能是在其他地方进行了转换)。

当你调用l.get(1967)时,结果项是一个HashMap(对吗?),所以也许你可以先检查表达式l.get(1967)的实际类型。

如果地图已被字符串编入索引,则String tmp_r = l.get(1967).get("field1")将打印您的字段。

答案 1 :(得分:0)

Danieles的回答,以及STaefi的评论,引领我走向了严谨的方向。解决方案最终变得非常简单。我的错误可以归结为我曾经使用过这段时间的事实。我将界面中的返回类型从List更改为List。

RecordRepository.java:

FCPATH

RecordController:

    Using tfp As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\Users\Charlie\Documents\Test.txt")
        'set the field type to delimited
        tfp.TextFieldType = FileIO.FieldType.Delimited
        'set the delimiter to a space
        tfp.Delimiters = New String() {" "}
        'create a string array to hold the fields
        Dim currentRow As String()

        While Not tfp.EndOfData
            'call ReadFields to fill the string array
            currentRow = tfp.ReadFields()
            'here we're just looping through the row to show the individual fields
            For Each field As String In currentRow
                MsgBox(field)
            Next
        End While
    End Using

会给我一个值field1 has。