简体   繁体   中英

How can you map a property to a specific column of another table using JPA?

I have two tables. One has the data I'm concerned about, "Thing". Thing schema:

  • thing_id
  • name
  • thing_type_id
  • ...metadata (including created and modified dates)

'thing_type_id' is a foreign key for another table, which is basically acting as an enum.

ThingType schema:

  • thing_type_id
  • name
  • ...metadata

I have created classes for both, and I can easily join the two using

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

to associate a ThingType object with each Thing. However, the only relevant field is ThingType.name.

What I want to do is reference the string directly, like

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

Approaches I've tried

  • Using the @SecondaryTable annotation on the Thing class seems to only work for one-to-one mapping.
  • @JsonIgnore on all irrelevant fields of ThingType leaves me with an object containing only one entry rather than just the value of that entry.
  • Joining the whole object as above, @JsonIgnoring it, and create a getter to that field that somehow maps to the JSON output should work, but I'm not sure how to do that.

Thank you for your help!

Figured it out. The third approach works.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM