java - NullPointerException on getting ManyToMany relation -
i got entity account manytomany entity role.
@entity public class account { @id @generatedvalue(strategy=generationtype.sequence) private long id; @manytomany(cascade= {cascadetype.persist,cascadetype.merge,cascadetype.refresh}, fetch=fetchtype.eager) @jointable(name="account_role") private set<role> roles; // getters, setters }
when try access relationship collection got nullpointerexception roles null:
account account = new account(); account.getroles().size();
shouldn't empty set injected roles
? or default behaviour , should control roles
creation by:
private set<role> roles = new hashset()<>;
you created object
account account = new account();
that wasn't managed jpa. how expect not null?
reference type instance variables are, default, assigned null
. set
reference type. should create set
(as you've suggested).
private set<role> roles = new hashset()<>;
or retrieve entity instance jpa entitymanager
instance
account account = entitymanager.find(account.class, 42);
Comments
Post a Comment