No converter found capable of converting from type [java.math.BigInteger] to Entity - spring-boot

I'm trying to get a list of transactions from database and this is the error I'm facing.
"trace": "org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.Object[]] to type [com.wallet.sendmoney.entities.TransactionEntity] for value '{1, 1, null, null, KES, null, 123456, LQALVZCFJMU6, null, 2547XXXXXX3, 61234, Load wallet, null, null, null, null, null, WS322, null}'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.math.BigInteger] to type [com.wallet.sendmoney.entities.TransactionEntity]
I'm using JPA #Query annotation and here is my repository
#Repository
public interface TransactionsRepository extends JpaRepository<LoadWalletEntity, Long> {
#Query(value = "SELECT * FROM transactions_attempts WHERE mobile_number= :mobile_number", nativeQuery = true)
List<TransactionEntity> getAllByPhoneNumber(#RequestParam String mobile_number);
}
Here is my entity class:
#Entity(name = "transactions_attempts")
#Table
#Data
#NoArgsConstructor
#AllArgsConstructor
public class LoadWalletEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String currency;
#Column(name = "mobile_number")
private String mobileNumber;
private String transactionRef;
private String merchantCode;
private Integer amount;
private String networkCode;
private String reason;
private String statusCode;
private String merchantReference;
private String merchantRequestId;
private String checkoutRequestId;
private Integer resultCode;
private String resultDescription;
private String billRefNumber;
private Date transactionDate;
#Column(name = "customer_mobile")
private String customerMobile;
private String thirdPartyTransId;
}
What could I be missing or doing wrong here.
Thanks in advance

you are trying to query a list of TransactionEntity
but your Repository is extends with
extends JpaRepository<LoadWalletEntity, Long> {
what's this LoadWalletEntity????
it should be
extends JpaRepository<TransactionEntity, Long> {

Try this solution please:
#Entity
#Table(name = "transactions_attempts")
instead of
#Entity(name = "transactions_attempts")
#Table

Related

Spring JPA - How can I make JpaRepository queries using an #Embedded property?

I'm trying to make a existsBy query using a property that comes from an embedded class, but I'm receiving "No property 'cpf' found for type 'Patient'".
The class Patient uses the Person class as embedded.
Person.java
#Embeddable
#Data
public class Person {
#Column(nullable = false, length = 11)
private String cpf;
#Column(name = "full_name", nullable = false, length = 60)
private String fullName;
#Column(nullable = false)
private String birthdate;
#Column(name = "email", nullable = true, length = 30)
private String emailAddress;
#Column(name = "cellphone_number", nullable = true, length = 11)
private String cellphoneNumber;
}
Patient.java
#Data
#Entity
#Table(name = "tb_patient")
public class Patient implements Serializable {
#Serial
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "patient_id")
private UUID id;
#Column
private LocalDateTime registrationDate;
#Embedded
private Person Person;
}
PatientController.java (part of)
#PostMapping
public ResponseEntity<Object> savePatient(#RequestBody Person person) {
if(patientService.existsByCpf(person.getCpf())) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("CONFLICT: CPF number is already in use!");
}
var patientModel = new Patient();
BeanUtils.copyProperties(person, patientModel);
patientModel.setRegistrationDate(LocalDateTime.now(ZoneId.of("UTC")));
return ResponseEntity.status(HttpStatus.CREATED).body(patientService.save(patientModel));
}
PatientService.java (part of)
#Service
public class PatientService {
final PatientRepository patientRepository;
public PatientService(PatientRepository patientRepository) {
this.patientRepository = patientRepository;
}
public boolean existsByCpf(String cpf) {
return patientRepository.existsByCpf((cpf));
}
PatientRepository.java
#Repository
public interface PatientRepository extends JpaRepository<Patient, UUID> {
boolean existsByCpf(String cpf);
}
How can I pass the #Embedded properties to the #Repository?
You can try separate by _ embedded filed name and it's filed.
#Repository
public interface PatientRepository extends JpaRepository<Patient, UUID> {
boolean existsByPerson_Cpf(String cpf);
}

Why I am receiving empty array?

I am doing a project in Spring and Postgres. I am getting this empty column when I try to call a request with Postman. As you can see, it returns everything except ingredient column.
{
"recept_id": 8,
"recept_name": "conceptual",
"nation_id": 1,
"type_id": 1,
"isvegan": true,
"isvegetarian": true,
"photo": null,
"video": null,
"ingredient": [],
"level_id": 5,
"recept_view": 1,
"company_id": 4,
"ratinglvl": 5
}
However, in Postgres, this column has data ({1,2,3}). The data type of the ingredient column is an integer[] in Postgres. I inserted data to ingredient to Postgres manually.
While in Spring, I am using a simple CRUDrepository.
Entity:
#Data
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name = "recept")
public class Recept {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long recept_id;
#Column
private String recept_name;
private long nation_id;
private long type_id;
private boolean isvegan;
private boolean isvegetarian;
private File photo;
private File video;
#ElementCollection(targetClass=Long.class)
private List<Long> ingredient;
private short level_id;
private long recept_view;
private long company_id;
private short ratinglvl;
}
Controller:
#RestController
public class ReceptController {
private final ReceptService receptService;
public ReceptController(ReceptService receptService) {
this.receptService = receptService;
}
#RequestMapping(value="/recept",method= RequestMethod.GET, headers = "Accept=application/json")
public ResponseEntity<?> getAll() {
return ResponseEntity.ok(receptService.getAll());
}
Repository:
public interface ReceptRepository extends CrudRepository<Recept, Long> {}
Service:
#Service
public class ReceptService {
private final ReceptRepository receptRepository;
private final IngredientRepository ingredientRepository;
public ReceptService(ReceptRepository receptRepository, IngredientRepository ingredientRepository) {
this.receptRepository = receptRepository;
this.ingredientRepository = ingredientRepository;
}
public List<Recept> getAll(){
return (List<Recept>)receptRepository.findAll();
}
Don't know why it doesn't return it.
#ElementCollection is meant to collect the values of a column in a related table -not to denote a PostgreSQL array type.
In order to use Postgresql arrays, you need to define a custom type. Thankfully the hibernate-types library already provides a ListArrayType out of the box. This will allow you to define your entity like:
#Data
#NoArgsConstructor
#AllArgsConstructor
#Entity
#TypeDef(
name = "list-array"
typeClass = ListArrayType.class
)
#Table(name = "recept")
public class Recept {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long recept_id;
#Column
private String recept_name;
private long nation_id;
private long type_id;
private boolean isvegan;
private boolean isvegetarian;
private File photo;
private File video;
#ElementCollection(targetClass=Long.class)
#Type(type = "list-array)
#Column(
name = "ingredient",
columnDefinition = "integer[]"
)
private List<Long> ingredient;
private short level_id;
private long recept_view;
private long company_id;
private short ratinglvl;
}

Spring, JPA: How to query for Entities under another Entity with a many-to-many relationship bridge table setup

I'm fairly new to Spring. I'm trying to query all the donations under one donor with this ERD:
Donor |----* Agreement *----| Donations (A many-to-many relationship that uses a bridge table)
Here's my code:
Donor.java
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
public class Donor extends Auditable implements Comparable<Donor>{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotBlank(message = "Cannot have an empty account number field.")
private String accountNumber;
private String accountName;
private String salutation;
private String donorName;
private String cellphoneNumber;
private String emailAddress;
private String companyTIN;
private String phone1;
private String phone2;
private String faxNumber;
private String address1;
private String address2;
private String address3;
private String address4;
private String address5;
private String companyAddress;
private LocalDate birthDate;
private String notes;
#OneToMany(mappedBy = "donor")
List<MOA> moaList = new ArrayList<>();
...
}
Donation.java
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
public class Donation extends Auditable implements Comparable<Donation> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotBlank(message = "Cannot have an empty account number field.")
private String accountNumber;
private String accountName;
private String orNumber;
private String date;
private Double amount;
private String notes;
private String needCertificate;
private String purposeOfDonation;
#OneToMany(mappedBy = "donation")
List<MOA> moaList = new ArrayList<>();
...
}
MOA.java (Agreement)
#Entity
#Data
#NoArgsConstructor
#AllArgsConstructor
public class MOA extends Auditable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne
#JoinColumn(name = "donor_id")
#JsonIgnoreProperties("moaList")
private Donor donor;
#ManyToOne
#JoinColumn(name = "donation_id")
#JsonIgnoreProperties("moaList")
private Donation donation;
private String name;
private String donorAccountNumber;
private Long foreignDonationId;
private LocalDate dateSigned;
}
In my DonorRepository I'm trying to make this query which I expected would give me what I want:
public interface DonorRepository extends JpaRepository<Donor, Long> {
...
#Query(value = "SELECT * FROM donor WHERE account_number = ?1", nativeQuery = true)
List<Donation> findDonorsDonations(String accountNumber);
...
This gives me an error
Failed to convert from type [java.lang.Object[]] to type [com.package.server.domain.Donation] for value '{1, admin, 2021-04-01 10:29:53.0, admin, 2021-04-01 10:29:53.0, School, 123456, null, null, null, null, null, null, null, null, null, John Doe, null, null, null, null, null, Mr.}'; nested exception is org
You can use specification api and SpecificationExecutor.
You have to Join Donation with MAO(MAO with Donor) then query for donations of a particular Donor.

Spring data jpa CRUDRepository/ JPArepository saveall can not get id (non primary key)

I am fetching data from FB marketing API and trying to save in DB. I am able to save data in the DB using CrudRepository or JpaRepository -> saveall method, but when trying to fetch the id in response of saveall, I am getting id as null. When I see in the h2-console, able to see the auto increment value after the completion of transaction.
Note: id is not used as primary key #Id. accountId is used as primary key.
Model:
#Entity
#Table(name = "accounts")
#Data
#ToString(onlyExplicitlyIncluded = true)
public class Account implements Serializable{
#JsonIgnore
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(columnDefinition = "integer auto_increment",insertable = false)
private Long id;
#JsonProperty("account_id")
#Column(name = "account_id")
#Id
private String accountId;
#Column(name = "account_status")
private int accountStatus;
#JsonProperty("timezone_id")
#Column(name = "timezone_id")
private int timezoneId;
private int timezoneOffsetUtc;
private String currency;
#Column(name = "timezone_name")
#JsonProperty("timezone_name")
private String timezoneName;
private String name;
#Column(name = "created_on",nullable = false, updatable = false)
#CreationTimestamp
private LocalDateTime createdOn;
#Column(name = "updated_on")
#UpdateTimestamp
private LocalDateTime updatedOn;
}
Repository:
#Repository()
public interface AccountRepository extends CrudRepository<Account, String> {
}
Tried with JpaRepository<Account, Long> too and flush after saving..but still getting id null in return list response of saveall()
Service:
#Service
public class AccountsService {
#Autowired
private AccountRepository repository;
#Override
#Transactional
public List<Account> saveAll(List<Account> accounts) {
//in case of JpaRepository
List<Account> savedAccounts= repository.saveAll(accounts);
repository.flush();
return savedAccounts;
//in case of CrudRepository
return (List<Account>)repository.saveAll(accounts);
}
}
when executing this
//accountsList received from FB API
List<Account> savedList=iAccountsService.saveAll(accountsList);
savedList.get(0).getId() **//this is coming as null**
Any sort of help is appreciated.
In your entity class :
Use this #GeneratedValue(strategy = GenerationType.IDENTITY)
public class Account implements Serializable{
#JsonIgnore
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(unique = true, nullable = false, insertable = false, updatable = false)
private Long id;
}

How to count records with where clause in jpa test with latest spring-boot?

I have UserRepository:
public interface UserRepository extends JpaRepository<User, String> {}
The entity:
#Entity
#Table(schema="test", name = "TBL_USERS")
#Builder
#AllArgsConstructor
public class User implements Persistable<String> {
#Id
#Column(name = "ID", columnDefinition = "char")
private String id;
#NotNull
#Column(name = "NAME", columnDefinition = "char", nullable = false)
private String name;
...
}
And in my test I want to count records with certain name like the query:
select count(*) from TBL_USERS where name='John';
#Test
public void testCountSimilarNames() {
...
userRepository.count() ... ?
}
I use latest spring-boot.
You need something like :
public interface UserRepository extends CrudRepository<User , String >{
Integer countByName(String name);
}

Resources