How to use BeanUtils.copyProperties? - java

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

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

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

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

Using GSON to parse an JSON object with an array of elements

How can I use GSON to parse the following JSON object:
{
"ProductsByCategory": [
{.....},
{.....},
{.....},
{.....},
]
}
The JSON object contains an array of elements. I am using GSON to try and parse the JSON and have the following POJO classes to assist me with this.
public class ProductItems {
#SerializedName("ProductsByCategory")
#Expose
private List<ProductsByCategory> productsByCategory = null;
public List<ProductsByCategory> getProductsByCategory() {
return productsByCategory;
}
public void setProductsByCategory(List<ProductsByCategory> productsByCategory) {
this.productsByCategory = productsByCategory;
}
}
public class ProductsByCategory {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("slug")
#Expose
private String slug;
#SerializedName("permalink")
#Expose
private String permalink;
#SerializedName("date_created")
#Expose
private String dateCreated;
#SerializedName("date_created_gmt")
#Expose
private String dateCreatedGmt;
#SerializedName("date_modified")
#Expose
private String dateModified;
#SerializedName("date_modified_gmt")
#Expose
private String dateModifiedGmt;
#SerializedName("type")
#Expose
private String type;
#SerializedName("status")
#Expose
private String status;
#SerializedName("featured")
#Expose
private Boolean featured;
#SerializedName("catalog_visibility")
#Expose
private String catalogVisibility;
#SerializedName("description")
#Expose
private String description;
#SerializedName("short_description")
#Expose
private String shortDescription;
#SerializedName("sku")
#Expose
private String sku;
#SerializedName("price")
#Expose
private String price;
#SerializedName("regular_price")
#Expose
private String regularPrice;
#SerializedName("sale_price")
#Expose
private String salePrice;
#SerializedName("date_on_sale_from")
#Expose
private Object dateOnSaleFrom;
#SerializedName("date_on_sale_from_gmt")
#Expose
private Object dateOnSaleFromGmt;
#SerializedName("date_on_sale_to")
#Expose
private Object dateOnSaleTo;
#SerializedName("date_on_sale_to_gmt")
#Expose
private Object dateOnSaleToGmt;
#SerializedName("price_html")
#Expose
private String priceHtml;
#SerializedName("on_sale")
#Expose
private Boolean onSale;
#SerializedName("purchasable")
#Expose
private Boolean purchasable;
#SerializedName("total_sales")
#Expose
private Integer totalSales;
#SerializedName("virtual")
#Expose
private Boolean virtual;
#SerializedName("downloadable")
#Expose
private Boolean downloadable;
#SerializedName("downloads")
#Expose
private List<Object> downloads = null;
#SerializedName("download_limit")
#Expose
private Integer downloadLimit;
#SerializedName("download_expiry")
#Expose
private Integer downloadExpiry;
#SerializedName("external_url")
#Expose
private String externalUrl;
#SerializedName("button_text")
#Expose
private String buttonText;
#SerializedName("tax_status")
#Expose
private String taxStatus;
#SerializedName("tax_class")
#Expose
private String taxClass;
#SerializedName("manage_stock")
#Expose
private Boolean manageStock;
#SerializedName("stock_quantity")
#Expose
private Integer stockQuantity;
#SerializedName("in_stock")
#Expose
private Boolean inStock;
#SerializedName("backorders")
#Expose
private String backorders;
#SerializedName("backorders_allowed")
#Expose
private Boolean backordersAllowed;
#SerializedName("backordered")
#Expose
private Boolean backordered;
#SerializedName("sold_individually")
#Expose
private Boolean soldIndividually;
#SerializedName("weight")
#Expose
private String weight;
#SerializedName("dimensions")
#Expose
private Dimensions dimensions;
#SerializedName("shipping_required")
#Expose
private Boolean shippingRequired;
#SerializedName("shipping_taxable")
#Expose
private Boolean shippingTaxable;
#SerializedName("shipping_class")
#Expose
private String shippingClass;
#SerializedName("shipping_class_id")
#Expose
private Integer shippingClassId;
#SerializedName("reviews_allowed")
#Expose
private Boolean reviewsAllowed;
#SerializedName("average_rating")
#Expose
private String averageRating;
#SerializedName("rating_count")
#Expose
private Integer ratingCount;
#SerializedName("related_ids")
#Expose
private List<Integer> relatedIds = null;
#SerializedName("upsell_ids")
#Expose
private List<Object> upsellIds = null;
#SerializedName("cross_sell_ids")
#Expose
private List<Object> crossSellIds = null;
#SerializedName("parent_id")
#Expose
private Integer parentId;
#SerializedName("purchase_note")
#Expose
private String purchaseNote;
#SerializedName("categories")
#Expose
private List<Category> categories = null;
#SerializedName("tags")
#Expose
private List<Object> tags = null;
#SerializedName("images")
#Expose
private List<Image> images = null;
#SerializedName("attributes")
#Expose
private List<Attribute> attributes = null;
#SerializedName("default_attributes")
#Expose
private List<Object> defaultAttributes = null;
#SerializedName("variations")
#Expose
private List<Integer> variations = null;
#SerializedName("grouped_products")
#Expose
private List<Object> groupedProducts = null;
#SerializedName("menu_order")
#Expose
private Integer menuOrder;
#SerializedName("meta_data")
#Expose
private List<MetaDatum> metaData = null;
#SerializedName("_links")
#Expose
private Links links;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getPermalink() {
return permalink;
}
public void setPermalink(String permalink) {
this.permalink = permalink;
}
public String getDateCreated() {
return dateCreated;
}
public void setDateCreated(String dateCreated) {
this.dateCreated = dateCreated;
}
public String getDateCreatedGmt() {
return dateCreatedGmt;
}
public void setDateCreatedGmt(String dateCreatedGmt) {
this.dateCreatedGmt = dateCreatedGmt;
}
public String getDateModified() {
return dateModified;
}
public void setDateModified(String dateModified) {
this.dateModified = dateModified;
}
public String getDateModifiedGmt() {
return dateModifiedGmt;
}
public void setDateModifiedGmt(String dateModifiedGmt) {
this.dateModifiedGmt = dateModifiedGmt;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Boolean getFeatured() {
return featured;
}
public void setFeatured(Boolean featured) {
this.featured = featured;
}
public String getCatalogVisibility() {
return catalogVisibility;
}
public void setCatalogVisibility(String catalogVisibility) {
this.catalogVisibility = catalogVisibility;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getRegularPrice() {
return regularPrice;
}
public void setRegularPrice(String regularPrice) {
this.regularPrice = regularPrice;
}
public String getSalePrice() {
return salePrice;
}
public void setSalePrice(String salePrice) {
this.salePrice = salePrice;
}
public Object getDateOnSaleFrom() {
return dateOnSaleFrom;
}
public void setDateOnSaleFrom(Object dateOnSaleFrom) {
this.dateOnSaleFrom = dateOnSaleFrom;
}
public Object getDateOnSaleFromGmt() {
return dateOnSaleFromGmt;
}
public void setDateOnSaleFromGmt(Object dateOnSaleFromGmt) {
this.dateOnSaleFromGmt = dateOnSaleFromGmt;
}
public Object getDateOnSaleTo() {
return dateOnSaleTo;
}
public void setDateOnSaleTo(Object dateOnSaleTo) {
this.dateOnSaleTo = dateOnSaleTo;
}
public Object getDateOnSaleToGmt() {
return dateOnSaleToGmt;
}
public void setDateOnSaleToGmt(Object dateOnSaleToGmt) {
this.dateOnSaleToGmt = dateOnSaleToGmt;
}
public String getPriceHtml() {
return priceHtml;
}
public void setPriceHtml(String priceHtml) {
this.priceHtml = priceHtml;
}
public Boolean getOnSale() {
return onSale;
}
public void setOnSale(Boolean onSale) {
this.onSale = onSale;
}
public Boolean getPurchasable() {
return purchasable;
}
public void setPurchasable(Boolean purchasable) {
this.purchasable = purchasable;
}
public Integer getTotalSales() {
return totalSales;
}
public void setTotalSales(Integer totalSales) {
this.totalSales = totalSales;
}
public Boolean getVirtual() {
return virtual;
}
public void setVirtual(Boolean virtual) {
this.virtual = virtual;
}
public Boolean getDownloadable() {
return downloadable;
}
public void setDownloadable(Boolean downloadable) {
this.downloadable = downloadable;
}
public List<Object> getDownloads() {
return downloads;
}
public void setDownloads(List<Object> downloads) {
this.downloads = downloads;
}
public Integer getDownloadLimit() {
return downloadLimit;
}
public void setDownloadLimit(Integer downloadLimit) {
this.downloadLimit = downloadLimit;
}
public Integer getDownloadExpiry() {
return downloadExpiry;
}
public void setDownloadExpiry(Integer downloadExpiry) {
this.downloadExpiry = downloadExpiry;
}
public String getExternalUrl() {
return externalUrl;
}
public void setExternalUrl(String externalUrl) {
this.externalUrl = externalUrl;
}
public String getButtonText() {
return buttonText;
}
public void setButtonText(String buttonText) {
this.buttonText = buttonText;
}
public String getTaxStatus() {
return taxStatus;
}
public void setTaxStatus(String taxStatus) {
this.taxStatus = taxStatus;
}
public String getTaxClass() {
return taxClass;
}
public void setTaxClass(String taxClass) {
this.taxClass = taxClass;
}
public Boolean getManageStock() {
return manageStock;
}
public void setManageStock(Boolean manageStock) {
this.manageStock = manageStock;
}
public Integer getStockQuantity() {
return stockQuantity;
}
public void setStockQuantity(Integer stockQuantity) {
this.stockQuantity = stockQuantity;
}
public Boolean getInStock() {
return inStock;
}
public void setInStock(Boolean inStock) {
this.inStock = inStock;
}
public String getBackorders() {
return backorders;
}
public void setBackorders(String backorders) {
this.backorders = backorders;
}
public Boolean getBackordersAllowed() {
return backordersAllowed;
}
public void setBackordersAllowed(Boolean backordersAllowed) {
this.backordersAllowed = backordersAllowed;
}
public Boolean getBackordered() {
return backordered;
}
public void setBackordered(Boolean backordered) {
this.backordered = backordered;
}
public Boolean getSoldIndividually() {
return soldIndividually;
}
public void setSoldIndividually(Boolean soldIndividually) {
this.soldIndividually = soldIndividually;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public Dimensions getDimensions() {
return dimensions;
}
public void setDimensions(Dimensions dimensions) {
this.dimensions = dimensions;
}
public Boolean getShippingRequired() {
return shippingRequired;
}
public void setShippingRequired(Boolean shippingRequired) {
this.shippingRequired = shippingRequired;
}
public Boolean getShippingTaxable() {
return shippingTaxable;
}
public void setShippingTaxable(Boolean shippingTaxable) {
this.shippingTaxable = shippingTaxable;
}
public String getShippingClass() {
return shippingClass;
}
public void setShippingClass(String shippingClass) {
this.shippingClass = shippingClass;
}
public Integer getShippingClassId() {
return shippingClassId;
}
public void setShippingClassId(Integer shippingClassId) {
this.shippingClassId = shippingClassId;
}
public Boolean getReviewsAllowed() {
return reviewsAllowed;
}
public void setReviewsAllowed(Boolean reviewsAllowed) {
this.reviewsAllowed = reviewsAllowed;
}
public String getAverageRating() {
return averageRating;
}
public void setAverageRating(String averageRating) {
this.averageRating = averageRating;
}
public Integer getRatingCount() {
return ratingCount;
}
public void setRatingCount(Integer ratingCount) {
this.ratingCount = ratingCount;
}
public List<Integer> getRelatedIds() {
return relatedIds;
}
public void setRelatedIds(List<Integer> relatedIds) {
this.relatedIds = relatedIds;
}
public List<Object> getUpsellIds() {
return upsellIds;
}
public void setUpsellIds(List<Object> upsellIds) {
this.upsellIds = upsellIds;
}
public List<Object> getCrossSellIds() {
return crossSellIds;
}
public void setCrossSellIds(List<Object> crossSellIds) {
this.crossSellIds = crossSellIds;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public String getPurchaseNote() {
return purchaseNote;
}
public void setPurchaseNote(String purchaseNote) {
this.purchaseNote = purchaseNote;
}
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public List<Object> getTags() {
return tags;
}
public void setTags(List<Object> tags) {
this.tags = tags;
}
public List<Image> getImages() {
return images;
}
public void setImages(List<Image> images) {
this.images = images;
}
public List<Attribute> getAttributes() {
return attributes;
}
public void setAttributes(List<Attribute> attributes) {
this.attributes = attributes;
}
public List<Object> getDefaultAttributes() {
return defaultAttributes;
}
public void setDefaultAttributes(List<Object> defaultAttributes) {
this.defaultAttributes = defaultAttributes;
}
public List<Integer> getVariations() {
return variations;
}
public void setVariations(List<Integer> variations) {
this.variations = variations;
}
public List<Object> getGroupedProducts() {
return groupedProducts;
}
public void setGroupedProducts(List<Object> groupedProducts) {
this.groupedProducts = groupedProducts;
}
public Integer getMenuOrder() {
return menuOrder;
}
public void setMenuOrder(Integer menuOrder) {
this.menuOrder = menuOrder;
}
public List<MetaDatum> getMetaData() {
return metaData;
}
public void setMetaData(List<MetaDatum> metaData) {
this.metaData = metaData;
}
public Links getLinks() {
return links;
}
public void setLinks(Links links) {
this.links = links;
}
}
The code that I use is the following:
public void onResponse(Call call, Response response) throws IOException
{
String mMessage = response.body().string();
if (response.isSuccessful())
{
try
{
Gson gson = new Gson();
final ProductItems categoryProducts = gson.fromJson(mMessage, ProductItems.class);
response.close();
}
catch (Exception e)
{
Log.e("Error", "Failed to upload");
e.printStackTrace();
}
However, I get the following error: GSON throwing “Expected BEGIN_OBJECT but was BEGIN_ARRAY.
I have tried to change the ProductItems class to taking an object for productbycategories but then I get the following error: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2324 path $.ProductsByCategory[0].meta_data[0].value. I am now a bit confused.
The reason you get this error is that the data is not consistent with the way the POJO is generated.
This is the specific part of the data that has the issue:
"meta_data": [
{
"id": 14232,
"key": "_vc_post_settings",
"value": {
"vc_grid_id": []
}
},
{
"id": 14273,
"key": "fb_product_description",
"value": ""
},
{
"id": 14274,
"key": "fb_visibility",
"value": "1"
},
Notice how the "meta_data" field is an array of objects and that these objects contain a "value" field. The data type of the "value" varies- sometimes it's an object and other times it's a string.
One possible solution would be to change the MetaDatum class so that the value is an Object:
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class MetaDatum {
...
#SerializedName("value")
#Expose
private Object value;
...
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}

get values from string and copy the values to pojo properties : java

I have a string containing this values :
String verifyPaymentDetails = "{
2298597={mihpayid=403993715508098532, request_id=NULL, bank_ref_num=NULL, amt=53.77, disc=0.00, mode=CC, PG_TYPE=AXIS, card_no=512345XXXXXX2346, name_on_card=emu, udf2=0, addedon=2013-06-03 17:34:42, status=failure, unmappedstatus=failed, Merchant_UTR=NULL, Settled_At=NULL},
6503939={mihpayid=Not Found, status=Not Found}
}"
and I want to extract the values from the above string and store them like the following :
key would be 2298597 and values for the key mihpayid=403993715508098532, request_id=NULL, bank_ref_num=NULL, amt=53.77, disc=0.00, mode=CC, PG_TYPE=AXIS, card_no=512345XXXXXX2346, name_on_card=emu, udf2=0, addedon=2013-06-03 17:34:42, status=failure, unmappedstatus=failed, Merchant_UTR=NULL, Settled_At=NULL
Map<String,Item> tag = new HashMap<String,VerifyPaymentRO>();
and this is what is my VerifyPaymentRO
public class VerifyPaymentRO {
private String mihpayid;
private String request_id;
private String bank_ref_num;
private String amt;
private String disc;
private String mode;
private String PG_TYPE;
private String card_no;
private String name_on_card;
private String udf2;
private String addedon;
private String status;
private String unmappedstatus;
private String Merchant_UTR;
private String Settled_At;
public String getMihpayid() {
return mihpayid;
}
public void setMihpayid(String mihpayid) {
this.mihpayid = mihpayid;
}
public String getRequest_id() {
return request_id;
}
public void setRequest_id(String request_id) {
this.request_id = request_id;
}
public String getBank_ref_num() {
return bank_ref_num;
}
public void setBank_ref_num(String bank_ref_num) {
this.bank_ref_num = bank_ref_num;
}
public String getAmt() {
return amt;
}
public void setAmt(String amt) {
this.amt = amt;
}
public String getDisc() {
return disc;
}
public void setDisc(String disc) {
this.disc = disc;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public String getPG_TYPE() {
return PG_TYPE;
}
public void setPG_TYPE(String pG_TYPE) {
PG_TYPE = pG_TYPE;
}
public String getCard_no() {
return card_no;
}
public void setCard_no(String card_no) {
this.card_no = card_no;
}
public String getName_on_card() {
return name_on_card;
}
public void setName_on_card(String name_on_card) {
this.name_on_card = name_on_card;
}
public String getUdf2() {
return udf2;
}
public void setUdf2(String udf2) {
this.udf2 = udf2;
}
public String getAddedon() {
return addedon;
}
public void setAddedon(String addedon) {
this.addedon = addedon;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUnmappedstatus() {
return unmappedstatus;
}
public void setUnmappedstatus(String unmappedstatus) {
this.unmappedstatus = unmappedstatus;
}
public String getMerchant_UTR() {
return Merchant_UTR;
}
public void setMerchant_UTR(String merchant_UTR) {
Merchant_UTR = merchant_UTR;
}
public String getSettled_At() {
return Settled_At;
}
public void setSettled_At(String settled_At) {
Settled_At = settled_At;
}
}
so how do get the id from the string and values for the id and copy the values to POJO and store them like id and object in a HashMap?
if there is way for this in spring also fine
Assuming it is not a JSON and you really need to do the hard work, I think the best solution is to use the combination of Rojo and BeanMap from commons-beanutils. I am also author of Rojo, so I would like to show how it could be used in this context. I wouldn't recommend direct regexp mapping by group due to dynamically changing number of pairs inside, so that's why I think the BeanMap could do a lot of work for us.
First let's update your bean with id, which will serve as a primary key:
public class VerifyPaymentRO {
private String id;
private String mihpayid;
private String request_id;
private String bank_ref_num;
private String amt;
private String disc;
private String mode;
private String PG_TYPE;
private String card_no;
private String name_on_card;
private String udf2;
private String addedon;
private String status;
private String unmappedstatus;
private String Merchant_UTR;
private String Settled_At;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMihpayid() {
return mihpayid;
}
public void setMihpayid(String mihpayid) {
this.mihpayid = mihpayid;
}
public String getRequest_id() {
return request_id;
}
public void setRequest_id(String request_id) {
this.request_id = request_id;
}
public String getBank_ref_num() {
return bank_ref_num;
}
public void setBank_ref_num(String bank_ref_num) {
this.bank_ref_num = bank_ref_num;
}
public String getAmt() {
return amt;
}
public void setAmt(String amt) {
this.amt = amt;
}
public String getDisc() {
return disc;
}
public void setDisc(String disc) {
this.disc = disc;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public String getPG_TYPE() {
return PG_TYPE;
}
public void setPG_TYPE(String PG_TYPE) {
this.PG_TYPE = PG_TYPE;
}
public String getCard_no() {
return card_no;
}
public void setCard_no(String card_no) {
this.card_no = card_no;
}
public String getName_on_card() {
return name_on_card;
}
public void setName_on_card(String name_on_card) {
this.name_on_card = name_on_card;
}
public String getUdf2() {
return udf2;
}
public void setUdf2(String udf2) {
this.udf2 = udf2;
}
public String getAddedon() {
return addedon;
}
public void setAddedon(String addedon) {
this.addedon = addedon;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUnmappedstatus() {
return unmappedstatus;
}
public void setUnmappedstatus(String unmappedstatus) {
this.unmappedstatus = unmappedstatus;
}
public String getMerchant_UTR() {
return Merchant_UTR;
}
public void setMerchant_UTR(String merchant_UTR) {
Merchant_UTR = merchant_UTR;
}
public String getSettled_At() {
return Settled_At;
}
public void setSettled_At(String settled_At) {
Settled_At = settled_At;
}
}
Now the working example could be as follows:
public class VerifyPaymentExample {
public static void main(String[] args) {
String verifyPaymentDetails = "{" +
"2298597={mihpayid=403993715508098532, request_id=NULL, bank_ref_num=NULL, amt=53.77, disc=0.00, mode=CC, PG_TYPE=AXIS, card_no=512345XXXXXX2346, name_on_card=emu, udf2=0, addedon=2013-06-03 17:34:42, status=failure, unmappedstatus=failed, Merchant_UTR=NULL, Settled_At=NULL}," +
"6503939={mihpayid=Not Found, status=Not Found}" +
"}";
Map<String, VerifyPaymentRO> result = Rojo.asMap("(\\d+)=\\{(.+?)\\}", verifyPaymentDetails)
.entrySet()
.stream()
.map(e -> toBean(e))
.collect(Collectors.toMap(VerifyPaymentRO::getId, Function.identity()));
}
public static VerifyPaymentRO toBean(Map.Entry<String,String> entry) {
VerifyPaymentRO bean = new VerifyPaymentRO();
bean.setId(entry.getKey());
BeanMap beanMap = new BeanMap(bean);
Rojo.asMap("(\\w.+?)=([^,]+)", entry.getValue())
.forEach( (key, value) -> {
//Some additional mapping is required due to non-standard naming
if ("Settled_At".equals(key)) {
beanMap.put("settled_At", value);
} else if ("Merchant_UTR".equals(key)) {
beanMap.put("merchant_UTR", value);
} else {
beanMap.put(key, value);
}
});
return bean;
}
}
If you run the code and look into result, you should have exactly what you want.

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