java - JPA Collection Using Map -
so have small proof of concept using jpa, hibernate , spring data. in poc have created post
entity , comment
entity. post
entity contains map of comments map<integer,comment>
.
i having issues persisting multiple comment
entities map
since used comment
entities @id
column key map. basically, if didn't explicitly set id of comment
hibernate recognized them same entity , persisted 1 of them.
i found persist map
specifying garbage keys, mysql autonumber replace once persisted. led issue, keys within current map not receive new commentid
values set database. caused unit test fail.
so have 3 questions?
- should specify garbage keys persist entities in map?
- is approach wrong? if so, whats better way?
- if garbage keys ok, how can refresh them after insert?
post.java
@entity @table(name = "post") public class post { @id @generatedvalue(strategy = generationtype.identity) @column(name = "post_id") private integer postid; @column(name = "title") private string title; @onetomany(mappedby = "post", cascade = cascadetype.all) @mapkeycolumn(name="comment_id") private map<integer, comment> comments = new hashmap<integer, comment>(); /** accessors (get/set) **/ /** hashcode & equals not consider postid field or map */ }
comment.java
@entity @table(name="comment") public class comment { @id @column(name="comment_id") @generatedvalue(strategy=generationtype.identity) private integer commentid; @column(name="body") private string body; @manytoone(cascade=cascadetype.all) @joincolumn(name="post_id") private post post; /** accessors (get/set) **/ /** hashcode & equals not consider commentid field or post */ }
unit test
@test public void inserttest2(){ comment comment = new comment(); comment comment2 = new comment(); final string body1 = "this map test"; final string body2 = "this map test"; comment.setbody(body1); comment2.setbody(body2); post post = new post(); post.setpostdate(new date()); post.settitle("first post"); post.getcomments().put(1,comment); //setting garbage ids post.getcomments().put(2, comment2); //setting garbage ids comment.setpost(post); comment2.setpost(post); repository.save(post); post dbpost = repository.findone(post.getpostid()); map<integer, comment> comments = dbpost.getcomments(); //test fails using old id asserttrue(comments.containskey(comment.getcommentid())); //same here asserttrue(comments.containskey(comment2.getcommentid())); }
also note bidirectional relationship
should specify garbage keys persist entities in map?
no. real id affected, map in inconsistent state. keys of map should immutable.
is approach wrong? if so, whats better way?
frankly, don't see point in using map hold comments id. entity manager able comment id. use set or list.
the alternative persist comments , flush entity manager before adding them map, make sure have real id.
Comments
Post a Comment