I'm learning Java and Spring framework, so, in my Java web application I have interface Client
and 2 classes that implements this interface - PersonClient
and CompanyClient
. Also, there is interface Account
and class that implements this interface - DebitAccount
:
package com.bankapp.bankwebapplication.models;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class DebitAccount implements Account {
@Id
private Long id;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
private Long clientId;
public Long getClientId() { return clientId; }
public void setClientId(Long clientId) { this.clientId = clientId; }
private Long amountOfMoney;
public Long getAmountOfMoney() { return amountOfMoney; }
public void setAmountOfMoney(Long amountOfMoney) { this.amountOfMoney = amountOfMoney; }
}
This class has filed clientId
. And here is a problem. As you can see, this is not DB, so, I can't just create private Long clientId
. It has to be class instead of Long
data type, but, I have interface, and I can't create interface instance, but I understand, that I can't leave it this way, it has to be class data type, not Long
.
I was thinking about abstract class, but, as same as interface, it's about polymorphism and I can't create abstract class instance either. How to figure that out? Or should I just create 2 fields for CompanyClient
and PersonalClient
?
CodePudding user response:
"...this is not DB..." is in opposite to the @Entity annotation. Your field clientId seems to be a foreign reference to one of your Client entities.
Usually such a 1:n relationship is modelled by JPA trough an entity reference, although the DB only has a Long ClientId as foreign key. The creation of the instance of the Client is done by JPA implementation (e.g. Hibernate) when you fetch a result set.
But you have to annotate the member by indicating the DB-Field which describes the relationship. E.g. (assuming one client can have more than one DebitAccount):
@ManyToOne(mappedBy="clientId")
Client client;
On the other hand, the @Entity implementations (the descendants of Client) must annotate how Hibernate can distiguish the two types, e.g. by a DB-Field ClientType. There are many possibilities to model this. This link may be a starting point.
CodePudding user response:
Here is my solution of the problem. I just added transient
before class name and variable name, like that:
private transient Client clientId;
public Long getClientId() { return clientId.getId(); }
public void setClientId(Client clientId) { this.clientId = clientId; }
And, for example, using getClientId
I just need to call method in interface.