Spring Data JPA Non-key field references in Hibernate

Viewed 29

Is there any way in Hibernate that allows using non-primary key fields to describe relationships?

How can I describe Users and Authorities in Hibernate?

When I use @OneToMany and @ManyToOne, it just helps Authorities create a field called user_id and it will reference the User id.

Entity Relationship Model

https://i.stack.imgur.com/3k0eS.png

Java classes

@Entity
@Table(name = "Users")
public class User {

    @Id
    @GeneratedValue
    private Long id;

    private String username;

    // ...getters and setters
}

--

@Entity
@Table(name = "Authorities")
public class Authority {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    private User user;

    // ...getters and setters
}
1 Answers

You could use the @NaturalId annotation on the username field of the User entity and then reference that column in the Authority entity via @ManyToOne(referencedColumnName=...).

Example

@Entity
@Table(name = "Users")
public class User {

    @Id
    @GeneratedValue
    private Long id;

    @NaturalId
    private String username;

    // ...getters and setters
}

--

@Entity
@Table(name = "Authorities")
public class Authority {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne(fetch = ...)
    @JoinColumn(
        name = "username", 
        referencedColumnName="username"
    )
    private User user;

    // ...getters and setters
}
Related