Nested JSON data show in a Vaadin grid - java

I'm new to Java and Vaadin and stuck during display data in a Vaadin grid. I have data in JSON format like:
[
{
"id":1,
"name":"testSiteC",
"accountId":1,
"accountData":{
"id":1,
"name":"testAccountA",
"code":"AC0001",
"salesStaffId":200,
"samplingDate":1493038800000,
"startDate":1493038800000,
"creditPeriod":15,
"cinNo":"testCinNo",
"vatRegistrationNo":"testVatRegistrationNo",
"panNo":"testPanNo",
"serviceTaxRegistrationNo":"testServiceTaxRegistrationNo",
"isActive":true,
"billingType":"testBillingType",
"billingBasis":"cup count basis",
"billingAddress":"billingAddress",
"consigneeAddress":"test",
"clientRelationshipManagerStaffId":2,
"opsManagerId":1,
"serviceTaxId":1,
"createdOn":1483209000000,
"updatedOn":1494949002000
},
"building":"3rd floor",
"locality":"Koramangala",
"city":"Bangalore",
"state":"Karnataka",
"country":"India",
"peopleCount":100,
"staffInCharge":1,
"dailyStartTime":"23:34:23",
"dailyEndTime":"23:34:34",
"createdOn":1493799889000,
"updatedOn":1494945760000,
"isActive":true,
"opsStartDate":1493730000000
}
]
Bean to be nested:
package com.chaipoint.boxc.common.model;
import java.io.Serializable;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Date;
public class SiteResponse implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private Integer accountId;
private AccountResponse accountData;
private String building;
private String locality;
private String city;
private String state;
private String country;
private Integer peopleCount;
private Integer staffInCharge;
private Time dailyStartTime;
private Time dailyEndTime;
private Date createdOn;
private Timestamp updatedOn;
private Boolean isActive;
private Date opsStartDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAccountId() {
return accountId;
}
public void setAccountId(Integer accountId) {
this.accountId = accountId;
}
public AccountResponse getAccountData() {
return accountData;
}
public void setAccountData(AccountResponse accountData) {
this.accountData = accountData;
}
public String getBuilding() {
return building;
}
public void setBuilding(String building) {
this.building = building;
}
public String getLocality() {
return locality;
}
public void setLocality(String locality) {
this.locality = locality;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Integer getPeopleCount() {
return peopleCount;
}
public void setPeopleCount(Integer peopleCount) {
this.peopleCount = peopleCount;
}
public Integer getStaffInCharge() {
return staffInCharge;
}
public void setStaffInCharge(Integer staffInCharge) {
this.staffInCharge = staffInCharge;
}
public Time getDailyStartTime() {
return dailyStartTime;
}
public void setDailyStartTime(Time dailyStartTime) {
this.dailyStartTime = dailyStartTime;
}
public Time getDailyEndTime() {
return dailyEndTime;
}
public void setDailyEndTime(Time dailyEndTime) {
this.dailyEndTime = dailyEndTime;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public Timestamp getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Timestamp updatedOn) {
this.updatedOn = updatedOn;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
public Date getOpsStartDate() {
return opsStartDate;
}
public void setOpsStartDate(Date opsStartDate) {
this.opsStartDate = opsStartDate;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
Bean containing a nested bean
public class SitePantryResponse implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private Integer siteId;
private SiteResponse siteData;
private Integer floorNo;
private Date createdOn;
private Timestamp updatedOn;
private Boolean isActive;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSiteId() {
return siteId;
}
public void setSiteId(Integer siteId) {
this.siteId = siteId;
}
public SiteResponse getSiteData() {
return siteData;
}
public void setSiteData(SiteResponse siteData) {
this.siteData = siteData;
}
public Integer getFloorNo() {
return floorNo;
}
public void setFloorNo(Integer floorNo) {
this.floorNo = floorNo;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public Timestamp getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Timestamp updatedOn) {
this.updatedOn = updatedOn;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
So, while displaying data into the grid like table.addColumn(SitePantryResponse::getSiteData::getName).setCaption("Site Name") it throws:
The target type of this expression must be a functional interface` error.

SitePantryResponse::getSiteData::getName
It's not possible to chain method references like that. You can use simple lambda expression instead:
table.addColumn(r -> r.getSideDate().getName()).setCaption("Site Name")
or if you really want to use method references, you can use a helper method which will chain them and return ValueProvider which can be later passed to Grid.addColumn:
<A, B, C> ValueProvider<A, C> chain(Function<A, B> f1, Function<B, C> f2) {
return f1.andThen(f2)::apply;
}
With this you can write:
table.addColumn(chain(SitePantryResponse::getSiteData, SiteResponse::getName)).setCaption("Site Name")
but, as you can see, this makes the code more complicated and longer, so there is no reason to use this approach over simple lambda expression.

Related

How to only update certain fields that might already be null (using JSON patch)

I am trying to use json patch to update an object using PATCH in my app.
I want to update only 2 fields in my object and they might be null before updating.
Each time I try and update, the whole object gets updated.
How do I restrict this?
I've tried multiple ways.
#PatchMapping("/bmwsales/updateweb/{id}")
public ResponseEntity<?> updateVehicleTagWeb(#PathVariable(value="id") Integer id, #RequestBody Bmwsales v) throws JsonProcessingException{
ObjectMapper objMapper=new ObjectMapper();
JsonPatchBuilder jsonPatchBuilder=Json.createPatchBuilder();
JsonPatch jsonPatch=jsonPatchBuilder.replace("/templocation",v.getTemplocation()).replace("/rfidtag", v.getRfidtag()).build();
Bmwsales vehicle=bmwService.getVin(id).orElseThrow(ResourceNotFoundException::new);
BmwsalesUpdate veh=oMapper.asInput(vehicle);
BmwsalesUpdate vehPatched=patchHelp.patch(jsonPatch, veh, BmwsalesUpdate.class);
oMapper.update(vehicle, vehPatched);
System.out.println("the patched info is: "+vehicle.getRfidtag()+vehicle.getTemplocation());
bmwService.updateVehTag(vehicle);
return new ResponseEntity<>(HttpStatus.OK);
#Override
public void updateVehTag(Bmwsales vehicle) {
bmwsalesRepository.save(vehicle);
}
Jackson config:
#Configuration
public class JacksonConfig {
#Bean
public ObjectMapper objectMapper(){
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.findAndRegisterModules();
}}
Bmwsales class
#Entity(name="bmwsales")
#Table(name="bmwsales")
public class Bmwsales implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
#Column(name="customerfirstname")
private String customerfirstname;
#Column(name="customerlastname")
private String customerlastname;
#Column(name="lastmileage")
private Integer lastmileage;
#Column(name="licensenum")
private String licensenum;
#Column(name="make")
private String make;
#Column(name="currentmileage")
private Integer currentmileage;
#Column(name="model")
private String model;
#Column(name="purchasedhere")
private String purchasedhere;
#JsonSerialize(using = JsonDateSerializer.class)
#Column(name="rfiddate")
private Timestamp rfiddate;
#Column(name="rfidtag")
private String rfidtag;
#Column(name="stocknum")
private String stocknum;
#Column(name="vehiclerole")
private String vehiclerole;
#NotBlank
#Column(name="vin")
private String vin;
#Column(name="year")
private Timestamp year;
#Column(name="vineight")
private String vineight;
#Column(name="taggingsource")
private String taggingsource;
#Column(name="vehicletype")
private String vehicletype;
#Column(name="salutation")
private String customersal;
#Column(name="customermiddlename")
private String customermiddlename;
#Column(name="suffix")
private String suffix;
#Column(name="address1")
private String address1;
#Column(name="address2")
private String address2;
#Column(name="city")
private String city;
#Column(name="state")
private String state;
#Column(name="zip")
private String zip;
#Column(name="county")
private String county;
#Column(name="homephone")
private String homephone;
#Column(name="cellphone")
private String cellphone;
#Column(name="email")
private String email;
#Column(name="cobuyersalutation")
private String cobuyersal;
#Column(name="cobuyerfirstname")
private String cobuyerfirstname;
#Column(name="cobuyermiddlename")
private String cobuyermiddlename;
#Column(name="cobuyerlastname")
private String cobuyerlastname;
#Column(name="salesperson")
private String salesperson;
#Column(name="salesperson2")
private String salesperson2;
#Column(name="purchasedheredate")
private Timestamp purchasedheredate;
#Column(name="carwashmember")
private String carwashmember;
#Column(name="serviceadvisor")
private String serviceadvisor;
#JsonSerialize(using = JsonDateSerializer2.class)
#Column(name="openrodate")
private Date openrodate;
#Column(name="closerodate")
private Timestamp closerodate;
#Column(name="openro")
private String openro;
#Column(name="snstext")
private Timestamp snstext;
#Column(name="carwashexpire")
private Timestamp carwashexpire;
#Column(name="enterrodate")
private Timestamp enterrodate;
#Column(name="servicecarwash")
private String servicecarwash;
#Column(name="templocation")
private String templocation;
public Bmwsales(String vineight){
this.vineight=vineight;
}
public static class Builder{
private Integer id;
private String rfidtag;
//#JsonSerialize(using = JsonDateSerializer.class)
private Timestamp rfiddate;
private String vin;
private String vineight;
private String templocation;
public Builder setVin(String vin) {
this.vin=vin;
return this;
}
public Builder setVineight(String vineight) {
this.vineight=vineight;
return this;
}
public Builder setRfidtag(String rfidtag) {
this.rfidtag=rfidtag;
return this;
}
public Builder setRfiddate(Timestamp rfiddate) {
this.rfiddate=rfiddate;
return this;
}
public Builder setTemplocation(String templocation) {
this.templocation=templocation;
return this;
}
/*public Builder setOpenro(String openro){
this.openro=openro;
return this;
}
public Builder setOpenrodate(Date openrodate){
this.openrodate=openrodate;
return this;
}*/
public Bmwsales build(){
Bmwsales bmwsales=new Bmwsales(vin, vineight,rfidtag,rfiddate,
templocation);
return bmwsales;
}
}
public Bmwsales(String vin, String vineight, String rfidtag, Timestamp
rfiddate, String templocation){
this.vin=vin;
this.vineight=vineight;
this.rfiddate=rfiddate;
this.rfidtag=rfidtag;
this.templocation=templocation;
}
public Bmwsales(String customersal, String customerfirstname, String
customerlastname, String customermiddlename, String suffix,
String make, Integer currentmileage, String model, String
purchasedhere, String vehiclerole, String vin, String vineight,
Timestamp year, String taggingsource, String vehicletype,
String address1, String address2, String city, String state,
String zip, String county, String homephone, String cellphone,
String email, String cobuyersal, String cobuyerfirstname,
String cobuyermiddlename, String cobuyerlastname, String
salesperson, String salesperson2, Timestamp purchasedheredate,
String carwashmember, String serviceadvisor, Date openrodate,
Timestamp closerodate, Timestamp snstext, String openro,
Timestamp carwashexpire, Timestamp enterrodate, String
servicecarwash, Timestamp rfiddate, String rfidtag, String templocation){
super();
this.customersal=customersal;
this.customerfirstname=customerfirstname;
this.customermiddlename=customermiddlename;
this.customerlastname=customerlastname;
this.suffix=suffix;
this.make=make;
this.currentmileage=currentmileage;
this.model=model;
this.purchasedhere=purchasedhere;
this.vehiclerole=vehiclerole;
this.vin=vin;
this.vineight=vineight;
this.year=year;
this.taggingsource=taggingsource;
this.vehicletype=vehicletype;
this.address1=address1;
this.address2=address2;
this.city=city;
this.state=state;
this.zip=zip;
this.county=county;
this.homephone=homephone;
this.cellphone=cellphone;
this.email=email;
this.cobuyersal=cobuyersal;
this.cobuyerfirstname=cobuyerfirstname;
this.cobuyermiddlename=cobuyermiddlename;
this.cobuyerlastname=cobuyerlastname;
this.salesperson=salesperson;
this.salesperson2=salesperson2;
this.purchasedheredate=purchasedheredate;
this.carwashmember=carwashmember;
this.serviceadvisor=serviceadvisor;
this.openrodate=openrodate;
this.closerodate=closerodate;
this.snstext=snstext;
this.openro=openro;
this.carwashexpire=carwashexpire;
this.enterrodate=enterrodate;
this.servicecarwash=servicecarwash;
this.rfiddate=rfiddate;
this.rfidtag=rfidtag;
this.templocation=templocation;
};
public Bmwsales(){
}
public void setId(Integer id) {
this.id=id;
}
public Integer getId() {
return id;
}
public void setCustomersal(String customersal) {
this.customersal=customersal;
}
public String getCustomersal() {
return customersal;
}
public void setCustomerfirstname(String customerfirstname) {
this.customerfirstname=customerfirstname;
}
public String getCustomerfirstname() {
return customerfirstname;
}
public void setCustomermiddlename(String customermiddlename) {
this.customermiddlename=customermiddlename;
}
public String getCustomermiddlename() {
return customermiddlename;
}
public void setCustomerlastname(String customerlastname) {
this.customerlastname=customerlastname;
}
public String getCustomerlastname() {
return customerlastname;
}
public void setSuffix(String suffix) {
this.suffix=suffix;
}
public String getSuffix() {
return suffix;
}
public void setMake(String make) {
this.make=make;
}
public String getMake() {
return make;
}
public void setCurrentmileage(Integer currentmileage) {
this.currentmileage=currentmileage;
}
public Integer getCurrentmileage() {
return currentmileage;
}
public void setModel(String model) {
this.model=model;
}
public String getModel() {
return model;
}
public void setPurchasedhere(String purchasedhere) {
this.purchasedhere=purchasedhere;
}
public String getPurchasedhere() {
return purchasedhere;
}
public void setVehiclerole(String vehiclerole) {
this.vehiclerole=vehiclerole;
}
public String getVehiclerole() {
return vehiclerole;
}
public void setVin(String vin) {
this.vin=vin;
}
public String getVin() {
return vin;
}
public void setVineight(String vineight) {
this.vineight=vineight;
}
public String getVineight() {
return vineight;
}
public void setYear(Timestamp year) {
this.year=year;
}
public Timestamp getYear() {
return year;
}
public void setTaggingsource(String taggingsource) {
this.taggingsource=taggingsource;
}
public String getTaggingsource() {
return taggingsource;
}
public void setVehicletype(String vehicletype) {
this.vehicletype=vehicletype;
}
public String getVehicletype() {
return vehicletype;
}
public void setAddress1(String address1) {
this.address1=address1;
}
public String getAddress1() {
return address1;
}
public void setAddress2(String address2) {
this.address2=address2;
}
public String getAddress2() {
return address2;
}
public void setCity(String city) {
this.city=city;
}
public String getCity() {
return city;
}
public void setState(String state) {
this.state=state;
}
public String getState() {
return state;
}
public void setZip(String zip) {
this.zip=zip;
}
public String getZip() {
return zip;
}
public void setCounty(String county) {
this.county=county;
}
public String getCounty() {
return county;
}
public void setHomephone(String homephone) {
this.homephone=homephone;
}
public String getHomephone() {
return homephone;
}
public void setCellphone(String cellphone) {
this.cellphone=cellphone;
}
public String getCellphone() {
return cellphone;
}
public void setEmail(String email) {
this.email=email;
}
public String getEmail() {
return email;
}
public void setCobuyersal(String cobuyersal) {
this.cobuyersal=cobuyersal;
}
public String getCobuyersal() {
return cobuyersal;
}
public void setCobuyerfirstname(String cobuyerfirstname) {
this.cobuyerfirstname=cobuyerfirstname;
}
public String getCobuyerfirstname() {
return cobuyerfirstname;
}
public void setCobuyermiddlename(String cobuyermiddlename) {
this.cobuyermiddlename=cobuyermiddlename;
}
public String getCobuyermiddlename() {
return cobuyermiddlename;
}
public void setCobuyerlastname(String cobuyerlastname) {
this.cobuyerlastname=cobuyerlastname;
}
public String getCobuyerlastname() {
return cobuyerlastname;
}
public void setSalesperson(String salesperson) {
this.salesperson=salesperson;
}
public String getSalesperson() {
return salesperson;
}
public void setSalesperson2(String salesperson2) {
this.salesperson2=salesperson2;
}
public String getSalesperson2() {
return salesperson2;
}
public void setPurchasedheredate(Timestamp purchasedheredate) {
this.purchasedheredate=purchasedheredate;
}
public Timestamp getPurchasedheredate() {
return purchasedheredate;
}
public void setCarwashmember(String carwashmember) {
this.carwashmember=carwashmember;
}
public String getCarwashmember() {
return carwashmember;
}
public void setServiceadvisor(String serviceadvisor) {
this.serviceadvisor=serviceadvisor;
}
public String getServiceadvisor() {
return serviceadvisor;
}
public void setOpenrodate(Date openrodate) {
this.openrodate=openrodate;
}
public Date getOpenrodate() {
return openrodate;
}
public void setCloserodate(Timestamp closerodate) {
this.closerodate=closerodate;
}
public Timestamp getCloserodate() {
return closerodate;
}
public void setSnstext(Timestamp snstext) {
this.snstext=snstext;
}
public Timestamp getSnstext() {
return snstext;
}
public void setOpenro(String openro) {
this.openro=openro;
}
public String getOpenro() {
return openro;
}
public void setCarwashexpire(Timestamp carwashexpire) {
this.carwashexpire=carwashexpire;
}
public Timestamp getCarwashexpire() {
return carwashexpire;
}
public void setEnterrodate(Timestamp enterrodate) {
this.enterrodate=enterrodate;
}
public Timestamp getEnterrodate() {
return enterrodate;
}
public void setServicecarwash(String servicecarwash) {
this.servicecarwash=servicecarwash;
}
public String getServicecarwash() {
return servicecarwash;
}
public void setRfiddate(Timestamp rfiddate) {
this.rfiddate=rfiddate;
}
public Timestamp getRfiddate() {
return rfiddate;
}
public void setRfidtag(String rfidtag) {
this.rfidtag=rfidtag;
}
public String getRfidtag() {
return rfidtag;
}
public void setTemplocation(String templocation) {
this.templocation=templocation;
}
public String getTemplocation() {
return templocation;
}
public static Object Builder() {
return new Bmwsales.Builder();
}
}
How do I update only these fields?
Your code is long one why are you code getters/setters/constructors from typing.it will get a long time to develop.
Then what you must add this dependency into your POM.xml file
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
And adding this dependency you can generate your getters/setters and constructors from giving simple annotations like this.do not type those in your fingers.:-)
Then your code will be more easy to readable.
#Data //this will create all getters,setters,toString
#NoArgsConstructor //this will create default constructor
#AllArgsConstructor //this will create all argivements constructor
#Entity(name="bmwsales") //name means table name
public class Bmwsales implements Serializable{
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
// like this do all your columns
#NotNull(message="customer First Name is compulsory")
#Column(name="customerfirstname")
private String customerfirstname;
//your entity mapping here etc.
}
After that, if the user does not fill the required fields that message will trigger.
And your controller class that means your endpoint calling place should use #Valid annotation to your Entity class or DTO class(you do not get DTO).
#PatchMapping("/bmwsales/updateweb/{id}")
public ResponseEntity<String> updateVehicleTagWeb(#PathVariable(value="id") Integer id, #Valid #RequestBody Bmwsales v) throws JsonProcessingException{
ObjectMapper objMapper=new ObjectMapper();
JsonPatchBuilder jsonPatchBuilder=Json.createPatchBuilder();
JsonPatch jsonPatch=jsonPatchBuilder.replace("/templocation",v.getTemplocation()).replace("/rfidtag", v.getRfidtag()).build();
Bmwsales vehicle=bmwService.getVin(id).orElseThrow(ResourceNotFoundException::new);
BmwsalesUpdate veh=oMapper.asInput(vehicle);
BmwsalesUpdate vehPatched=patchHelp.patch(jsonPatch, veh, BmwsalesUpdate.class);
oMapper.update(vehicle, vehPatched);
System.out.println("the patched info is: "+vehicle.getRfidtag()+vehicle.getTemplocation());
bmwService.updateVehTag(vehicle);
return ResponseEntity.ok("Input is valid");
For more understanding what I said to refer to this link:-
https://www.baeldung.com/spring-boot-bean-validation

show all list query java hibernate

i have this function to query in hibernate:
public List<TransactionQR> getAllTransaction() throws HibernateException {
return this.session.createQuery("SELECT id FROM TransactionQR").list();
}
then is success to show the data like this in html:
[2, 3]
but when i add more column in SELECT like this:
public List<TransactionQR> getAllTransaction() throws HibernateException {
return this.session.createQuery("SELECT id, codeqr FROM TransactionQR").list();
}
the result show like this:
[Ljava.lang.Object;#25026824, [Ljava.lang.Object;#170b75f9]
what is Ljava.lang.Object;#25026824 ? is return object, can i handle it to convert from list to json ?
i have model TransactionQR.java :
public class TransactionQR implements Serializable {
private Long id;
private String codeqr;
private Date approvaltime;
private String merchant;
private String code_merchant;
private Long amount;
private Long saldoawal;
private Integer tracenumber;
private String state;
private Date createdate;
private Batch batch;
public TransactionQR() {
}
public TransactionQR(Long id, String codeqr, Date approvaltime, String merchant, String code_merchant, Long amount,
Long saldoawal, Integer tracenumber, String state, Date createdate, Batch batch) {
super();
this.id = id;
this.codeqr = codeqr;
this.approvaltime = approvaltime;
this.merchant = merchant;
this.code_merchant = code_merchant;
this.amount = amount;
this.saldoawal = saldoawal;
this.tracenumber = tracenumber;
this.state = state;
this.createdate = createdate;
this.batch = batch;
}
public Long getId() {
return id;
}
public Date getApprovalTime() {
return approvaltime;
}
public Batch getBatch() {
return batch;
}
public void setBatch(Batch batch) {
this.batch = batch;
}
public void setApprovalTime(Date approvalTime) {
this.approvaltime = approvalTime;
}
public void setId(Long id) {
this.id = id;
}
public Date getApprovaltime() {
return approvaltime;
}
public void setApprovaltime(Date approvaltime) {
this.approvaltime = approvaltime;
}
public String getCodeqr() {
return codeqr;
}
public void setCodeqr(String codeqr) {
this.codeqr = codeqr;
}
public String getMerchant() {
return merchant;
}
public void setMerchant(String merchant) {
this.merchant = merchant;
}
public String getCode_merchant() {
return code_merchant;
}
public void setCode_merchant(String code_merchant) {
this.code_merchant = code_merchant;
}
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public Long getSaldoawal() {
return saldoawal;
}
public void setSaldoawal(Long saldoawal) {
this.saldoawal = saldoawal;
}
public Integer getTracenumber() {
return tracenumber;
}
public void setTracenumber(Integer tracenumber) {
this.tracenumber = tracenumber;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getCreatedate() {
return createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
}
the result is i want to show all data from database in list
In second case, since you are selecting two attributes, that is why session.createQuery("").list returns a list of object array(List<Object[]>) . At each index of list you will find an object array. Each array will have two indexes. First index will provide id while the second one would provide codeqr. So, basically you need to iterate over the list. Then fetch each value individually like arr[0], arr[1]..

How do I map Retrofit response to Data Model Class?

Here is my Retrofit Call...
public void getContests() {
String token = LoginActivity.authToken;
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(OctoInterface.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
OctoInterface api = retrofit.create(OctoInterface.class);
Call<List<OctoModel2>> call = api.getOctoContests(token);
call.enqueue(new Callback<List<OctoModel2>>() {
#Override
public void onResponse(Call<List<OctoModel2>> call, Response<List<OctoModel2>> response) {
int statusCode = response.code();
int i = 0;
if (response.body().size() > titleList.size()) {
for (i = 0; i <= response.body().size() -1; i++) {
contestIdList.add(String.valueOf(response.body().get(i).getId()));
titleList.add(response.body().get(i).getTitle());
subtitleList.add(response.body().get(i).getDescShort());
offerIdList.add(String.valueOf(response.body().get(i).getId()));
offerLogoList.add(response.body().get(i).getLogoUrl());
businessId = String.valueOf(response.body().get(i).getBusinessId());
submit_button_text = response.body().get(i).getSubmitButtonText();
}
}
}
#Override
public void onFailure(Call<List<OctoModel2>> call, Throwable t) {
Log.e("Get Contest failure", call.toString());
t.printStackTrace();
}
});
}
As you can see, I'm currently grabbing the pieces of the response that I need and passing them to individual array lists. I'd much rather pass the entire return into a list of model objects that hold the data.
Here is my POJO class for retrofit...
public class OctoModel2 {
#SerializedName("how_it_works")
#Expose
private List<String> howItWorks = null;
#SerializedName("id")
#Expose
private int id;
#SerializedName("business_id")
#Expose
private int businessId;
#SerializedName("title")
#Expose
private String title;
#SerializedName("desc_short")
#Expose
private String descShort;
#SerializedName("logo_url")
#Expose
private String logoUrl;
#SerializedName("hashtag")
#Expose
private String hashtag;
#SerializedName("confirm_message_title")
#Expose
private String confirmMessageTitle;
#SerializedName("rules")
#Expose
private String rules;
#SerializedName("confirm_message")
#Expose
private String confirmMessage;
#SerializedName("start_date")
#Expose
private String startDate;
#SerializedName("end_date")
#Expose
private String endDate;
#SerializedName("active")
#Expose
private boolean active;
#SerializedName("entry_count")
#Expose
private int entryCount;
#SerializedName("age_required")
#Expose
private int ageRequired;
#SerializedName("submit_button_text")
#Expose
private String submitButtonText;
#SerializedName("hide_redeem_code")
#Expose
private boolean hideRedeemCode;
#SerializedName("redeem_button_text")
#Expose
private String redeemButtonText;
#SerializedName("rules_text")
#Expose
private String rulesText;
#SerializedName("mode")
#Expose
private String mode;
#SerializedName("entry_mode")
#Expose
private String entryMode;
#SerializedName("created_at")
#Expose
private String createdAt;
#SerializedName("updated_at")
#Expose
private String updatedAt;
#SerializedName("deleted_at")
#Expose
private Object deletedAt;
#SerializedName("locations")
#Expose
private List<Location> locations = null;
#SerializedName("entries")
#Expose
private List<Entry> entries = null;
#SerializedName("entry")
#Expose
private Entry entry;
#SerializedName("AWSAccessKeyId")
#Expose
private String aWSAccessKeyId;
#SerializedName("key")
#Expose
private String key;
#SerializedName("policy")
#Expose
private String policy;
#SerializedName("signature")
#Expose
private String signature;
#SerializedName("uuid")
#Expose
private String uuid;
#SerializedName("reward")
#Expose
private Reward reward;
#SerializedName("s3_url")
#Expose
private String s3_url;
public OctoModel2(Integer id, Integer businessId, String title, String descShort, String logoUrl, String hashtag, String confirmMessageTitle, String rules, String confirmMessage, String startDate, String endDate, Boolean active,
String submitButtonText, String redeemButtonText, String rulesText, List<Location> locations, String aWSAccessKeyId, String key, String policy, String signature, String uuid) {
this.id = id;
this.businessId = businessId;
this.title = title;
this.descShort = descShort;
this.logoUrl = logoUrl;
this.hashtag = hashtag;
this.confirmMessageTitle = confirmMessageTitle;
this.rules = rules;
this.confirmMessage = confirmMessage;
this.startDate = startDate;
this.endDate = endDate;
this.active = active;
this.submitButtonText = submitButtonText;
this.redeemButtonText = redeemButtonText;
this.rulesText = rulesText;
this.locations = locations;
this.aWSAccessKeyId = aWSAccessKeyId;
this.key = key;
this.policy = policy;
this.signature = signature;
this.uuid = uuid;
}
public List<String> getHowItWorks() {
return howItWorks;
}
public void setHowItWorks(List<String> howItWorks) {
this.howItWorks = howItWorks;
}
public int getId() {
return id;
}
public List<OctoModel2> getResults() {
return results;
}
public void setId(int id) {
this.id = id;
}
public int getBusinessId() {
return businessId;
}
public void setBusinessId(int businessId) {
this.businessId = businessId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescShort() {
return descShort;
}
public void setDescShort(String descShort) {
this.descShort = descShort;
}
public String getLogoUrl() {
return logoUrl;
}
public void setLogoUrl(String logoUrl) {
this.logoUrl = logoUrl;
}
public String getHashtag() {
return hashtag;
}
public void setHashtag(String hashtag) {
this.hashtag = hashtag;
}
public String getConfirmMessageTitle() {
return confirmMessageTitle;
}
public void setConfirmMessageTitle(String confirmMessageTitle) {
this.confirmMessageTitle = confirmMessageTitle;
}
public String getRules() {
return rules;
}
public void setRules(String rules) {
this.rules = rules;
}
public String getConfirmMessage() {
return confirmMessage;
}
public void setConfirmMessage(String confirmMessage) {
this.confirmMessage = confirmMessage;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public int getEntryCount() {
return entryCount;
}
public void setEntryCount(int entryCount) {
this.entryCount = entryCount;
}
public int getAgeRequired() {
return ageRequired;
}
public void setAgeRequired(int ageRequired) {
this.ageRequired = ageRequired;
}
public String getSubmitButtonText() {
return submitButtonText;
}
public void setSubmitButtonText(String submitButtonText) {
this.submitButtonText = submitButtonText;
}
public boolean isHideRedeemCode() {
return hideRedeemCode;
}
public void setHideRedeemCode(boolean hideRedeemCode) {
this.hideRedeemCode = hideRedeemCode;
}
public String getRedeemButtonText() {
return redeemButtonText;
}
public void setRedeemButtonText(String redeemButtonText) {
this.redeemButtonText = redeemButtonText;
}
public String getRulesText() {
return rulesText;
}
public void setRulesText(String rulesText) {
this.rulesText = rulesText;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public String getEntryMode() {
return entryMode;
}
public void setEntryMode(String entryMode) {
this.entryMode = entryMode;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public Object getDeletedAt() {
return deletedAt;
}
public void setDeletedAt(Object deletedAt) {
this.deletedAt = deletedAt;
}
public List<Location> getLocations() {
return locations;
}
public void setLocations(List<Location> locations) {
this.locations = locations;
}
public List<Entry> getEntries() {
return entries;
}
public void setEntries(List<Entry> entries) {
this.entries = entries;
}
public Entry getEntry() {
return entry;
}
public String getAWSAccessKeyId() {
return aWSAccessKeyId;
}
public void setAWSAccessKeyId(String aWSAccessKeyId) {
this.aWSAccessKeyId = aWSAccessKeyId;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getPolicy() {
return policy;
}
public void setPolicy(String policy) {
this.policy = policy;
}
public String getSignature() {
return signature;
}
public String gets3url() {
return s3_url;
}
public void setSignature(String signature) {
this.signature = signature;
}
public Reward getReward() {
return reward;
}
public void setReward(Reward reward) {
this.reward = reward;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}
Instead of calling the data from each list like
TitleList.get(position);
SubtitleList.get(position);
LogoUrlList.get(position);
etc...
I'd like to be able to call
Contests.get(position).getTitle();
Contests.get(position).getSubtitle();
Contests.get(position).getLogoUrl();
or however it would be. This would make it better for me to sort the responses and get the data from individual responses without hoping and praying that I'm pulling the correct item from the correct ArrayList.
You need a mapper that maps your DTO (Data Transfer Object) into an entity or list of entities. For example:
public interface Mapper<From, To> {
To map(From value);
}
Now you can create a class, e.g. called `MyRetrofitResponseMapper, that implements the interface and maps the fields needed.
Moreover, you can create multiple mappers that map the same DTO into different entities depending on what DTO fields are required for those.
An example can be found here.

null values returning from gson.fromJson

I have some values in my object are returning by value null when converting from json to object and some others doesn't,i can't figure out why is that happening
here's my code to convert
OriginalMovie originalMovie = gson.fromJson(jsonString, OriginalMovie.class);
here's my json
{"page":1,
"results":[{"adult":false,
"backdrop_path":"/o4I5sHdjzs29hBWzHtS2MKD3JsM.jpg",
"genre_ids":[878,28,53,12],
"id":87101,"original_language":"en",
"original_title":"Terminator Genisys",
"overview":"The year is 2029. John Connor, leader of the resistance continues the war against the machines.",
"release_date":"2015-07-01",
"poster_path":"/5JU9ytZJyR3zmClGmVm9q4Geqbd.jpg",
"popularity":54.970301,
"title":"Terminator Genisys","video":false,
"vote_average":6.4,
"vote_count":197}],
"total_pages":11666,"total_results":233312}
and here's my base class (contains results)
package MovieReviewHelper;
import java.util.ArrayList;
import java.util.List;
public class OriginalMovie
{
private long page;
private List<Result> results = new ArrayList<Result>();
private long totalPages;
private long totalResults;
public long getPage()
{
return page;
}
public void setPage(long page)
{
this.page = page;
}
public List<Result> getResults()
{
return results;
}
public void setResults(List<Result> results)
{
this.results = results;
}
public long getTotalPages() {
return totalPages;
}
public void setTotalPages(long totalPages)
{
this.totalPages = totalPages;
}
public long getTotalResults()
{
return totalResults;
}
public void setTotalResults(long totalResults)
{
this.totalResults = totalResults;
}
}
and here's my other class
package MovieReviewHelper;
import java.util.ArrayList;
import java.util.List;
public class Result {
private boolean adult;
private String backdropPath;
private List<Long> genreIds = new ArrayList<Long>();
private long id;
private String originalLanguage;
private String originalTitle;
private String overview;
private String releaseDate;
private String posterPath;
private double popularity;
private String title;
private boolean video;
private double voteAverage;
private long voteCount;
public boolean isAdult()
{
return adult;
}
public void setAdult(boolean adult)
{
this.adult = adult;
}
public String getBackdropPath()
{
return backdropPath;
}
public void setBackdropPath(String backdropPath)
{
this.backdropPath = backdropPath;
}
public List<Long> getGenreIds()
{
return genreIds;
}
public void setGenreIds(List<Long> genreIds)
{
this.genreIds = genreIds;
}
public long getId()
{
return id;
}
public void setId(long id)
{
this.id = id;
}
public String getOriginalLanguage()
{
return originalLanguage;
}
public void setOriginalLanguage(String originalLanguage)
{
this.originalLanguage = originalLanguage;
}
public String getOriginalTitle()
{
return originalTitle;
}
public void setOriginalTitle(String originalTitle)
{
this.originalTitle = originalTitle;
}
public String getOverview()
{
return overview;
}
public void setOverview(String overview)
{
this.overview = overview;
}
public String getReleaseDate()
{
return releaseDate;
}
public void setReleaseDate(String releaseDate)
{
this.releaseDate = releaseDate;
}
public String getPosterPath()
{
return posterPath;
}
public void setPosterPath(String posterPath)
{
this.posterPath = posterPath;
}
public double getPopularity()
{
return popularity;
}
public void setPopularity(double popularity)
{
this.popularity = popularity;
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public boolean isVideo()
{
return video;
}
public void setVideo(boolean video)
{
this.video = video;
}
public double getVoteAverage()
{
return voteAverage;
}
public void setVoteAverage(double voteAverage)
{
this.voteAverage = voteAverage;
}
public long getVoteCount()
{
return voteCount;
}
public void setVoteCount(long voteCount)
{
this.voteCount = voteCount;
}
}
Your Json and Class variables should have the same name.
backdrop_path in Json and backdropPath in class would not work
Incase this helps for someone like me who spent half a day in trying to figure out a similar issue with gson.fromJson() returning object with null values, but when using #JsonProperty with an underscore in name and using Lombok in the model class.
My model class had a property like below and am using Lombok #Data for class
#JsonProperty(value="dsv_id")
private String dsvId;
So in my Json file I was using
"dsv_id"="123456"
Which was causing null value. The way I resolved it was changing the Json to have below ie.without the underscore. That fixed the problem for me.
"dsvId = "123456"

Hibernate JPA searching two joined tables

I am pretty new to Hibernate and JPA implementation in Spring, so basically have set up a MySQL 5 database which maps to the domain objects below.
I am trying to search for Location on the Company_Details table but I can't figure out how to search the class Product_Details for Product_Name at the same time
If anyone could help that would be great.
Company_Details
#Entity
public class Company_Details implements Serializable{
/**
*
*/
private static final long serialVersionUID = 3336251433829975771L;
#Id
#GeneratedValue
private Integer Id;
private String Company;
private String Address_Line_1;
private String Address_Line_2;
private String Postcode;
private String County;
private String Country;
private String Mobile_Number;
private String Telephone_Number;
private String URL;
private String Contact;
private String Logo_URL;
private double Amount_Overall;
private double Amount_Paid;
private Timestamp Date_Joined;
private int Account_Details;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "Company_Id")
private List<Product_Details> products;
public Integer getId() {
return Id;
}
public void setId(Integer id) {
Id = id;
}
public String getCompany() {
return Company;
}
public void setCompany(String company) {
Company = company;
}
public String getAddress_Line_1() {
return Address_Line_1;
}
public void setAddress_Line_1(String address_Line_1) {
Address_Line_1 = address_Line_1;
}
public String getAddress_Line_2() {
return Address_Line_2;
}
public void setAddress_Line_2(String address_Line_2) {
Address_Line_2 = address_Line_2;
}
public String getPostcode() {
return Postcode;
}
public void setPostcode(String postcode) {
Postcode = postcode;
}
public String getCounty() {
return County;
}
public void setCounty(String county) {
County = county;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
public String getMobile_Number() {
return Mobile_Number;
}
public void setMobile_Number(String mobile_Number) {
Mobile_Number = mobile_Number;
}
public String getTelephone_Number() {
return Telephone_Number;
}
public void setTelephone_Number(String telephone_Number) {
Telephone_Number = telephone_Number;
}
public String getURL() {
return URL;
}
public void setURL(String uRL) {
URL = uRL;
}
public String getContact() {
return Contact;
}
public void setContact(String contact) {
Contact = contact;
}
public String getLogo_URL() {
return Logo_URL;
}
public void setLogo_URL(String logo_URL) {
Logo_URL = logo_URL;
}
public double getAmount_Overall() {
return Amount_Overall;
}
public void setAmount_Overall(double amount_Overall) {
Amount_Overall = amount_Overall;
}
public double getAmount_Paid() {
return Amount_Paid;
}
public void setAmount_Paid(double amount_Paid) {
Amount_Paid = amount_Paid;
}
public Timestamp getDate_Joined() {
return Date_Joined;
}
public void setDate_Joined(Timestamp date_Joined) {
Date_Joined = date_Joined;
}
public int getAccount_Details() {
return Account_Details;
}
public void setAccount_Details(int account_Details) {
Account_Details = account_Details;
}
public List<Product_Details> getProducts() {
return products;
}
public void setProducts(List<Product_Details> products) {
this.products = products;
}
Product_Details
#Entity
public class Product_Details implements Serializable{
/**
*
*/
private static final long serialVersionUID = 6477618197240654478L;
#Id
#GeneratedValue
private Integer Id;
private Integer Company_Id;
private String Product_Name;
private String Description;
private String Main_Photo_URL;
private String Other_Photo_URLS;
private Integer Total_Bookings;
private double Average_Rating;
private Integer Number_Of_Slots;
private Integer Time_Per_Slot;
private double Price_Per_Slot;
private String Monday_Open;
private String Tuesday_Open;
private String Wednesday_Open;
private String Thursday_Open;
private String Friday_Open;
private String Saturday_Open;
private String Sunday_Open;
private String Dates_Closed;
public Integer getId() {
return Id;
}
public void setId(Integer id) {
Id = id;
}
public Integer getCompany_Id() {
return Company_Id;
}
public void setCompany_Id(Integer company_Id) {
Company_Id = company_Id;
}
public String getProduct_Name() {
return Product_Name;
}
public void setProduct_Name(String product_Name) {
Product_Name = product_Name;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getMain_Photo_URL() {
return Main_Photo_URL;
}
public void setMain_Photo_URL(String main_Photo_URL) {
Main_Photo_URL = main_Photo_URL;
}
public String getOther_Photos_URLS() {
return Other_Photo_URLS;
}
public void setOther_Photos_URLS(String other_Photo_URLS) {
Other_Photo_URLS = other_Photo_URLS;
}
public Integer getTotal_Bookings() {
return Total_Bookings;
}
public void setTotal_Bookings(Integer total_Bookings) {
Total_Bookings = total_Bookings;
}
public double getAverage_Rating() {
return Average_Rating;
}
public void setAverage_Rating(double average_Rating) {
Average_Rating = average_Rating;
}
public Integer getNumber_Of_Slots() {
return Number_Of_Slots;
}
public void setNumber_Of_Slots(Integer number_Of_Slots) {
Number_Of_Slots = number_Of_Slots;
}
public Integer getTime_Per_Slot() {
return Time_Per_Slot;
}
public void setTime_Per_Slot(Integer time_Per_Slot) {
Time_Per_Slot = time_Per_Slot;
}
public double getPrice_Per_Slot() {
return Price_Per_Slot;
}
public void setPrice_Per_Slot(double price_Per_Slot) {
Price_Per_Slot = price_Per_Slot;
}
public String getMonday_Open() {
return Monday_Open;
}
public void setMonday_Open(String monday_Open) {
Monday_Open = monday_Open;
}
public String getTuesday_Open() {
return Tuesday_Open;
}
public void setTuesday_Open(String tuesday_Open) {
Tuesday_Open = tuesday_Open;
}
public String getWednesday_Open() {
return Wednesday_Open;
}
public void setWednesday_Open(String wednesday_Open) {
Wednesday_Open = wednesday_Open;
}
public String getThursday_Open() {
return Thursday_Open;
}
public void setThursday_Open(String thursday_Open) {
Thursday_Open = thursday_Open;
}
public String getFriday_Open() {
return Friday_Open;
}
public void setFriday_Open(String friday_Open) {
Friday_Open = friday_Open;
}
public String getSaturday_Open() {
return Saturday_Open;
}
public void setSaturday_Open(String saturday_Open) {
Saturday_Open = saturday_Open;
}
public String getSunday_Open() {
return Sunday_Open;
}
public void setSunday_Open(String sunday_Open) {
Sunday_Open = sunday_Open;
}
public String getDates_Closed() {
return Dates_Closed;
}
public void setDates_Closed(String dates_Closed) {
Dates_Closed = dates_Closed;
}
}
#Service
public class ProductServiceImpl implements ProductService{
private final static Logger LOG = Logger.getLogger(ProductServiceImpl.class.getName());
#PersistenceContext
EntityManager em;
#Transactional
public List<Company_Details> search(Search search) {
LOG.info("Entering search method");
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Company_Details> c = builder.createQuery(Company_Details.class);
Root<Company_Details> companyRoot = c.from(Company_Details.class);
c.select(companyRoot);
c.where(builder.equal(companyRoot.get("County"),search.getLocation()));
return em.createQuery(c).getResultList();
}
}
You need two criteria: criteria on the Company_Details class
And criteria on the Product_Details class
Then
Criteria crit1 = session.createCriteria(Company_Details.class);
crit1.add(restriction)
Criteria crit2 = crit1.createCriteria("products");
crit2.add(restriction)
// Then query crit1
List results = crit1.list();

Categories

Resources