如何使用JPA将属性映射到另一个表的特定列?

时间:2018-11-20 16:51:01

标签: java spring spring-boot jpa

我有两个桌子。其中一项是我关注的数据“事物”。 事物架构:

  • thing_id
  • 名称
  • thing_type_id
  • ...元数据(包括创建和修改的日期)

'thing_type_id'是另一个表的外键,该表基本上充当枚举。

ThingType模式:

  • thing_type_id
  • 名称
  • ...元数据

我已经为两者创建了类,并且可以使用

@ManyToOne() @JoinColumn(name = "thing_type_id") private ThingType thingType;

将ThingType对象与每个Thing相关联。但是,唯一相关的字段是ThingType.name。

我想做的是直接引用字符串,例如

@Column(table = "thing_type" name="name") private String thingType;

我尝试过的方法

  • 在Thing类上使用@SecondaryTable批注似乎仅适用于一对一映射。
  • @JsonIgnore在ThingType的所有不相关字段上,给我留下了一个仅包含一个条目而不只是该条目值的对象。
  • 按上述方法连接整个对象,@ Json忽略它,并为该字段创建一个吸气剂,以某种方式映射到JSON输出应该起作用,但是我不确定如何做到这一点。

谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

弄清楚了。第三种方法有效。

@JsonIgnore @ManyToOne() @JoinColumn(name = "thing_type_id") private ThingType thingType;

@JsonProperty("thingType") String getThingType() { return this.thingType.getName(); }