首页 > 解决方案 > 从 JPA 子实体中获取价值

问题描述

如何使用 Spring-data-jpa 从 childofchild 实体中检索值?

例如。Person Entity ->Account Entity ->Debit_Account Entity

借记帐户实体包含我要检索的值 dbtAmount。

我是 spring 和 spring-data-jpa 存储库中的新手,使用 find 方法我无法从 childofchild 实体获取详细信息。

标签: javaspringhibernatespring-bootspring-data-jpa

解决方案


我们必须正确地实现实体之间的关系。如,

  • 一对一
  • 一对多
  • 多对多

如果您已经正确配置了这个,您应该能够获取人员实体,使用 getAccounts 方法从中获取 Account 实体,并使用 getDebitAccounts 方法从中获取 DebitAccount。

JPA 关系映射概念 https://www.mkyong.com/hibernate/hibernate-one-to-many-relationship-example/

假设关系是一对多,我添加了更多解释,

在此处输入图像描述

import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.OneToMany;

@Entity
public class Person {

@Column
private String username;

@Column
private String email;

@OneToMany(mappedBy="user")
private Set<Account> accounts;

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public Set<Account> getAccounts() {
    return accounts;
}

public void setAccounts(Set<Account> accounts) {
    this.accounts = accounts;
}
}

import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.OneToMany;

@Entity
public class Account {

@Column
String name;

@OneToMany(mappedBy="account")
private Set<DebitAccount> debitAccounts;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Set<DebitAccount> getDebitAccounts() {
    return debitAccounts;
}

public void setDebitAccounts(Set<DebitAccount> debitAccounts) {
    this.debitAccounts = debitAccounts;
}

}

import javax.persistence.Column;
import javax.persistence.Entity;

@Entity
public class DebitAccount {

@Column
String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}

希望这可以帮助。


推荐阅读