如何使用 MySql 或 Jpa 存储库从数据库中给定的父代码获取子代码列表
How to get the child code list from the given parent code in database Using MySql or Jpa repository
我有一个业务需求,需要编写一个服务,returns 来自给定代理代码的子代理代码列表。这个 agent_details
table 如下。
这个tableagent_code是唯一的,但是reporter_code可以重复。每个特工都有一个记者。
另外,记者是代理人。据此table代理人和记者的联系如下。
我需要一项服务,通过提供代理代码来获取子代理列表。
例如,当给出 1011
时,应该 returns [1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010]
当给出 1005
时,应该 returns [ 1002, 1003]
.
我正在为此项目使用 Jpa 存储库。我的实体 class 和存储库 class 如下。如何解决这个问题 sql query or jpa repository?
@Data
@Entity
@Table(name = "agent_details")
public class AgentDetails {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Long id;
@Column(name = "agent_code", nullable = false, length = 16)
private String agentCode;
@Column(name = "reporter_code", nullable = false, length = 16)
private String reporterCode;
@Column(name = "branch", nullable = false, length = 32)
private String branch;
}
public interface AgentDetailsRepository extends JpaRepository<AgentDetails, Long>
{
AgentDetails findByAgentCode(String agentCode);
List<AgentDetails> findByReporterCode(String reporterCode);
}
你可以试试这个(常用 Table 表达式):
例如:“1011”作为您的动态父节点。
with recursive
cte
(childs)
as
( select agent_code as childs
from agent_details where agent_code = '1011'
union all
select g.agent_code as childs
from cte a
join agent_details g
on a.childs = g.reporter_code
)
select childs as parent_and_childs from cte;
然后在您的存储库中创建一个接收 List<String>
.
的方法
我有一个业务需求,需要编写一个服务,returns 来自给定代理代码的子代理代码列表。这个 agent_details
table 如下。
这个tableagent_code是唯一的,但是reporter_code可以重复。每个特工都有一个记者。 另外,记者是代理人。据此table代理人和记者的联系如下。
我需要一项服务,通过提供代理代码来获取子代理列表。
例如,当给出 1011
时,应该 returns [1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010]
当给出 1005
时,应该 returns [ 1002, 1003]
.
我正在为此项目使用 Jpa 存储库。我的实体 class 和存储库 class 如下。如何解决这个问题 sql query or jpa repository?
@Data
@Entity
@Table(name = "agent_details")
public class AgentDetails {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Long id;
@Column(name = "agent_code", nullable = false, length = 16)
private String agentCode;
@Column(name = "reporter_code", nullable = false, length = 16)
private String reporterCode;
@Column(name = "branch", nullable = false, length = 32)
private String branch;
}
public interface AgentDetailsRepository extends JpaRepository<AgentDetails, Long>
{
AgentDetails findByAgentCode(String agentCode);
List<AgentDetails> findByReporterCode(String reporterCode);
}
你可以试试这个(常用 Table 表达式): 例如:“1011”作为您的动态父节点。
with recursive
cte
(childs)
as
( select agent_code as childs
from agent_details where agent_code = '1011'
union all
select g.agent_code as childs
from cte a
join agent_details g
on a.childs = g.reporter_code
)
select childs as parent_and_childs from cte;
然后在您的存储库中创建一个接收 List<String>
.