Michael
Michael

Reputation: 102

How to use a foreign key variable without writing the specific foreign key column in the entity class?

I have the following entity 'User' where the field 'companyId' is a foreign key:

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

@Id
@GeneratedValue
private long id;

@Column(name = "company_id")
private Long companyId;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "company_id", insertable = false, updatable = false)
private Company company;

The Company entity:

@Entity
@Table(name = "Companies")
@Getter @Setter @ToString
public class Company {

    @Id
    @GeneratedValue
    private long id;
      
    @OneToMany(mappedBy = "company", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
    private List<User> users;

I removed other irrelevant fields from the classes. I'm using spring boot data jpa. My question is how to remove the field 'companyId' and use the company id inside the field 'company' for CRUD functions with the DB.

Upvotes: 0

Views: 302

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36103

Simply remove the companyId and make Company writable

@Entity

    @Table(name = "Users")
    @Getter @Setter @ToString
    public class User {
    
    @Id
    @GeneratedValue
    private long id;
    
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id")
    private Company company;

Upvotes: 2

Related Questions