1

I have two tables.

-- child
id           key (VARCHAR, UNIQUE)
----------------------------------
0            'a'
1            'b'

-- parent
id           child_keys (JSON)
------------------------------
0            ["a", "b"]

Ho can I map the child_keys column into a List or Map of Child?

class Parent {

    // works
    @JdbcTypeCode(SqlTypes.JSON)
    @Column(name = "child_keys")
    List<String> childKeys;

    // how can I do this?
    // Child(0,"a"), Child(1,"b")
    List<Child> children;

    // or this?
    // "a"-Child(0,"a"), "b"-Child(1, "b")
    Map<String, Child> children;
}
3
  • 1
    You don't, not with ORM directly as this isn't a 'normal' database mapping. You would need to use your string LIst of keys and find the matching entities to build list of Child entity objects. Is there any reason you don't normalize this by having a separate M:M table, or put the FK in the child table? This would give you foreign key constraints and referential integrity in the DB.. and just more mapping options. Commented Oct 24 at 17:36
  • @Chris Thank you for the comment. The table is not under my control, simply. Commented Oct 25 at 12:45
  • 1
    Then I would avoid it as much as possible as there are a lot of edge cases to handle -but it is possible to build your LIst or map in a PostLoad event by querying based on the fetched 'childKeys' List<String> to fetch the Child entities. Just be sure to mark the list/Map as JPA transient as you have to manage it yourself - and you'll want to decide if/how to manage updates on the way back as it'll be the List<String> that controls the mapping. This might be better done only when needed though via a special service method instead of on every entity fetch. Commented Oct 27 at 16:14

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.