Home > Software engineering >  Join column from another table with Foreign Key using JPA
Join column from another table with Foreign Key using JPA

Time:05-26

I'm new to JPA and trying to understand if there's a way to make an Entity where one column is coming from another table that is linked by a foreign key. For example, consider the following tables:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE `jobs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11),
  PRIMARY KEY (`id`),
  CONSTRAINT `fk_jobs_users` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
);

Now I want to make an Entity for the "jobs" table that will include the user.email. I know I can do something like

@Entity
@Table(name = "jobs")
public class JobEntity {

    @Id
    @Column(name = "id")
    private Long id;

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

    @Formula("(select user.email FROM user WHERE user.id = user_id)")
    private String userEmail;

But I feel there's a way I can better leverage the foreign key relationship, but I'm not sure how. I was looking into @JoinColumn but was not seeing the result I wanted since the foreign key is a different column in my Entity. Is there a better way rather than using @Forula to do this?

CodePudding user response:

I don't really understand this. I'm sure @JoinColumn can accomplish the behavior you're looking for.

I was looking into @JoinColumn but was not seeing the result I wanted since the foreign key is a different column in my Entity

Example:

@Entity
@Table(name = "jobs")
public class KronosFileEntity {

    @Id
    @Column(name = "id")
    private Long id;

    @ManyToOne
    @JoinColumn(name = "user_id", referencedColumn = "id")
    private User user;
}

Then you can access the email like job.getUser().getEmail()
Or add a convenience method if that helps

public String getUserEmail() {
   return user.getEmail();
}

Then job.getUserEmail()

  • Related