I am at present working on a android chat application like whatsapp but I stuck at a situation in where Realm Migration is issue. I am not knowing so much about realm but testing it for a successful offline chat application. I am not able to use more than one model in realm because it is saying about the migrator. I tried all the ways but my migrator is not working and I also not having idea that what statements I have to use after this (schema.) statement for migrate my model according to my situations.
Here is the Code for my Realm ChatList Model:-
public class RealmChatListModel extends RealmObject {
#Index
private String userID;
private String Username;
private String Descryption;
private String phoneNo;
private String lastMessage;
private String Date;
private String ImageURI;
private long lastMessageTime;
public RealmChatListModel() {
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getUsername() {
return Username;
}
public void setUsername(String username) {
Username = username;
}
public String getDescryption() {
return Descryption;
}
public void setDescryption(String descryption) {
Descryption = descryption;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getLastMessage() {
return lastMessage;
}
public void setLastMessage(String lastMessage) {
this.lastMessage = lastMessage;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
public String getImageURI() {
return ImageURI;
}
public void setImageURI(String imageURI) {
ImageURI = imageURI;
}
public long getLastMessageTime() {
return lastMessageTime;
}
public void setLastMessageTime(long lastMessageTime) {
this.lastMessageTime = lastMessageTime;
}
}
And here is my code for realm Chat Model :-
public class RealmChat extends RealmObject {
#PrimaryKey
#Index
private String messageKey;
private String time;
private String date;
private String textMessage;
private String type;
private String sender;
private String receiver;
private String uri;
private boolean isSeen;
private String duration;
private String receivername;
private String fileSize;
private boolean isNextDay;
private boolean isDeleted;
private Date extactdate;
private String repMesKey;
private String repMesUri;
private String repMesText;
private String repMesType;
private String repMesSender;
private long timestamp;
private String repMesSendPhone;
private boolean isReplied;
private String phoneNo;
private boolean isForwarded;
public String getMessageKey() {
return messageKey;
}
public void setMessageKey(String messageKey) {
this.messageKey = messageKey;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTextMessage() {
return textMessage;
}
public void setTextMessage(String textMessage) {
this.textMessage = textMessage;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public boolean isSeen() {
return isSeen;
}
public void setSeen(boolean seen) {
isSeen = seen;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getReceivername() {
return receivername;
}
public void setReceivername(String receivername) {
this.receivername = receivername;
}
public String getFileSize() {
return fileSize;
}
public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}
public boolean isNextDay() {
return isNextDay;
}
public void setNextDay(boolean nextDay) {
isNextDay = nextDay;
}
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean deleted) {
isDeleted = deleted;
}
public Date getExtactdate() {
return extactdate;
}
public void setExtactdate(Date extactdate) {
this.extactdate = extactdate;
}
public String getRepMesKey() {
return repMesKey;
}
public void setRepMesKey(String repMesKey) {
this.repMesKey = repMesKey;
}
public String getRepMesUri() {
return repMesUri;
}
public void setRepMesUri(String repMesUri) {
this.repMesUri = repMesUri;
}
public String getRepMesText() {
return repMesText;
}
public void setRepMesText(String repMesText) {
this.repMesText = repMesText;
}
public String getRepMesType() {
return repMesType;
}
public void setRepMesType(String repMesType) {
this.repMesType = repMesType;
}
public String getRepMesSender() {
return repMesSender;
}
public void setRepMesSender(String repMesSender) {
this.repMesSender = repMesSender;
}
public String getRepMesSendPhone() {
return repMesSendPhone;
}
public void setRepMesSendPhone(String repMesSendPhone) {
this.repMesSendPhone = repMesSendPhone;
}
public boolean isReplied() {
return isReplied;
}
public void setReplied(boolean replied) {
isReplied = replied;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public boolean isForwarded() {
return isForwarded;
}
public void setForwarded(boolean forwarded) {
isForwarded = forwarded;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
And Here is my code for my migrator :-
public class RealmMigration implements io.realm.RealmMigration {
#Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
RealmSchema schema = realm.getSchema();
// Migrate from version 0 to version 1
if (oldVersion == 0) {
schema.get("RealmChatListModel")
.addField("Username", String.class)
.addRealmListField("lastMessageTime", long.class);
oldVersion++;
}
if (oldVersion == 1) {
schema.get("RealmChat")
.addField("extactdate", Date.class)
.addRealmListField("timestamp",long.class);
}
}
public static RealmConfiguration getDefaultConfig() {
return new RealmConfiguration.Builder()
.schemaVersion(2)
.migration(new RealmMigration())
.build();
}
#Override
public int hashCode() { return RealmMigration.class.hashCode(); }
#Override
public boolean equals(Object object) { return object != null && object instanceof RealmMigration; }
}
Please Help me...................................................................................
<<<<<<<<<<<<<<<<------------------(~~~~~~~~~~~~~~~~~~~)------------------->>>>>>>>>>>>>>>>>>>>>
Yes I got it my migration is working only by a single change :-
#Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
RealmSchema schema = realm.getSchema();
// Migrate from version 0 to version 1
if (oldVersion == 0) {
schema.get("RealmChatListModel")
.addField("userID", String.class, FieldAttribute.REQUIRED);
oldVersion++;
}
}
Here I removed Realm Chat from migrating the old version because it is the last model and added in realmChatListSchema that userID field is required.Noting else reqired. I am happy 🥰 🥰 🥰 .
Related
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
I am developing app now I want to convert Date to String in realm but I have tried but I can't achieve what I want
below SaveMessage model class
#RealmClass
public class SaveMessage extends RealmObject {
private int mId;
private String mUsername;
private String mContent;
private Date mCreatedAt;
private boolean mRightMessage;
private String mPictureString;
private String mType;
public SaveMessage(int id, String username, String content, Date createdAt, boolean isRightMessage) {
mId = id;
mUsername = username;
mContent = content;
mCreatedAt = createdAt;
mRightMessage = isRightMessage;
}
public SaveMessage() {
}
public int getId() {
return mId;
}
public String getUsername() {
return mUsername;
}
public String getContent() {
return mContent;
}
public Date getDate() {
return mCreatedAt;
}
public void setDate(Date createdAt) {
mCreatedAt = createdAt;
}
below my Date conversion
SimpleDateFormat input = new
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); SimpleDateFormat
output = new SimpleDateFormat("dd/MM/yyyy");
Date d = new Date();
try {
d = input.parse(output);
} catch (ParseException e) {
e.printStackTrace();
}
public boolean ismRightMessage() {
return mRightMessage;
}
public int getmId() {
return mId;
}
public void setmId(int mId) {
this.mId = mId;
}
public String getmUsername() {
return mUsername;
}
public void setmUsername(String mUsername) {
this.mUsername = mUsername;
}
public String getmContent() {
return mContent;
}
public void setmContent(String mContent) {
this.mContent = mContent;
}
public boolean ismRightMessage(String isRightMessage) {
return mRightMessage;
}
public void setmRightMessage(boolean mRightMessage) {
this.mRightMessage = mRightMessage;
}
public String getPictureString() {
return mPictureString;
}
public void setPictureString(String pictureString) {
mPictureString = pictureString;
}
public String getType() {
return mType;
}
public void setType(String type) {
mType = type;
}
}
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"
How to pass array of string in insert query statement in ibatis. On passing string array as parameter it is giving me this exception of ibatis -
Can't infer the SQL type to use for an instance of [Ljava.lang.String;. Use setObject() with an explicit Types value to specify the type to use.
How to solve this error ?
My method is -
public void insertCampaignData(String campaignData, ObjectMapper jsonObjMapper) {
Campaign campaign = null;
SqlSession session = null;
IfrmCreateCampaign createCampaign = null;
try {
campaign = jsonObjMapper.readValue(campaignData,Campaign.class);
session = DBConnectionFactory.getNewSession();
createCampaign = session.getMapper(IfrmCreateCampaign.class);
createCampaign.insertCampaignData(campaign);
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
My entity class is -
import java.io.File;
import java.util.Date;
public class Campaign {
private long campaignId;
private String campaignName;
private long keywordId;
private String brandName;
private String clientName;
private String mobileNum;
private Date startTime;
private Date endTime;
private double campaignBudget;
private double allocatedFund;
private double campaignRate;
private boolean basicTgt;
private boolean customTgt;
private boolean advTgt;
private boolean chechme;
private boolean couponSend;
private String couponFrom;
private String couponTo;
private String couponFilePath;
private File[] couponFile;
private String[] couponFileFileName;
private String[] couponFileContent;
private String callbackUrl;
private String status;
private int campaignTypeId;
private long roAmount;
// edit
private int roType;
public int getRoType() {
return roType;
}
public void setRoType(int roType) {
this.roType = roType;
}
// edit
private String strStartTime;
private String strEndTime;
private String keyword;
private String keywordNum;
private int goal;
private double spentAmount;
private int goalAchievePercent;
private int dial;
private int uniqueDial;
private long userId;
private double campaignTotalAmount;
private double operatorShare;
private long responseCount;
private String strRoPdfFileName;
private File[] roPdf;
private String[] roPdfFileName;
private String[] roPdfContent;
public long getCampaignId() {
return campaignId;
}
public void setCampaignId(long campaignId) {
this.campaignId = campaignId;
}
public String getCampaignName() {
return campaignName;
}
public void setCampaignName(String campaignName) {
this.campaignName = campaignName;
}
public long getKeywordId() {
return keywordId;
}
public void setKeywordId(long keywordId) {
this.keywordId = keywordId;
}
public String getKeywordNum() {
return keywordNum;
}
public void setKeywordNum(String keywordNum) {
this.keywordNum = keywordNum;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getMobileNum() {
return mobileNum;
}
public void setMobileNum(String mobileNum) {
this.mobileNum = mobileNum;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public double getCampaignBudget() {
return campaignBudget;
}
public void setCampaignBudget(double campaignBudget) {
this.campaignBudget = campaignBudget;
}
public double getAllocatedFund() {
return allocatedFund;
}
public void setAllocatedFund(double allocatedFund) {
this.allocatedFund = allocatedFund;
}
public double getCampaignRate() {
return campaignRate;
}
public void setCampaignRate(double campaignRate) {
this.campaignRate = campaignRate;
}
public boolean isBasicTgt() {
return basicTgt;
}
public void setBasicTgt(boolean basicTgt) {
this.basicTgt = basicTgt;
}
public boolean isCustomTgt() {
return customTgt;
}
public void setCustomTgt(boolean customTgt) {
this.customTgt = customTgt;
}
public boolean isAdvTgt() {
return advTgt;
}
public void setAdvTgt(boolean advTgt) {
this.advTgt = advTgt;
}
public boolean isChechme() {
return chechme;
}
public void setChechme(boolean chechme) {
this.chechme = chechme;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getStrStartTime() {
return strStartTime;
}
public void setStrStartTime(String strStartTime) {
this.strStartTime = strStartTime;
}
public String getStrEndTime() {
return strEndTime;
}
public void setStrEndTime(String strEndTime) {
this.strEndTime = strEndTime;
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public int getGoal() {
return goal;
}
public void setGoal(int goal) {
this.goal = goal;
}
public double getSpentAmount() {
return spentAmount;
}
public void setSpentAmount(double spentAmount) {
this.spentAmount = spentAmount;
}
public int getGoalAchievePercent() {
return goalAchievePercent;
}
public void setGoalAchievePercent(int goalAchievePercent) {
this.goalAchievePercent = goalAchievePercent;
}
public int getDial() {
return dial;
}
public void setDial(int dial) {
this.dial = dial;
}
public int getUniqueDial() {
return uniqueDial;
}
public void setUniqueDial(int uniqueDial) {
this.uniqueDial = uniqueDial;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public boolean isCouponSend() {
return couponSend;
}
public void setCouponSend(boolean couponSend) {
this.couponSend = couponSend;
}
public String getCouponFrom() {
return couponFrom;
}
public void setCouponFrom(String couponFrom) {
this.couponFrom = couponFrom;
}
public String getCouponTo() {
return couponTo;
}
public void setCouponTo(String couponTo) {
this.couponTo = couponTo;
}
public String getCouponFilePath() {
return couponFilePath;
}
public void setCouponFilePath(String couponFilePath) {
this.couponFilePath = couponFilePath;
}
public File[] getCouponFile() {
return couponFile;
}
public void setCouponFile(File[] couponFile) {
this.couponFile = couponFile;
}
public String[] getCouponFileFileName() {
return couponFileFileName;
}
public void setCouponFileFileName(String[] couponFileFileName) {
this.couponFileFileName = couponFileFileName;
}
public String[] getCouponFileContent() {
return couponFileContent;
}
public void setCouponFileContent(String[] couponFileContent) {
this.couponFileContent = couponFileContent;
}
public String getCallbackUrl() {
return callbackUrl;
}
public void setCallbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl;
}
public int getCampaignTypeId() {
return campaignTypeId;
}
public void setCampaignTypeId(int campaignTypeId) {
this.campaignTypeId = campaignTypeId;
}
public long getRoAmount() {
return roAmount;
}
public void setRoAmount(long roAmount) {
this.roAmount = roAmount;
}
public double getOperatorShare() {
return operatorShare;
}
public void setOperatorShare(double operatorShare) {
this.operatorShare = operatorShare;
}
public long getResponseCount() {
return responseCount;
}
public void setResponseCount(long responseCount) {
this.responseCount = responseCount;
}
public double getCampaignTotalAmount() {
return campaignTotalAmount;
}
public void setCampaignTotalAmount(double campaignTotalAmount) {
this.campaignTotalAmount = campaignTotalAmount;
}
public String getStrRoPdfFileName() {
return strRoPdfFileName;
}
public void setStrRoPdfFileName(String strRoPdfFileName) {
this.strRoPdfFileName = strRoPdfFileName;
}
public File[] getRoPdf() {
return roPdf;
}
public void setRoPdf(File[] roPdf) {
this.roPdf = roPdf;
}
public String[] getRoPdfFileName() {
return roPdfFileName;
}
public void setRoPdfFileName(String[] roPdfFileName) {
this.roPdfFileName = roPdfFileName;
}
public String[] getRoPdfContent() {
return roPdfContent;
}
public void setRoPdfContent(String[] roPdfContent) {
this.roPdfContent = roPdfContent;
}
}
My xml mapping file is -
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mogae.starStarWebServices.db.dao.IfrmCreateCampaign">
<insert id="insertCampaignData" statementType="PREPARED" >
insert into campaign(campaign_id,campaign_name,keyword_id,brand_name,client_name,mobile_num,start_time,end_time,campaign_type_id,ro_amount,ro_type,ro_pdf_file_name,campaign_budget,allocated_fund,campaign_rate,is_basic_tgt,is_custom_tgt,is_adv_tgt,is_checkme,is_coupon_send,coupon_from,coupon_to,coupon_file,callback_url,status) values (#{campaignId},#{campaignName},#{keywordId},#{brandName},#{clientName},#{mobileNum},#{startTime},#{endTime},#{campaignTypeId},#{roAmount},#{roType},
#{strRoPdfFileName},#{campaignBudget},#{allocatedFund},#{campaignRate},#{basicTgt},#{customTgt},#{advTgt},#{chechme},#{couponSend},#{couponFrom},#{couponTo},#{couponFileFileName},#{callbackUrl},#{status});
</insert>
<insert id="insertKeywordData" statementType="PREPARED" >
insert into keywords(keyword_id,keyword,keyword_num,booked_by,purchased_on,expires_on,status) values (#{keywordId},#{keyword},#{keywordNum},#{bookedBy},#{purchasedOn},#{expiresOn},#{status})
</insert>
</mapper>
I am trying to copy properties from one bean to another. Here are the signature of two beans:
SearchContent:
public class SearchContent implements Serializable {
private static final long serialVersionUID = -4500094586165758427L;
private Integer id;
private String docName;
private String docType;
private String docTitle;
private String docAuthor;
private String securityGroup;
private String docAccount;
private Integer revLabel;
private String profile;
private LabelValueBean<String> workflowStage;
private Date createDate;
private Date inDate;
private String originalName;
private String format;
private String extension;
private Long fileSize;
private String author;
private LabelValueBean<String> entity;
private LabelValueBean<String> brand;
private LabelValueBean<String> product;
private LabelValueBean<String> collection;
private LabelValueBean<String> subCollection;
private String description;
private LabelValueBean<String> program;
private String vintage;
private String model;
private String restrictedZone;
private LabelValueBean<String> event;
private LabelValueBean<String> language;
private String geographicLocation;
private String watermark;
private Integer pageNumber;
private String summary;
private String agentName;
private String commissionedByName;
private String commissionedByDepartment;
private LabelValueBean<Integer> bestOf;
private String mediaLocation;
private LabelValueBean<Integer> fullRights;
private LabelValueBean<String> mediaUsage;
private Date rightsEndDate;
private String geographicRights;
private LabelValueBean<Integer> evinConformity;
private String contactReference;
private LabelValueBean<String> publicationScope;
private String rightsComment;
/**
* Constructor SearchContent
* #author TapasB
* #since 15-Oct-2013 - 5:45:55 pm
* #version DAM 1.0
*/
public SearchContent() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDocName() {
return docName;
}
public void setDocName(String docName) {
this.docName = docName;
}
public String getDocType() {
return docType;
}
public void setDocType(String docType) {
this.docType = docType;
}
public String getDocTitle() {
return docTitle;
}
public void setDocTitle(String docTitle) {
this.docTitle = docTitle;
}
public String getDocAuthor() {
return docAuthor;
}
public void setDocAuthor(String docAuthor) {
this.docAuthor = docAuthor;
}
public String getSecurityGroup() {
return securityGroup;
}
public void setSecurityGroup(String securityGroup) {
this.securityGroup = securityGroup;
}
public String getDocAccount() {
return docAccount;
}
public void setDocAccount(String docAccount) {
this.docAccount = docAccount;
}
public Integer getRevLabel() {
return revLabel;
}
public void setRevLabel(Integer revLabel) {
this.revLabel = revLabel;
}
public String getProfile() {
return profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
public LabelValueBean<String> getWorkflowStage() {
return workflowStage;
}
public void setWorkflowStage(LabelValueBean<String> workflowStage) {
this.workflowStage = workflowStage;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getInDate() {
return inDate;
}
public void setInDate(Date inDate) {
this.inDate = inDate;
}
public String getOriginalName() {
return originalName;
}
public void setOriginalName(String originalName) {
this.originalName = originalName;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public Long getFileSize() {
return fileSize;
}
public void setFileSize(Long fileSize) {
this.fileSize = fileSize;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public LabelValueBean<String> getEntity() {
return entity;
}
public void setEntity(LabelValueBean<String> entity) {
this.entity = entity;
}
public LabelValueBean<String> getBrand() {
return brand;
}
public void setBrand(LabelValueBean<String> brand) {
this.brand = brand;
}
public LabelValueBean<String> getProduct() {
return product;
}
public void setProduct(LabelValueBean<String> product) {
this.product = product;
}
public LabelValueBean<String> getCollection() {
return collection;
}
public void setCollection(LabelValueBean<String> collection) {
this.collection = collection;
}
public LabelValueBean<String> getSubCollection() {
return subCollection;
}
public void setSubCollection(LabelValueBean<String> subCollection) {
this.subCollection = subCollection;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LabelValueBean<String> getProgram() {
return program;
}
public void setProgram(LabelValueBean<String> program) {
this.program = program;
}
public String getVintage() {
return vintage;
}
public void setVintage(String vintage) {
this.vintage = vintage;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getRestrictedZone() {
return restrictedZone;
}
public void setRestrictedZone(String restrictedZone) {
this.restrictedZone = restrictedZone;
}
public LabelValueBean<String> getEvent() {
return event;
}
public void setEvent(LabelValueBean<String> event) {
this.event = event;
}
public LabelValueBean<String> getLanguage() {
return language;
}
public void setLanguage(LabelValueBean<String> language) {
this.language = language;
}
public String getGeographicLocation() {
return geographicLocation;
}
public void setGeographicLocation(String geographicLocation) {
this.geographicLocation = geographicLocation;
}
public String getWatermark() {
return watermark;
}
public void setWatermark(String watermark) {
this.watermark = watermark;
}
public Integer getPageNumber() {
return pageNumber;
}
public void setPageNumber(Integer pageNumber) {
this.pageNumber = pageNumber;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getAgentName() {
return agentName;
}
public void setAgentName(String agentName) {
this.agentName = agentName;
}
public String getCommissionedByName() {
return commissionedByName;
}
public void setCommissionedByName(String commissionedByName) {
this.commissionedByName = commissionedByName;
}
public String getCommissionedByDepartment() {
return commissionedByDepartment;
}
public void setCommissionedByDepartment(String commissionedByDepartment) {
this.commissionedByDepartment = commissionedByDepartment;
}
public LabelValueBean<Integer> getBestOf() {
return bestOf;
}
public void setBestOf(LabelValueBean<Integer> bestOf) {
this.bestOf = bestOf;
}
public String getMediaLocation() {
return mediaLocation;
}
public void setMediaLocation(String mediaLocation) {
this.mediaLocation = mediaLocation;
}
public LabelValueBean<Integer> getFullRights() {
return fullRights;
}
public void setFullRights(LabelValueBean<Integer> fullRights) {
this.fullRights = fullRights;
}
public LabelValueBean<String> getMediaUsage() {
return mediaUsage;
}
public void setMediaUsage(LabelValueBean<String> mediaUsage) {
this.mediaUsage = mediaUsage;
}
public Date getRightsEndDate() {
return rightsEndDate;
}
public void setRightsEndDate(Date rightsEndDate) {
this.rightsEndDate = rightsEndDate;
}
public String getGeographicRights() {
return geographicRights;
}
public void setGeographicRights(String geographicRights) {
this.geographicRights = geographicRights;
}
public LabelValueBean<Integer> getEvinConformity() {
return evinConformity;
}
public void setEvinConformity(LabelValueBean<Integer> evinConformity) {
this.evinConformity = evinConformity;
}
public String getContactReference() {
return contactReference;
}
public void setContactReference(String contactReference) {
this.contactReference = contactReference;
}
public LabelValueBean<String> getPublicationScope() {
return publicationScope;
}
public void setPublicationScope(LabelValueBean<String> publicationScope) {
this.publicationScope = publicationScope;
}
public String getRightsComment() {
return rightsComment;
}
public void setRightsComment(String rightsComment) {
this.rightsComment = rightsComment;
}
}
And Content:
public class Content implements Serializable {
private static final long serialVersionUID = 2999449587418137835L;
private Boolean selected;
private Boolean renditionInfoFetched;
private String searchPageImageRendition;
private String detailPageImageRendition;
private String videoRendition;
private Integer id;
private String docName;
private String docType;
private String docTitle;
private String docAuthor;
private String securityGroup;
private String docAccount;
private Integer revLabel;
private String profile;
private Date createDate;
private Date inDate;
private String originalName;
private String format;
private String extension;
private Long fileSize;
private String author;
private LabelValueBean<String> entity;
private LabelValueBean<String> brand;
private LabelValueBean<String> product;
private LabelValueBean<String> collection;
private LabelValueBean<String> subCollection;
private String description;
private LabelValueBean<String> program;
private String vintage;
private String model;
private String restrictedZone;
private LabelValueBean<String> event;
private LabelValueBean<String> language;
private String geographicLocation;
private String watermark;
private Integer pageNumber;
private String summary;
private String agentName;
private String commissionedByName;
private String commissionedByDepartment;
private LabelValueBean<Integer> bestOf;
private String mediaLocation;
private LabelValueBean<Integer> fullRights;
private LabelValueBean<String> mediaUsage;
private Date rightsEndDate;
private String geographicRights;
private LabelValueBean<Integer> evinConformity;
private String contactReference;
private LabelValueBean<String> publicationScope;
private String rightsComment;
public Boolean getSelected() {
return selected;
}
public void setSelected(Boolean selected) {
this.selected = selected;
}
public Boolean getRenditionInfoFetched() {
return renditionInfoFetched;
}
public void setRenditionInfoFetched(Boolean renditionInfoFetched) {
this.renditionInfoFetched = renditionInfoFetched;
}
public String getSearchPageImageRendition() {
return searchPageImageRendition;
}
public void setSearchPageImageRendition(String searchPageImageRendition) {
this.searchPageImageRendition = searchPageImageRendition;
}
public String getDetailPageImageRendition() {
return detailPageImageRendition;
}
public void setDetailPageImageRendition(String detailPageImageRendition) {
this.detailPageImageRendition = detailPageImageRendition;
}
public String getVideoRendition() {
return videoRendition;
}
public void setVideoRendition(String videoRendition) {
this.videoRendition = videoRendition;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDocName() {
return docName;
}
public void setDocName(String docName) {
this.docName = docName;
}
public String getDocType() {
return docType;
}
public void setDocType(String docType) {
this.docType = docType;
}
public String getDocTitle() {
return docTitle;
}
public void setDocTitle(String docTitle) {
this.docTitle = docTitle;
}
public String getDocAuthor() {
return docAuthor;
}
public void setDocAuthor(String docAuthor) {
this.docAuthor = docAuthor;
}
public String getSecurityGroup() {
return securityGroup;
}
public void setSecurityGroup(String securityGroup) {
this.securityGroup = securityGroup;
}
public String getDocAccount() {
return docAccount;
}
public void setDocAccount(String docAccount) {
this.docAccount = docAccount;
}
public Integer getRevLabel() {
return revLabel;
}
public void setRevLabel(Integer revLabel) {
this.revLabel = revLabel;
}
public String getProfile() {
return profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getInDate() {
return inDate;
}
public void setInDate(Date inDate) {
this.inDate = inDate;
}
public String getOriginalName() {
return originalName;
}
public void setOriginalName(String originalName) {
this.originalName = originalName;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public Long getFileSize() {
return fileSize;
}
public void setFileSize(Long fileSize) {
this.fileSize = fileSize;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public LabelValueBean<String> getEntity() {
return entity;
}
public void setEntity(LabelValueBean<String> entity) {
this.entity = entity;
}
public LabelValueBean<String> getBrand() {
return brand;
}
public void setBrand(LabelValueBean<String> brand) {
this.brand = brand;
}
public LabelValueBean<String> getProduct() {
return product;
}
public void setProduct(LabelValueBean<String> product) {
this.product = product;
}
public LabelValueBean<String> getCollection() {
return collection;
}
public void setCollection(LabelValueBean<String> collection) {
this.collection = collection;
}
public LabelValueBean<String> getSubCollection() {
return subCollection;
}
public void setSubCollection(LabelValueBean<String> subCollection) {
this.subCollection = subCollection;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LabelValueBean<String> getProgram() {
return program;
}
public void setProgram(LabelValueBean<String> program) {
this.program = program;
}
public String getVintage() {
return vintage;
}
public void setVintage(String vintage) {
this.vintage = vintage;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getRestrictedZone() {
return restrictedZone;
}
public void setRestrictedZone(String restrictedZone) {
this.restrictedZone = restrictedZone;
}
public LabelValueBean<String> getEvent() {
return event;
}
public void setEvent(LabelValueBean<String> event) {
this.event = event;
}
public LabelValueBean<String> getLanguage() {
return language;
}
public void setLanguage(LabelValueBean<String> language) {
this.language = language;
}
public String getGeographicLocation() {
return geographicLocation;
}
public void setGeographicLocation(String geographicLocation) {
this.geographicLocation = geographicLocation;
}
public String getWatermark() {
return watermark;
}
public void setWatermark(String watermark) {
this.watermark = watermark;
}
public Integer getPageNumber() {
return pageNumber;
}
public void setPageNumber(Integer pageNumber) {
this.pageNumber = pageNumber;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getAgentName() {
return agentName;
}
public void setAgentName(String agentName) {
this.agentName = agentName;
}
public String getCommissionedByName() {
return commissionedByName;
}
public void setCommissionedByName(String commissionedByName) {
this.commissionedByName = commissionedByName;
}
public String getCommissionedByDepartment() {
return commissionedByDepartment;
}
public void setCommissionedByDepartment(String commissionedByDepartment) {
this.commissionedByDepartment = commissionedByDepartment;
}
public LabelValueBean<Integer> getBestOf() {
return bestOf;
}
public void setBestOf(LabelValueBean<Integer> bestOf) {
this.bestOf = bestOf;
}
public String getMediaLocation() {
return mediaLocation;
}
public void setMediaLocation(String mediaLocation) {
this.mediaLocation = mediaLocation;
}
public LabelValueBean<Integer> getFullRights() {
return fullRights;
}
public void setFullRights(LabelValueBean<Integer> fullRights) {
this.fullRights = fullRights;
}
public LabelValueBean<String> getMediaUsage() {
return mediaUsage;
}
public void setMediaUsage(LabelValueBean<String> mediaUsage) {
this.mediaUsage = mediaUsage;
}
public Date getRightsEndDate() {
return rightsEndDate;
}
public void setRightsEndDate(Date rightsEndDate) {
this.rightsEndDate = rightsEndDate;
}
public String getGeographicRights() {
return geographicRights;
}
public void setGeographicRights(String geographicRights) {
this.geographicRights = geographicRights;
}
public LabelValueBean<Integer> getEvinConformity() {
return evinConformity;
}
public void setEvinConformity(LabelValueBean<Integer> evinConformity) {
this.evinConformity = evinConformity;
}
public String getContactReference() {
return contactReference;
}
public void setContactReference(String contactReference) {
this.contactReference = contactReference;
}
public LabelValueBean<String> getPublicationScope() {
return publicationScope;
}
public void setPublicationScope(LabelValueBean<String> publicationScope) {
this.publicationScope = publicationScope;
}
public String getRightsComment() {
return rightsComment;
}
public void setRightsComment(String rightsComment) {
this.rightsComment = rightsComment;
}
}
I am trying to copy properties from SearchContent to Content as:
Content content = new Content();
Converter converter = new DateConverter(null);
BeanUtilsBean beanUtilsBean = BeanUtilsBean.getInstance();
beanUtilsBean.getConvertUtils().register(converter, Date.class);
BeanUtils.copyProperties(searchContent, content);
System.out.println(searchContent);
System.out.println(content);
The Sysout is printing:
com.mhis.dam.service.search.bean.SearchContent[id=52906,docName=MHIS043570,docType=Images,docTitle=preview_1_8,docAuthor=sysadmin,securityGroup=Internal,docAccount=WF/017/DAM/000,revLabel=1,profile=DAMMedia,workflowStage=com.mhis.dam.generic.bean.LabelValueBean[label=Published,value=published],createDate=Fri Oct 18 15:30:35 IST 2013,inDate=Fri Oct 18 15:30:35 IST 2013,originalName=Vintage 2004 Gift Box & Bottle Black - hires.jpg,format=image/jpeg,extension=jpg,fileSize=2106898,author=Arjan,entity=com.mhis.dam.generic.bean.LabelValueBean[label=Dom Perignon,value=WF/017/DAM],brand=com.mhis.dam.generic.bean.LabelValueBean[label=Dom Perignon,value=WF/017/DAM/001],product=com.mhis.dam.generic.bean.LabelValueBean[label=Blanc,value=17_1_blanc],collection=com.mhis.dam.generic.bean.LabelValueBean[label=Pack shot,value=pack_shot_dp],subCollection=com.mhis.dam.generic.bean.LabelValueBean[label=Bottle shot,value=ps_bottle_dp],description=preview_1,program=com.mhis.dam.generic.bean.LabelValueBean[label=<null>,value=],vintage=,model=,restrictedZone=,event=com.mhis.dam.generic.bean.LabelValueBean[label=<null>,value=],language=com.mhis.dam.generic.bean.LabelValueBean[label=<null>,value=],geographicLocation=,watermark=,pageNumber=0,summary=,agentName=,commissionedByName=Nicolas,commissionedByDepartment=,bestOf=com.mhis.dam.generic.bean.LabelValueBean[label=<null>,value=0],mediaLocation=,fullRights=com.mhis.dam.generic.bean.LabelValueBean[label=<null>,value=1],mediaUsage=com.mhis.dam.generic.bean.LabelValueBean[label=<null>,value=],rightsEndDate=<null>,geographicRights=,evinConformity=com.mhis.dam.generic.bean.LabelValueBean[label=<null>,value=2],contactReference=,publicationScope=com.mhis.dam.generic.bean.LabelValueBean[label=Full public usage,value=fullPublic],rightsComment=]
com.mhis.dam.web.model.Content[selected=<null>,renditionInfoFetched=<null>,searchPageImageRendition=<null>,detailPageImageRendition=<null>,videoRendition=<null>,id=<null>,docName=<null>,docType=<null>,docTitle=<null>,docAuthor=<null>,securityGroup=<null>,docAccount=<null>,revLabel=<null>,profile=<null>,createDate=<null>,inDate=<null>,originalName=<null>,format=<null>,extension=<null>,fileSize=<null>,author=<null>,entity=<null>,brand=<null>,product=<null>,collection=<null>,subCollection=<null>,description=<null>,program=<null>,vintage=<null>,model=<null>,restrictedZone=<null>,event=<null>,language=<null>,geographicLocation=<null>,watermark=<null>,pageNumber=<null>,summary=<null>,agentName=<null>,commissionedByName=<null>,commissionedByDepartment=<null>,bestOf=<null>,mediaLocation=<null>,fullRights=<null>,mediaUsage=<null>,rightsEndDate=<null>,geographicRights=<null>,evinConformity=<null>,contactReference=<null>,publicationScope=<null>,rightsComment=<null>]
It is obvious to have null values for selected and renditionInfoFetched fields of the class Content, since they are not present in SearchContent but you can see all the other properties of Content is null. I am unable to find what I am doing wrong!
Any pointer would be very helpful.
There are two BeanUtils.copyProperties(parameter1, parameter2) in Java.
One is
org.apache.commons.beanutils.BeanUtils.copyProperties(Object dest,
Object orig)
Another is
org.springframework.beans.BeanUtils.copyProperties(Object source,
Object target)
Pay attention to the opposite position of parameters.
If you want to copy from searchContent to content, then code should be as follows
BeanUtils.copyProperties(content, searchContent);
You need to reverse the parameters as above in your code.
From API,
public static void copyProperties(Object dest, Object orig)
throws IllegalAccessException,
InvocationTargetException)
Parameters:
dest - Destination bean whose properties are modified
orig - Origin bean whose properties are retrieved
As you can see in the below source code, BeanUtils.copyProperties internally uses reflection and there's additional internal cache lookup steps as well which is going to add cost wrt performance
private static void copyProperties(Object source, Object target, #Nullable Class<?> editable,
#Nullable String... ignoreProperties) throws BeansException {
Assert.notNull(source, "Source must not be null");
Assert.notNull(target, "Target must not be null");
Class<?> actualEditable = target.getClass();
if (editable != null) {
if (!editable.isInstance(target)) {
throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
"] not assignable to Editable class [" + editable.getName() + "]");
}
actualEditable = editable;
}
**PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);**
List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
for (PropertyDescriptor targetPd : targetPds) {
Method writeMethod = targetPd.getWriteMethod();
if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
if (sourcePd != null) {
Method readMethod = sourcePd.getReadMethod();
if (readMethod != null &&
ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
try {
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source);
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}
writeMethod.invoke(target, value);
}
catch (Throwable ex) {
throw new FatalBeanException(
"Could not copy property '" + targetPd.getName() + "' from source to target", ex);
}
}
}
}
}
}
So it's better to use plain setters given the cost reflection