Direct self-reference leading to cycle - java

I'm trying to send a request to get back an array of an object - Coupon when I submit the request I get the answer-
Direct self-reference leading to cycle (through reference chain:
java.util.HashSet[0] => model.Coupon["emptyCoupon"] => model.Coupon["emptyCoupon"])
The model.Coupon probably does the problem.
empty coupon is intended to be returned if the requested coupon does not exist.
public static final int NO_ID = -1;
private static final Coupon EMPTY_COUPON = new Coupon(NO_ID, null, null, null, NO_ID, NO_ID, null, NO_ID, null);
private long id = NO_ID;
private String title;
private LocalDate startDate;
private LocalDate endDate;
private int amount;
private int category;
private String message;
private double price;
private String image;
public Coupon() {
}
private Coupon(long id, String title, LocalDate start_date, LocalDate end_date, int amount, int category,
String message, double price, String image) {
this.id = id;
this.title = title;
this.startDate = start_date;
this.endDate = end_date;
this.amount = amount;
this.category = category;
this.message = message;
this.price = price;
this.image = image;
}
public Coupon getEmptyCoupon() {
return EMPTY_COUPON;
}
Before I added the EMPTY_COUPON I had no problems with the requests.
I want the emptyCoupon in the code, and I'll be happy to help

Since you are serializing to JSON or XML with Jersey, you may not have cycles in your object graph.
Jersey doesn't have a #JsonBackReference like Jackson does, so you might consider to move the EMPTY_COUPON in a separate class (something like Constants.java) and obtain it from there.
Other options are to add #XmlIgnore to your field or to switch to another JSON serializer like Jackson.

Related

Is it possible to change mysql to jpaquery?

I tried to create the mysql code in #query, but failed to validate, so i want to make this sql code exactly the same as querydsl, can someone help me put the sum and the hypothesis in the dsl query? Do you have any documentation on this? or it is not possible to do so. Thank you for your time and your help will be invaluable! I'm really trying my best to deal with this problem.
Mysql:
SELECT id_product,date,
sum(case
when action_description = "import"
then quantity_product
else -quantity_product
END) as test
FROM testdb.warehouse_management
inner join product
on warehouse_management.product_id = product.id_product
where id_product = 3 and date <= 1200
group by id_product,date
Querydsl:
public class ManagementRepositoryImpl implements ManagementRepositoryCustom {
#PersistenceContext
private EntityManager entityManager;
#Override
public List<StockRecoveryDTO> findTotal(Long id_product, String date){
JPAQuery<StockRecoveryDTO> stockRecoveryDTOJPAQuery = new JPAQuery<>(entityManager);
QManagement management = QManagement.management;
QProduct product = QProduct.product;
return stockRecoveryDTOJPAQuery.select(Projections.bean(StockRecoveryDTO.class,
product.id_product,
management.date,
product.quantity_product,
management.action_description,
management.id_action,
management.quantity))
.from(management)
.innerJoin(product)
.on(management.product_id.eq(product)
DTO: package com.example.dto;
public class StockRecoveryDTO {
private Long id_product;
private String date;
private int quantity_product;
private String action_description;
private Long id_action;
private String quantity;
private int total;
public StockRecoveryDTO() {
}
public StockRecoveryDTO(Long id_product, String date, int quantity_product, String action_description, Long id_action, String quantity, int total) {
this.id_product = id_product;
this.date = date;
this.quantity_product = quantity_product;
this.action_description = action_description;
this.id_action = id_action;
this.quantity = quantity;
this.total = total;
}
//GETTER SETTER

Adding an object to a List of another type

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;
}

POJO serialization problems

In the past I have had no problems serializing and deserializing POJOs using GSon library. But ever since I modularization my project and updated my Android studio to 4.1, any POJO I try to serialize returns me a bad value here is an example.
The expected result
dSecBook.toString ==> DSecBook{sd='for the love of God and I not e', np='26.5', op='null', img='null', id='null'}
the result I'm getting
dSecBook.toJSon ==> {"b":"for the love of God and I not e","c":"26.5"}
Here is my POJO which is an SQL query derivative
public class DSecBook implements Serializable {
#ColumnInfo(name = "short_description")
public String sd;
#ColumnInfo(name = "newPrice")
public String np;
#ColumnInfo(name = "oldPrice")
public String op;
#ColumnInfo(name = "pro_download_thumbUrl")
public String img;
#ColumnInfo(name = "proID")
public String id;
public DSecBook() {
//for firebase
}
public DSecBook(String sd, String np, String op, String img, String id) {
this.sd = sd;
this.np = np;
this.op = op;
this.img = img;
this.id = id;
}
........
}
Problem is even firebase is giving the same result, this is killing my work
Please help

java.time.format.DateTimeParseException, Date could not be parsed

I am trying to create an application using springboot-java,
front end as html/css/javascript. I get the below error while doing a post to create an employee record. I am passing a join date which is causing the error.
failed - {"readyState":4,
"responseText":"{\"timestamp\":1515066928232,
\"status\":500,
\"error\":\"Internal Server Error\",
\"exception\":\"java.time.format.DateTimeParseException\",
\"message\":\"Text '01-17-2018' could not be parsed at index 0\",
\"path\":\"/employee/\"}",
"responseJSON":{"timestamp":1515066928232,
"status":500,
"error":"Internal Server Error",
"exception":"java.time.format.DateTimeParseException",
"message":"Text '01-17-2018' could not be parsed at index 0",
"path":"/employee/"},
"status":500,
"statusText":"error"}
Below is the code I use in java:
private static final long serialVersionUID = -7314008048174880868L;
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("MM-dd-yyyy");
private Integer organisation;
private String empName;
private String joinDate;
private String gender;
private String designation;
private String email;
public EmployeeDto(){
}
public EmployeeDto(Integer organisation, String empName, String joinDate, String gender,
String designation, String email) {
super();
this.organisation = organisation;
this.empName = empName;
this.joinDate = joinDate;
this.gender = gender;
this.designation = designation;
this.email = email;
}
public Employee buildEmployee(){
return new Employee(this.empName,LocalDate.parse(this.joinDate),this.gender,this.designation,this.email);
}
I use the below date converter:
#Converter(autoApply = true)
public class LocalDateAttributeConverter implements AttributeConverter<LocalDate, Date> {
#Override
public Date convertToDatabaseColumn(LocalDate locDate) {
return (locDate == null ? null : Date.valueOf(locDate));
}
#Override
public LocalDate convertToEntityAttribute(Date sqlDate) {
return (sqlDate == null ? null : sqlDate.toLocalDate());
}
}
I am unable to find the root cause....
In buildEmployee() I think you want LocalDate.parse(this.joinDate, DATE_FORMAT) instead of LocalDate.parse(this.joinDate).
One often posted link here on Stack Overflow is How to debug small programs. In that blog post the first tip is to turn on compiler warnings and read them carefully. Putting your code into my Eclipse produces the following warning:
The value of the field EmployeeDto.DATE_FORMAT is not used
This may cause you to wonder why DATE_FORMAT is not used and why you wanted to have it there in the first place. Which in turn could inspire you to use it as intended, which fixes your error.

Instance of class as key in hashmap

I have this class:
public class Offer {
private Integer id;
private String description;
private Double price;
private String currency;
private Date timeExpired;
public Offer(Integer id, String description, Double price, String currency, Date timeExpired){
this.id = id;
this.description = description;
this.price = price;
this.currency = currency;
this.timeExpired = timeExpired;
}
}
I want to create a hashmap with key that refers to id of the class Offer and value as Offer.
HashMap<id of Offer(?),Offer> repo = new HashMap<id of Offer(?),Offer>();
How can I do that?
How assign each Offer id as key and the Offer objects as values on Hashmap repo?
I mean method repo.put(?)
Because the id is an Integer your need a HashMap<Integer, Offer>:
public static void main(String[]args){
HashMap<Integer, Offer> map = new HashMap<Integer, Offer>();
// First way
map.put(1038, new Offer(1038, "foo", 10.20, "bar", new Date()));
// Second way
Offer o1 = new Offer(1038, "foo", 10.20, "bar", new Date());
map.put(o1.getId(), o1);
}
Tips :
use int and double rather than Integer or Double if you don't really need the objects (int vs Integer)
use LocalDate instead of Date it's the latest version, and easier to use

Categories