【问题标题】:Retrieve entry from table using foreign key (Hibernate)使用外键从表中检索条目(休眠)
【发布时间】:2019-01-04 11:01:29
【问题描述】:

我正在学习如何使用 Hibernate,并且我有一个与查询具有一对一关系的表有关的问题。

有两个表,EmployeeAccount,具有一对一的关系。 Employee 的主键是员工 ID。我想将此 id 用于Account,并且我知道它因此可以定义为Account 表中的外键。

@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;
}

请注意,Account 没有额外的 id 字段。员工 ID 外键是唯一的。这可以接受吗?

我已为Account 声明了一个存储库接口,如下所示:

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

如何使用员工 ID 从该表中检索条目?

例如像

accountRepository.getOne(employeeId)

【问题讨论】:

    标签: java database hibernate foreign-keys one-to-one


    【解决方案1】:

    您可能希望将以下方法添加到您的存储库中。

    从 Spring Data JPA 的方法命名来看,这应该从其 Employee 对象的 id 字段中检索您的 Account

    Account findByEmployee_Id(Integer employeeId)
    

    【讨论】:

    • 不应该叫findByEmployeeId吗?
    • 不,这种语法只有在Account 有一个employeeId 整数字段而不是Employee 字段时才有效。方法名称中的下划线告诉 spring 查找子对象的属性值。
    猜你喜欢
    • 2019-01-05
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多