Reputation: 6216
It seems I have a problem with OneToMany, ManyToOne mapping.
I'm using a CrudRepository named "ur" here:
ur.save(new User("zx","z", "a", "[email protected]", "Baa")); //userRepo save
User u1 = ur.findOneByUserName("Bx");
MyToken t1 = new MyToken("X5");
u1.addToken(t1);
ur.save(u1);
MyToken t2 = TokenRepo.findOneByToken("X5"); // a different crudRepository
String foundUser = t2.getUser().getUserName(); // THIS "user" is null.
relevant sections of User.java (extends AbstractPersistable<Long>):
@OneToMany(fetch = FetchType.EAGER, cascade={CascadeType.ALL}, mappedBy = "user")
private Set<Role> roles = new HashSet<Role>(1);
@OneToMany(fetch = FetchType.EAGER, cascade={CascadeType.ALL}, mappedBy = "user")
private Set<MyToken> token = new HashSet<MyToken>();
MyToken.java (extends AbstractPersistable<Long>):
@ManyToOne(fetch = FetchType.EAGER, cascade={CascadeType.ALL})
@JoinColumn(name="user") // commenting this out or not does nothing...
private User user;
My debugger says 'user' is 'null' at line "String foundUser" even though that should be completely false according to the code.
As you can see, all is "eager" so I don't see why MyToken.setUser() is not automatically done. How are they not linked already? AnyInitiatedToken.getUser() should not be null if you already did User.addToken, and UserRepo.save().
NOTE: I have also tried .LAZY for the MyToken.java and Role.java class (but still doesn't work).
Upvotes: 0
Views: 1406
Reputation: 81988
Since you did not post the setters, I gonna assume they look like default setter.
User.token
is set, but it has a mappedby
, so it is really irrelevant for what is stored in the DB. Token.user
matters, but that is still an NULL
so that's what get's saved and retrieved.
You have two options:
Change User.setToken()
to update Token.user
of the passed in Token
(and of the one that was previously set.
Whenever you call User.setToken()
also update Token.users
to make both directions of the relationship match.
Upvotes: 2
Reputation: 3109
I think it's not related to the fetch strategy whether it's eager or lazy fetch type. I think you gave column alias for the user's id and missed that the name atributte's value of the @JoinColumn
should reference that primary key column alias.
Like in the User you have:
@Id
@Column(name = "userid", unique = true, nullable = false)
public String getUserId() {
return this.userId;
}
then in the Token should be
@ManyToOne(fetch = FetchType.EAGER, cascade={CascadeType.ALL})
@JoinColumn(name="userid") // commenting this out or not does nothing...
private User user;
Upvotes: 0