如何链接不同类的两个对象?

时间:2019-06-20 10:24:10

标签: java spring rest api

我想为库构建REST API(端点是客户和发票)。功能之一是添加发票(带有客户ID的PUT请求)。首先,我必须检查传递的客户ID(通过URL中的PUT)是否存在,这意味着要检查customerMap并照顾正在讨论的ID。问题在于,customerMap是clientService类中的HashMap(而不是invoiceService类中的HashMap)(使用Map而不是数据库)。如何获取存储在地图中的数据?特此代码的相关部分:

客户端

public class clientService {
public Map<Long, client> clientMap = new HashMap<>();

public client put(client g) {
    clientMap.put(g.getId(), g);
    return g;
}

public Collection<client> getAll() {
    return clientMap.values();
}
}

clientService

invoice  {

private static final AtomicLong counter = new AtomicLong();

private final long id;
private client client;

public invoice() {
    this.id = counter.getAndIncrement();
}

public long getId() {
    return id;
}
}

发票

public class invoiceService {
private Map<Long, invoice> invoiceMap = new HashMap<>();

public Rechnung createinvoice(invoice g, long id) {

    if(<!--client exists-->)
    invoicegMap.put(g.getId(), g);
    return g;
}}

invoiceService

$currencies

2 个答案:

答案 0 :(得分:0)

首先向您的ClientService添加一个方法,以按ID查找客户端:

public Client getClientById(Long clientId) {
   return clientMap.get(clientId);
}

然后将您的ClientService注入您的发票服务中;

public class invoiceService {
private Map<Long, invoice> invoiceMap = new HashMap<>();
private ClientService clientService; // provide a getter or a constructor argument for the service

public Rechnung createinvoice(invoice g, long id) {

    if(clientService.getClientById(id) != null) {
      invoicegMap.put(g.getId(), g);
}
    return g;
}}

答案 1 :(得分:-1)

为什么不将clientmap设为静态并直接从客户服务类访问它?