gpt4 book ai didi

java - 如何将 Map> 从 JSON 映射到 JPA?

转载 作者:行者123 更新时间:2023-11-30 06:14:11 26 4
gpt4 key购买 nike

我尝试了许多不同的解决方案,但没有任何效果。这是我现在拥有的:

我的玩家数据将如下所示:

{
"id": 1,
"name": "Stalker",
"type": "dark",
"faction": 3,
"weaponAbilities": {
"normal": [
5,
1,
0
],
"dark": [
4,
2,
8
]}
}

我正在尝试绘制能力图。

这是我的代码:

@Data
@Entity
@Table(name = "player")
@EntityListeners(AuditingEntityListener.class)
public class Player {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;

@OneToMany
Map<String, Abilities> weaponAbilities;

}

然后:

@Data
@Entity
@Table(name = "abilities")
@EntityListeners(AuditingEntityListener.class)
public class Abilities {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;

@ElementCollection(targetClass = Integer.class )
private List<Integer> ability;
}

我得到的错误:

Caused by: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `com.project.myapp.entity.Abilities` out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.project.myapp.entity.Abilities` out of START_ARRAY token
at [Source: (PushbackInputStream); line: 1, column: 1067708] (through reference chain: java.lang.Object[][911]> com.project.myapp.entity.Player["weaponAbilities"]->java.util.LinkedHashMap["normal"])

最佳答案

首先,错误是 JSON,而不是 JPA,所以如果您的意思是通过这个问题来解决该问题,请重述它。

我在这里回答如何映射 JPA 中的类以便能够保留该类型的字段。由于您尚未定义如何在数据库中保留该信息,因此您可以通过一种方法来实现此目的,而无需包含 List<Integer> 的人工实体。如下

@Entity
public class Player
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;

@CollectionTable
@ElementCollection
@Convert(attributeName="value",converter=ListIntegerStringConverter.class)
Map<String, List<Integer>> weaponAbilities;
}

然后,这会将 Map 字段存储到一个单独的表中,键存储在 VARCHAR 列中,值存储在 VARCHAR 列中。如果需要,您可以通过正常的 JPA 方式控制这些列的大小。 List<Integer>可以以逗号分隔、JSON 或其他任何形式存储到此值列中。例如,使用逗号分隔

@Converter(autoApply=true)
public class ListIntegerStringConverter implements AttributeConverter<List<Integer>, String>
{
public String convertToDatabaseColumn(List<Integer> attribute)
{
if (attribute == null)
{
return null;
}
StringBuilder str = new StringBuilder();
for (Integer val : attribute)
{
if (str.length() > 0)
{
str.append(",");
}
str.append(val);
}
return str.toString();
}

public List<Integer> convertToEntityAttribute(String dbData)
{
if (dbData == null)
{
return null;
}

List<Integer> list = new ArrayList<>();
StringTokenizer tokeniser = new StringTokenizer(dbData, ",");
while (tokeniser.hasMoreTokens())
{
list.add(Integer.valueOf(tokeniser.nextToken()));
}

return list;
}
}

但这完全取决于您对此列表的要求,其中是否可能包含大量元素,是否要查询它等等,这可能会影响您是否会这样做使用中间实体,或将其放入单个列中(如此处所示)。

关于java - 如何将 Map<String, List<Integer>> 从 JSON 映射到 JPA?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49593174/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com