public class Account {
private String accountId
private List<Transaction> transactions = new ArrayList<>();
public abstract class Transaction {
private double amount;
public class AccountEntity extends BaseEntity{
@OneToMany
private List<TransactionEntity> transactions;
public class TransactionEntity extends BaseEntity{
@Id
private String transactionId;
private double amount;
private String type;
@ManyToOne
@JoinColumn(name = "accountId", referencedColumnName = "accountNumber")
private AccountEntity account;
@Mapper(componentModel = "spring")
public interface AccountMapper {
Account AccountEntityToAccount(AccountEntity accountEntity);
AccountEntity AccountToAccountEntity(Account account);
My AccountEntityToAccount method is getting error which is The return type Transaction is an abstract class or interface. Provide a non abstract / non interface result type or a factory method. Account AccountEntityToAccount(AccountEntity accountEntity);
how could i solve this problem. My Transaction class should be abstract i can not change abstract keyword
CodePudding user response:
The Problem is
private List<Transaction> transactions = new ArrayList<>();
if you have another class which extends Transaction then use this for your generic in the list. Otherwise how should Mapstuct now which class to create for that List
CodePudding user response:
Add a method to create the correct Transaction from the TransactionEntity supplied.
Reading the code you probably want to have something like the following:
Transaction fromTransactionEntity(TransactionEntity entity){
if (entity == null){
return null;
}
if ( entity.getType().equals("something") ) {
return toSomethingTransaction(entity);
}
if ( entity.getType().equals("other") ) {
return toOtherTransaction(entity);
}
throw new IllegalStateException("unsupported transaction found, cannot instantiate object.");
}
SomethingTransaction toSomethingTransaction(TransactionEntity entity);
OtherTransaction toOtherTransaction(TransactionEntity entity);
In the other direction you probably want to do the same thing. (when 1.5.0
is released you can use @SubclassMapping
for this instead of manually writing the instanceof. currently at 1.5.0.RC1
stage.)
TransactionEntity toTransactionEntity(Transaction transaction){
if (transaction == null){
return null;
}
if (transaction instanceof SomethingTransaction){
return fromSomethingTransaction(transaction);
}
if (transaction instanceof OtherTransaction){
return toOtherTransaction(entity);
}
throw new IllegalStateException("unsupported transaction found, cannot store it.");
}
@Mapping( target = "type", constant = "something" )
TransactionEntity fromSomethingTransaction(SomethingTransaction transaction);
@Mapping( target = "type", constant = "other" )
TransactionEntity fromOtherTransaction(OtherTransaction transaction);