Java Object Serialization to JSON using Jackson - java

I have the following POJO classes
#JsonIgnoreProperties(ignoreUnknown = true)
public class GroupUser {
#JsonProperty("userId")
int userId;
#JsonProperty("status")
int status;
#JsonProperty("admin")
int isAdmin;
#JsonProperty("email")
String email;
#JsonProperty("creator")
int Creator;
#JsonProperty("new")
int isNew;
// generated and cached
#JsonProperty("user_name")
String userName;
public GroupUser() {
}
#JsonIgnore
public GroupUser(String email, int isCreator) {
this.userId = 0;
this.email = email;
this.Creator = isCreator;
this.isAdmin = isCreator;
if (isCreator == 1) {
this.status = Group.STATE_ACCEPTED;
this.isNew = 0;
} else {
this.isNew = 1;
this.status = Group.STATE_INVITED;
}
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getIsAdmin() {
return isAdmin;
}
public void setIsAdmin(int isAdmin) {
this.isAdmin = isAdmin;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getCreator() {
return Creator;
}
public void setCreator(int creator) {
Creator = creator;
}
public int getIsNew() {
return isNew;
}
public void setIsNew(int isNew) {
this.isNew = isNew;
}
}
And
#JsonIgnoreProperties(ignoreUnknown = true)
public class Group {
#JsonIgnore
final public static int STATE_INVITED = 1;
#JsonIgnore
final public static int STATE_REJECTED = 2;
#JsonIgnore
final public static int STATE_ACCEPTED = 3;
#JsonIgnore
final public static int STATE_PENDING = 4;
#JsonProperty("location")
String location;
#JsonProperty("radius")
int radius;
#JsonProperty("adminApprovalForObservers")
int isAdminApprovalRequired;
#JsonProperty("title")
String Title;
#JsonProperty("groupUsers")
GroupUser[] Users;
#JsonProperty("newVotingOnlyByAdmin")
int onlyAdminCreatesVote;
#JsonProperty("new")
int isNew;
#JsonProperty("requiredVotes")
int requiredVotes;
#JsonProperty("type")
int type;
#JsonProperty("allowObservers")
int allowObservers;
#JsonProperty("thumb")
String imageUrl;
#JsonProperty("timestamp")
long timeStamp;
#JsonProperty("openForAnyone")
int isOpenForAnyone;
#JsonProperty("uniqueId")
String uiqueId;
#JsonProperty("newDecisionOnlyByAdmin")
int newDecisionOnlyByAdmin;
#JsonProperty("requirePresence")
int requirePresence;
#JsonProperty("groupId")
int groupId;
#JsonProperty("automaticExclusions")
int autoExclusion;
#JsonProperty("adminApprovalForMembership")
int adminApprovalForMembership;
#JsonProperty("description")
String description;
// generated and cached
#JsonProperty("creator_name")
String creatorName;
public Group() {
}
#JsonIgnore
public Group(int id) {
this.groupId = id;
}
#JsonIgnore
public Group(String name, String description, String imagePath) {
this.Title = name;
this.description = description;
this.groupId = 0;
this.location = "";
this.radius = 0;
this.imageUrl = imagePath;
this.isNew = 1;
this.Users = new GroupUser[] {};
this.isOpenForAnyone = 1;
this.onlyAdminCreatesVote = 0;
this.adminApprovalForMembership = 0;
this.allowObservers = 1;
this.timeStamp = Calendar.getInstance().getTimeInMillis() / 1000;
}
#JsonIgnore
public String getCreatorsEmail() {
for (GroupUser u : Users) {
if (u.getCreator() == 1) {
return u.getEmail();
}
}
return null;
}
#JsonIgnore
public int getCreatorsId() {
for (GroupUser u : Users) {
if (u.getCreator() == 1) {
return u.getUserId();
}
}
return -1;
}
#JsonIgnore
public GroupUser getUser(int userId) {
if (Users != null) {
for (GroupUser gu : Users) {
if (gu.getUserId() == userId) {
return gu;
}
}
}
return null;
}
public String getCreatorName() {
return creatorName;
}
public void setCreatorName(String creatorName) {
this.creatorName = creatorName;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public int getIsAdminApprovalRequired() {
return isAdminApprovalRequired;
}
public void setIsAdminApprovalRequired(int isAdminApprovalRequired) {
this.isAdminApprovalRequired = isAdminApprovalRequired;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
#JsonProperty("groupUsers")
public GroupUser[] getUsers() {
return Users;
}
#JsonProperty("groupUsers")
public void setUsers(GroupUser[] users) {
Users = users;
}
public int getOnlyAdminCreatesVote() {
return onlyAdminCreatesVote;
}
public void setOnlyAdminCreatesVote(int onlyAdminCreatesVote) {
this.onlyAdminCreatesVote = onlyAdminCreatesVote;
}
public int getIsNew() {
return isNew;
}
public void setIsNew(int isNew) {
this.isNew = isNew;
}
public int getRequiredVotes() {
return requiredVotes;
}
public void setRequiredVotes(int requiredVotes) {
this.requiredVotes = requiredVotes;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getAllowObservers() {
return allowObservers;
}
public void setAllowObservers(int allowObservers) {
this.allowObservers = allowObservers;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public long getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(long timeStamp) {
this.timeStamp = timeStamp;
}
public int getIsOpenForAnyone() {
return isOpenForAnyone;
}
public void setIsOpenForAnyone(int isOpenForAnyone) {
this.isOpenForAnyone = isOpenForAnyone;
}
public String getUiqueId() {
return uiqueId;
}
public void setUiqueId(String uiqueId) {
this.uiqueId = uiqueId;
}
public int getNewDecisionOnlyByAdmin() {
return newDecisionOnlyByAdmin;
}
public void setNewDecisionOnlyByAdmin(int newDecisionOnlyByAdmin) {
this.newDecisionOnlyByAdmin = newDecisionOnlyByAdmin;
}
public int getRequirePresence() {
return requirePresence;
}
public void setRequirePresence(int requirePresence) {
this.requirePresence = requirePresence;
}
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
public int getAutoExclusion() {
return autoExclusion;
}
public void setAutoExclusion(int autoExclusion) {
this.autoExclusion = autoExclusion;
}
public int getAdminApprovalForMembership() {
return adminApprovalForMembership;
}
public void setAdminApprovalForMembership(int adminApprovalForMembership) {
this.adminApprovalForMembership = adminApprovalForMembership;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
I am using jackson library to serialize the Group Object to JSON like below:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true);
return mapper.writeValueAsString(group);
But the Users fields never gets serialized, no matter what groupUsers always is an empty array []. Any idea what am I doing wrong?

Related

Realm Migration is not working in Android?

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 🥰 🥰 🥰 .

Null Pointer at foreign key

I'm using MySQL and Hibernate. I've added record to Receiving table and have id and barcode fields as foreign keys in transaction table rcid and barcode.
When I search a specific record using id:
int id =(Integer)defaultTableModel.getValueAt(jReceivingsTable.getSelectedRow(),0);
Receivings receivings = manager.searchReceivingsId(id);
that doesn't null, printing id return appropriate value so why I'm getting null when I set it to Transaction table?
Rctransaction rctransaction = new Rctransaction();
rctransaction.getReceivings().getId().setId(id); // here id has value
rctransaction.getReceivings().getId().setBarcode(barcode);
rctransaction.setReceivings(receivings);
Here are classes :
Receivings.java
public class Receivings implements java.io.Serializable {
private ReceivingsId id;
private Suppliers suppliers;
private String itemName;
private String category;
private double wholesalePrice;
private double retailPrice;
private long tax1;
private long tax2;
private String type1;
private String type2;
private int quantityStock;
private int receivingQuantity;
private int recorderLevel;
private String receivingDate;
private double discount;
private Set itemses = new HashSet(0);
private Set rctransactions = new HashSet(0);
public Receivings() {
}
public Receivings(ReceivingsId id, Suppliers suppliers, String itemName, String category, double wholesalePrice, double retailPrice, long tax1, long tax2, String type1, String type2, int quantityStock, int receivingQuantity, int recorderLevel, String receivingDate, double discount) {
this.id = id;
this.suppliers = suppliers;
this.itemName = itemName;
this.category = category;
this.wholesalePrice = wholesalePrice;
this.retailPrice = retailPrice;
this.tax1 = tax1;
this.tax2 = tax2;
this.type1 = type1;
this.type2 = type2;
this.quantityStock = quantityStock;
this.receivingQuantity = receivingQuantity;
this.recorderLevel = recorderLevel;
this.receivingDate = receivingDate;
this.discount = discount;
}
public Receivings(ReceivingsId id, Suppliers suppliers, String itemName, String category, double wholesalePrice, double retailPrice, long tax1, long tax2, String type1, String type2, int quantityStock, int receivingQuantity, int recorderLevel, String receivingDate, double discount, Set itemses, Set rctransactions) {
this.id = id;
this.suppliers = suppliers;
this.itemName = itemName;
this.category = category;
this.wholesalePrice = wholesalePrice;
this.retailPrice = retailPrice;
this.tax1 = tax1;
this.tax2 = tax2;
this.type1 = type1;
this.type2 = type2;
this.quantityStock = quantityStock;
this.receivingQuantity = receivingQuantity;
this.recorderLevel = recorderLevel;
this.receivingDate = receivingDate;
this.discount = discount;
this.itemses = itemses;
this.rctransactions = rctransactions;
}
public ReceivingsId getId() {
return this.id;
}
public void setId(ReceivingsId id) {
this.id = id;
}
public Suppliers getSuppliers() {
return this.suppliers;
}
public void setSuppliers(Suppliers suppliers) {
this.suppliers = suppliers;
}
public String getItemName() {
return this.itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getCategory() {
return this.category;
}
public void setCategory(String category) {
this.category = category;
}
public double getWholesalePrice() {
return this.wholesalePrice;
}
public void setWholesalePrice(double wholesalePrice) {
this.wholesalePrice = wholesalePrice;
}
public double getRetailPrice() {
return this.retailPrice;
}
public void setRetailPrice(double retailPrice) {
this.retailPrice = retailPrice;
}
public long getTax1() {
return this.tax1;
}
public void setTax1(long tax1) {
this.tax1 = tax1;
}
public long getTax2() {
return this.tax2;
}
public void setTax2(long tax2) {
this.tax2 = tax2;
}
public String getType1() {
return this.type1;
}
public void setType1(String type1) {
this.type1 = type1;
}
public String getType2() {
return this.type2;
}
public void setType2(String type2) {
this.type2 = type2;
}
public int getQuantityStock() {
return this.quantityStock;
}
public void setQuantityStock(int quantityStock) {
this.quantityStock = quantityStock;
}
public int getReceivingQuantity() {
return this.receivingQuantity;
}
public void setReceivingQuantity(int receivingQuantity) {
this.receivingQuantity = receivingQuantity;
}
public int getRecorderLevel() {
return this.recorderLevel;
}
public void setRecorderLevel(int recorderLevel) {
this.recorderLevel = recorderLevel;
}
public String getReceivingDate() {
return this.receivingDate;
}
public void setReceivingDate(String receivingDate) {
this.receivingDate = receivingDate;
}
public double getDiscount() {
return this.discount;
}
public void setDiscount(double discount) {
this.discount = discount;
}
public Set getItemses() {
return this.itemses;
}
public void setItemses(Set itemses) {
this.itemses = itemses;
}
public Set getRctransactions() {
return this.rctransactions;
}
public void setRctransactions(Set rctransactions) {
this.rctransactions = rctransactions;
}
}
ReceivingsId.java
//Composition of Id and Barcode of Receivings
public class ReceivingsId implements java.io.Serializable {
private int id;
private int barcode;
public ReceivingsId() {
}
public ReceivingsId(int id, int barcode) {
this.id = id;
this.barcode = barcode;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public int getBarcode() {
return this.barcode;
}
public void setBarcode(int barcode) {
this.barcode = barcode;
}
public boolean equals(Object other) {
if ( (this == other ) ) return true;
if ( (other == null ) ) return false;
if ( !(other instanceof ReceivingsId) ) return false;
ReceivingsId castOther = ( ReceivingsId ) other;
return (this.getId()==castOther.getId())
&& (this.getBarcode()==castOther.getBarcode());
}
public int hashCode() {
int result = 17;
result = 37 * result + this.getId();
result = 37 * result + this.getBarcode();
return result;
}
}
Rctransaction.java
public class Rctransaction implements java.io.Serializable {
private Integer id;
private Receivings receivings;
private String transaction;
private String supplierName;
private String itemName;
private double quantity;
private String paymentType;
private double amountTendred;
private double due;
private double total;
private double price;
private int recorderLevel;
public Rctransaction() {
}
public Rctransaction(Receivings receivings, String transaction, String supplierName, String itemName, double quantity, String paymentType, double amountTendred, double due, double total, double price, int recorderLevel) {
this.receivings = receivings;
this.transaction = transaction;
this.supplierName = supplierName;
this.itemName = itemName;
this.quantity = quantity;
this.paymentType = paymentType;
this.amountTendred = amountTendred;
this.due = due;
this.total = total;
this.price = price;
this.recorderLevel = recorderLevel;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Receivings getReceivings() {
return this.receivings;
}
public void setReceivings(Receivings receivings) {
this.receivings = receivings;
}
public String getTransaction() {
return this.transaction;
}
public void setTransaction(String transaction) {
this.transaction = transaction;
}
public String getSupplierName() {
return this.supplierName;
}
public void setSupplierName(String supplierName) {
this.supplierName = supplierName;
}
public String getItemName() {
return this.itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public double getQuantity() {
return this.quantity;
}
public void setQuantity(double quantity) {
this.quantity = quantity;
}
public String getPaymentType() {
return this.paymentType;
}
public void setPaymentType(String paymentType) {
this.paymentType = paymentType;
}
public double getAmountTendred() {
return this.amountTendred;
}
public void setAmountTendred(double amountTendred) {
this.amountTendred = amountTendred;
}
public double getDue() {
return this.due;
}
public void setDue(double due) {
this.due = due;
}
public double getTotal() {
return this.total;
}
public void setTotal(double total) {
this.total = total;
}
public double getPrice() {
return this.price;
}
public void setPrice(double price) {
this.price = price;
}
public int getRecorderLevel() {
return this.recorderLevel;
}
public void setRecorderLevel(int recorderLevel) {
this.recorderLevel = recorderLevel;
}
}
You are instantiating the Hibernate objects in the wrong order.
First you need a ReceivingsId :
ReceivingsId rid = new ReceivingsId (id, barcode);
Then add this rid to a Receivings:
Receivings rec = new Receivings();
rec.setId(rid);
And finally set it to the Rctransaction:
Rctransaction rctransaction = new Rctransaction();
rctransaction.setReceivings(rec);
If you try to call getReceivings after instantiating the object without setting it before you'll always get a NullPointerException. To avoid this, you can instantiate the Receivings object in the Rctransaction constructor.

ObjectMapper can't map the variables of inner class

ObjectMapper mapper = new ObjectMapper();
try {
attractionMainResponse = mapper.readValue(response,AttractionMainResponse.class);
} catch(IOException io) {
showToast("Something went wrong");
FirebaseCrash.log(io.toString());
finish();
}
AttractionMainResponse :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AttractionMainResponse {
private AttractionDetailModel Attraction_Info;
private String response;
public AttractionMainResponse() {
Attraction_Info = null;
response =null;
}
public AttractionMainResponse(AttractionDetailModel aa,String ab) {
Attraction_Info = aa;
response = ab;
}
public AttractionDetailModel getAttraction_Info() {
return Attraction_Info;
}
public void setAttraction_Info(AttractionDetailModel attraction_Info) {
Attraction_Info = attraction_Info;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}
AttractionDetailModel :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AttractionDetailModel {
private AddressDataAttraction address_data;
private List<Image> Images;
private TypesInAttraction Type;
private String architect;
private String architectural_style;
private int city_id;
private String founder;
private String description;
private int id;
private String name;
private String height;
private String opened_since;
private String popularity;
private String timings;
private String visitors;
private String profile_image_url;
public AttractionDetailModel() {
address_data = null;
architect = null;
architectural_style = null;
city_id=-1;
founder = null;
description = null;
id=-1;
name=null;
height=null;
opened_since=null;
popularity = null;
timings=null;
visitors=null;
Images = null;
Type=null;
profile_image_url=null;
}
public AttractionDetailModel(AddressDataAttraction address_data, List<Image> images, TypesInAttraction type, String architect, String architectural_style, int city_id, String founder, String description, int id, String name, String height, String opened_since, String popularity, String timings, String visitors, String profile_image_url) {
this.address_data = address_data;
Images = images;
Type = type;
this.architect = architect;
this.architectural_style = architectural_style;
this.city_id = city_id;
this.founder = founder;
this.description = description;
this.id = id;
this.name = name;
this.height = height;
this.opened_since = opened_since;
this.popularity = popularity;
this.timings = timings;
this.visitors = visitors;
this.profile_image_url = profile_image_url;
}
public String getProfile_image_url() {
return profile_image_url;
}
public void setProfile_image_url(String profile_image_url) {
this.profile_image_url = profile_image_url;
}
public AddressDataAttraction getAddress_data() {
return address_data;
}
public void setAddress_data(AddressDataAttraction address_data) {
this.address_data = address_data;
}
public List<Image> getImages() {
return Images;
}
public void setImages(List<Image> images) {
Images = images;
}
public TypesInAttraction getType() {
return Type;
}
public void setType(TypesInAttraction type) {
Type = type;
}
public String getArchitect() {
return architect;
}
public void setArchitect(String architect) {
this.architect = architect;
}
public String getArchitectural_style() {
return architectural_style;
}
public void setArchitectural_style(String architectural_style) {
this.architectural_style = architectural_style;
}
public int getCity_id() {
return city_id;
}
public void setCity_id(int city_id) {
this.city_id = city_id;
}
public String getFounder() {
return founder;
}
public void setFounder(String founder) {
this.founder = founder;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getOpened_since() {
return opened_since;
}
public void setOpened_since(String opened_since) {
this.opened_since = opened_since;
}
public String getPopularity() {
return popularity;
}
public void setPopularity(String popularity) {
this.popularity = popularity;
}
public String getTimings() {
return timings;
}
public void setTimings(String timings) {
this.timings = timings;
}
public String getVisitors() {
return visitors;
}
public void setVisitors(String visitors) {
this.visitors = visitors;
}
}
AddressDataAttractions :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AddressDataAttraction {
private String address;
private String city;
private String country;
private String landmark;
private float latitude;
private float longitude;
private String pincode;
private String state;
public AddressDataAttraction() {
address=null;
city=null;
country=null;
landmark=null;
latitude=-1;
longitude=-1;
pincode=null;
state=null;
}
public AddressDataAttraction(String address, String city, String country, String landmark, float latitude, float longitude, String pincode, String state) {
this.address = address;
this.city = city;
this.country = country;
this.landmark = landmark;
this.latitude = latitude;
this.longitude = longitude;
this.pincode = pincode;
this.state = state;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLandmark() {
return landmark;
}
public void setLandmark(String landmark) {
this.landmark = landmark;
}
public float getLatitude() {
return latitude;
}
public void setLatitude(float latitude) {
this.latitude = latitude;
}
public float getLongitude() {
return longitude;
}
public void setLongitude(float longitude) {
this.longitude = longitude;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
TypeInAttraction :
#JsonIgnoreProperties (ignoreUnknown = true)
public class TypesInAttraction{
private String type;
private int id ;
public TypesInAttraction() {
type=null;
id=-1;
}
public TypesInAttraction(String type, int id) {
this.type = type;
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
In debug mode, string response in objectMapper shows correct response, string response in attractionMainResponse giving a success but can't map the attractionDetailModel, giving null.
Is this about a Jackson ObjectMapper? Is it possible to create a smaller example, that makes it easier to give a solution.

How to use BeanUtils.copyProperties?

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

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