0
votes

I have two tables user and student. Student and user has one to one relationship. I am mapping same column with both userId and UserEntity inside StudentEntity

@Entity
@Table(name = "user")
public class User {
    @Id
    private UUID id;

    @Column(name = "name")
    private String name;

    ...

    // getter setter ignored for brevity
}


@Entity
@Table(name = "student")
public class Student {
    @Id
    private UUID id;

    @Column(name = "user_id")
    private UUID userId;

    @OneToOne
    @JoinColumn(name = "user_id", referencedColumnName = "id", 
                insertable = false, updatable = false)
    private UserEntity userEntity;

    ...

    // getter setter ignored for brevity
}


@Repository
public interface StudentRepository extend PagingAndSortingRepository<StudentEntity, UUID> {

  Optional<StudentEntity> findByUserId(UUID userId);
}

Now when I call any of below method UserEntity is not populated

StudentEntity student = studentRepository.findByUserId(userId).get()
student.getUserId() --- this is present
student.getUserEntity() -- NULL

Not sure why UserEntity is not getting populated as a part of this call.

2
Your code works for me. Can you please show the whole method? Do you save and find the User in the same transaction?Simon Martinelli
Remove this field @Column(name = "user_id") private UUID userId; And it should workLucia
By specifying the user_id in the JoinColumn annotation makes everything correctly work. There is no need of seperate field for userId in your entityLucia
The thing is I need both so that in spring boot I can use findByUserId() and findByUserEntity()big
@SimonMartinelli I tried both same and different transactions its still nullbig

2 Answers

1
votes

The issue is most likely that your persistence context still contains the entity that you previously saved (which has no user set). You would first have to clear the persistence context and the load it again to see a non-null user.

Anyway, like suggested in the comments, I would advise you to just map the user. You don't need the userId field. The way you mapped it now, you should be able to use the following:

Optional<StudentEntity> findByUserEntityId(UUID userId);

Also read the official documentation for more information on the matter: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-property-expressions

-1
votes

You can try reverse mapping mapping like below by using mappedby in the owner of the relationship jpa hibernate @OneToOne @JoinColumn referencedColumnName ignored