ksl
ksl

Reputation: 4719

Retrieve entry from table using foreign key (Hibernate)

I'm learning how to use Hibernate and I have a question relating to querying tables that have a one-to-one relationship.

There are two tables, Employee and Account, that have a one-to-one relationship. The primary key for an Employee is an employee id. I want to use this id for an Account and I understand that it can therefore be defined as a foreign key in the Account table.

@Entity
@Table
public class Employee
{
    @Id
    private int employeeId;
}

@Entity
@Table
public class Account
{
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "employeeId", referencedColumnName = "employeeId", nullable=false, insertable=false, updatable=false, foreignKey = @ForeignKey(name="FK_Account_Employee"))
    private Employee employee;
}

Note that Account does not have an additional id field. The employee id foreign key is unique. Is this acceptable?

I have declared a repository interface for the Account as follows:

@Repository
public interface AccountRepository extends JpaRepository<Account, Integer>
{
}

How do I retrieve an entry from this table using the employee id?

E.g. something like

accountRepository.getOne(employeeId)

Upvotes: 0

Views: 2951

Answers (1)

Arnaud
Arnaud

Reputation: 17534

You may want to add the following method to your repository.

From the method naming of Spring Data JPA, this should retrieve your Account from the id field of its Employee object :

Account findByEmployee_Id(Integer employeeId)

Upvotes: 3

Related Questions