I have this Rest endpoint which returns table with IDs:
#GetMapping("pages")
public Page<ContractDTO> pages(#RequestParam(value="page") int page, #RequestParam(value="size") int size) {
return contractService.findAll(page, size).map(mapper::toDTO);
}
ContractDTO DTO:
public class ContractDTO {
private Integer id;
private String name;
private Integer gateway;
private Integer reseller_id;
private Integer acquirer_id;
private Integer terminal_id;
private Integer merchant_id;
private String descriptor;
...
}
I store into database table the ID's of each additional component like acquirer_id, terminal_id and etc.
I need to do additional SQL request like SELECT * FROM acquirers WHERE id = 3.
How I can make this after I convert the DTO object with Java?
Related
I'm trying to return the record that I got from my database. But I'm having a problem on how I can do that because the data than I retrieved from the database is in a different class from the return parameter.
public List<Record> getRecord(List<Request> requests) {
List<Record> records = new ArrayList<>();
for (Request request : requests) {
Billing billing = billingRepository
.findByBillingCycleAndStartDateAndEndDate(
request.getBillingCycle()
, request.getStartDate()
, request.getEndDate());
if (billing != null) {
// Need to add "billing" to "records" list here
}
}
return records;
}
Record.class
public class Record {
private int billingCycle;
private LocalDate startDate;
private LocalDate endDate;
private String accountName;
private String firstName;
private String lastname;
private double amount;
public Record() {
}
//Getters and setters
Billing.class
public class Billing {
private int billingId;
private int billingCycle;
private String billingMonth;
private Double amount;
private LocalDate startDate;
private LocalDate endDate;
private String lastEdited;
private Account accountId;
public Billing() {
}
//Getters and setters
What can I do? and please explain the answer so I can understand it. I really want to learn
You can use DozerMapper. It will map the object to another object having same name properties or you have to write the mapping in the dozer-mapping xml.
Lets come to your question. Here you are trying to convert your entity to another object.
For that you have to write mapping code. It will be something like this and it is very common practice to convert entity objects to another object before using them.
Record toRecord(Billing billing) {
if(billing == null) {
return null;
}
Record record = new Record();
record.setBillingCycle = billing.getBillingCycle();
...
...
// other properties
...
return record;
}
I'm trying to achive a findAllByUUID using mongo-spring-boot, but with no luck.
What I have:
public interface CarMatchRepository extends MongoRepository<CarMatchEntity, String> {
List<CarMatchEntity> findAllByCarID(Iterable<UUID> ids);
CarMatchEntity findByCarID(UUID carID);
}
Function call:
public void addCarsToCollection(String id, List<UUID> carId) {
List<CarMatchEntity> entities = carMatchRepository.findAllByCarID(carId); <--- empty
}
If I call findByCarID() it retrieves correctly a single object (if exists) but using Iterable the query does not fail, but it never returns any object. Am I doing something wrong here or am I taking the wrong road for this problem?
Thanks!
Edit:
#Document(collection = "car_index")
public class CarMatchEntity implements Serializable {
#Id
private String id;
private UUID carID;
//partner data
private UUID partnerID;
private String partnerThumbURL;
private String partnerName;
private Date partnerMembershipSince;
// car location
private List<Double> location;
private String district;
private String city;
// car data
private CarType carType;
private String carBrand;
private String carModel;
private String carPlate;
private List<CarFeature> carFeatures;
private String carAddress;
private String description;
private BigDecimal hourFare;
private BigDecimal dayFare;
private BigDecimal weekFare;
private BigDecimal dailyPrice;
private BigDecimal suggestedHourlyPrice;
private BigDecimal suggestedDailyPrice;
private BigDecimal suggestedWeeklyPrice;
private String carThumbURL;
private Map<String, CarPhotos> carPhotosURL;
private CarAvailability availability;
private CarStatus carStatus;
private String carYear;
private FuelType fuelType;
#Transient
private DayOfWeek prohibitedDay;
private String carYearModel;
#Transient
private double partnerRating = 5.0;
private CarTransmission carTransmission;
private CarColor carColor;
private String odometer;
private Integer manufactureYear;
private String fipeCode;
private String renavam;
private String chassi;
private InsuranceCompany insuranceCompany;
private List<CarSpecialFeature> carSpecialFeatures;
private BigDecimal deductible;
private Boolean superCar;
public CarMatchEntity() {
}
Try using JSON based queries with SpEL expressions
#Query("{carID: { $in: ?0 } })")
List<CarMatchEntity> findAllByCarIds(List<UUID> ids);
Use
List<CarMatchEntity> findAllByCarIDIn(Iterable<UUID> ids);
instead of
List<CarMatchEntity> findAllByCarID(Iterable<UUID> ids);
UPDATE:
Did you try to explicitly declare JPQL query instead of relying on Spring Data query generation mechanism?
#Query("select e from CarMatchEntity e where e.carID in (:ids)")
List<CarMatchEntity> findAllByCarID(#Param("ids") Iterable<UUID> ids);
UPDATE 2:
Another solution I would try is to declare argument ids in findAllByCarIDIn method as Collection<UUID> instead of Iterable<UUID>.
I have a POJO defined for a dynamodb Table like this:
public class DynamoDBTablePojo {
#NonNull
private String requestId;
#NonNull
private String responseId;
private String responseBlob;
#DynamoDBHashKey(attributeName = "RequestId")
public String getRequestId(){return this.requestId;};
#DynamoDBAttribute(attributeName = "ResponseId")
public String getResponseId(){return this.responseId;};
#DynamoDBAttribute(attributeName = "ResponseBlob")
public String getResponseBlob() {return responseBlob;}
}
I want to write a function in java which will take attribute name and DynamoDBTablePojo object and returns the value of that attribute. e.g.,
String func(String attributeName, DynamoDBTablePojo dynamoDBTablePojoObj){
// returns value associated with this attribute.
}
When I try to access the following REST service, it returns all data plus a field that does not exist in the "SupplierPayment" entity class "customerId".
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<SupplierPayment> getAllSupplierPaymentsService() {
return (ArrayList<SupplierPayment>) supplierPaymentDao.getAllSupplierPayments();
}
Here is the getAllSupplierPayments() method:
public List<SupplierPayment> getAllSupplierPayments() {
String query = "SELECT * FROM supplierpayment";
return (ArrayList<SupplierPayment>) getJdbcTemplate().query(query,
new BeanPropertyRowMapper<SupplierPayment>(SupplierPayment.class));
}
Here are all the fields in the "SupplierPayment" class:
private Integer supplierPaymentId;
private BigDecimal amount;
private Integer purchaseInvoiceId;
private Integer supplierId;
private Integer paymentMethodId;
private String description;
private Integer checkId;
private Integer fromBankAccountId;
private Integer toBankAccountId;
private String creditCardNo;
private Timestamp created;
private Integer createdBy;
When I debug, I find that the ArrayList of the web service does not return that field, then somehow I find that field in the response.
I tried truncating and dropping the table and adding the columns one after the other. What I found is the field is returned in the response only when I add the column "supplierId" to the table and its value is the same of "supplierId". I think the column "customerId" existed before and I dropped it.
I found that the following getter and setter existed in the SupplierPayment entity class because of the previously existing column in the table:
public Integer getCustomerId() {
return supplierId;
}
public void setCustomerId(Integer customerId) {
this.supplierId = customerId;
}
By removing them, the problem was solved.
I have a structure of lists that I would like to populate from database. I've already mapped all tables and insertion methods. However I don't know what is the best approach to get all those data and populate my Java Objects. I have this structure:
public class DailySchedule {
private long id;
private List<Task> tasks;
private List<Plan> plans;
}
public class Task {
private long id;
private long duration;
private String description;
private Date date;
}
public class Plan {
private long id;
private String description;
private Date date;
private List<User> users;
}
public class User {
private long id;
private String name;
}
Should I create a huge INNERJOIN and get all the data (including repeated info) and try to populate the Java Objects or I should get all the Id's from each table and perform a loop in Java(using cursor) and perform Selects by ID's and populate the tables?
I assume you have below tables
daily_schedule
task
plan
user
Code
public List<DailySchedule> getDailySchedules(){
SQLiteDatabase db = getReadableDataBase();
Cursor dailyScheduleCursor = db.rawQuery(“Select * from daily_schedule ”);
List<DailySchedule> all = new ArrayList<>();
While(dailyScheduleCursor.next()){
DailySchedule dailySchedule = new DailySchedule();
dailySchedule.setId(dailyScheduleCursor.getLong(0));
dailySchedule.setTasks(getTasks(dailyScheduleCursor.getLong(0)));
dailySchedule.setPlans(getTasks(dailyScheduleCursor.getLong(0)));
all.add(dailySchedule);
}
db.close();
}
public List<Task> getTasks(int id ){
SQLiteDatabase db = getReadableDataBase();
Cursor taskCursor = db.rawQuery(“Select * from tasks where id =’”+id+”’ ”);
List<Task> all = new ArrayList<>();
While(taskCursor.next()){
Task task = new task();
task.setId(taskCursor.getLong(0));
// set other attributes
all.add(task);
}
db.close();
return all;
}
public List<Plan> getPlan(int id ){
getUser(id);// get all plans
// set user
return plans;
}
public User(int id){
//create user from data
return user;
}
Then call getDailySchedules() from somewhere.
Note If you want to see your SQLite databse content, use
AndroidDBvieweR