我尝试将Armor对象放入Equipment对象,并将其作为JSONB格式存储在数据库中的Hero实体中。 有一些实体:
@MappedSuperclass
@Data
@AllArgsConstructor
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "type")
@JsonSubTypes({
@Type(value = Armor.class, name = "armor"),
})
public abstract class Item {
@Id
private Integer id;
private String name;
private int count;
public Item() {
}
}
@Entity
@TypeDefs({
@TypeDef(name = "pgsql_enum", typeClass = PostgreSQLEnumType.class)
})
@Getter
@Setter
public class Armor extends Item implements Serializable {
private int armorStat;
@Type(type = "pgsql_enum")
@Enumerated(value = EnumType.STRING)
private ArmorType armorType;
private String description;
public Armor() {
}
public Armor(Integer id, String name, int count, int armorStat,
ArmorType armorType, String description) {
super(id, name, count);
this.armorStat = armorStat;
this.armorType = armorType;
this.description = description;
}
}
@Entity
@Data
public class Hero {
@Id
@GeneratedValue
private Long id;
private String name = "";
private int fame = 0;
private int gold = 0;
private int tiredness = 100;
private int hp = 10;
private int damage = 1;
private int defense = 1;
@Type(type = "jsonb")
@Column(columnDefinition = "jsonb")
private Equipment equipment;
@Type(type = "jsonb")
@Column(columnDefinition = "jsonb")
private Inventory inventory;
private String kingdom;
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
private User user;
public Hero() {
this.equipment = new Equipment();
this.inventory = new Inventory();
}
}
@Data
public class Equipment implements Serializable {
private Armor helmet;
private Armor chestplate;
private Armor gloves;
private Armor boots;
}
当我尝试设置设备并将其保存到数据库时,它将引发如下异常:
Caused by java.lang.IllegalArgumentException: The given JSON object value: Equipment(helmet=Item(id=1, name=Leather helmet, count=1), chestplate=null, gloves=null, boots=null) cannot be transformed to a String
服务层代码:
Hero hero = user.getHero();
Equipment equipment = hero.getEquipment();
Armor armor = armorRepository.getOne(dataParser.getItemId(user.getAttributes().getExecutable()));
equipment.setHelmet(armor);
userService.save(user);
我不知道该如何解决。请给我一些有关解决问题的建议。