I have the following configuration file where I am trying to map this yaml file into Java POJO Classes with Snakeyaml library.
consumers:
- acls:
- group: GRP-NAME-1
tags:
- CON-NAME
- group: GRP-NAME-2
tags:
- CON-NAME-TAG
oauth2_credentials:
- client_id: CRD-NAME
client_secret: xxxx
name: CRD-NAME
redirect_uris:
- http://xyz
tags:
- CON-NAME-TAG
username: CON-NAME
tags:
- CON-NAME-TAG
RootConfig.java
public class RootConfig {
private List<Consumer> consumers;
public List<Consumer> getConsumers() {
return consumers;
}
public void setConsumers(List<Consumer> consumers) {
this.consumers = consumers;
}
}
Consumer.java:
public class Consumer {
private List<Acl> acls;
private List<Oauth2Credential> oauth2Credentials;
private String username;
private List<String> tags;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public List<Acl> getAcls() {
return acls;
}
public void setAcls(List<Acl> acls) {
this.acls = acls;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public List<Oauth2Credential> getOauth2Credentials() {
return oauth2Credentials;
}
public void setOauth2Credentials(List<Oauth2Credential> oauth2Credentials) {
this.oauth2Credentials = oauth2Credentials;
}
}
Oauth2Credential.java:
public class Oauth2Credential {
private String clientId;
private String clientSecret;
private String name;
private List<String> redirectUris;
private List<String> tags;
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getClientSecret() {
return clientSecret;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getRedirectUris() {
return redirectUris;
}
public void setRedirectUris(List<String> redirectUris) {
this.redirectUris = redirectUris;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
}
Acl.java:
public class Acl {
private String group;
private List<String> tags;
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
}
ConfigLoader.java:
public class ConfigLoader {
public RootConfig load(String file) {
Yaml yaml = new Yaml(new Constructor(RootConfig.class));
InputStream inputStream = this.getClass()
.getClassLoader()
.getResourceAsStream(file);
RootConfig rootConfig = yaml.load(inputStream);
System.out.println(rootConfig);
return rootConfig;
}
}
Config loader is giving me following error:
Caused by: Cannot create property=oauth2_credentials for JavaBean=uk.gov.hmrc.deck.config.tool.modal.Consumer#1554909b
in 'reader', line 9, column 5:
- oauth2_credentials:
^
Unable to find property 'oauth2_credentials' on class: uk.gov.hmrc.deck.config.tool.modal.Consumer
in 'reader', line 10, column 7:
- client_id: CRD-MDTP-BREATHINGS ...
^
at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.constructJavaBean2ndStep(Constructor.java:291)
at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.construct(Constructor.java:172)
at org.yaml.snakeyaml.constructor.BaseConstructor.constructObjectNoCheck(BaseConstructor.java:230)
at org.yaml.snakeyaml.constructor.BaseConstructor.constructObject(BaseConstructor.java:220)
at org.yaml.snakeyaml.constructor.BaseConstructor.constructSequenceStep2(BaseConstructor.java:391)
at org.yaml.snakeyaml.constructor.BaseConstructor.constructSequence(BaseConstructor.java:375)
at org.yaml.snakeyaml.constructor.Constructor$ConstructSequence.construct(Constructor.java:543)
at org.yaml.snakeyaml.constructor.BaseConstructor.constructObjectNoCheck(BaseConstructor.java:230)
at org.yaml.snakeyaml.constructor.BaseConstructor.constructObject(BaseConstructor.java:220)
at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.newInstance(Constructor.java:306)
at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.constructJavaBean2ndStep(Constructor.java:268)
... 10 more
Caused by: org.yaml.snakeyaml.error.YAMLException: Unable to find property 'oauth2_credentials' on class: uk.gov.hmrc.deck.config.tool.modal.Consumer
at org.yaml.snakeyaml.introspector.PropertyUtils.getProperty(PropertyUtils.java:158)
at org.yaml.snakeyaml.introspector.PropertyUtils.getProperty(PropertyUtils.java:148)
at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.getProperty(Constructor.java:310)
at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.constructJavaBean2ndStep(Constructor.java:231)
... 20 more
If I remove oauth2_credentials element, it seems to be working fine. I believe the underscore in the name is causing this issue.
Any idea how to fix this?
You will need to use #YamlProperty(key = "oauth2_credentials") as follows:
public class Consumer {
private List<Acl> acls;
#YamlProperty(key = "oauth2_credentials")
private List<Oauth2Credential> oauth2Credentials;
private String username;
private List<String> tags;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public List<Acl> getAcls() {
return acls;
}
public void setAcls(List<Acl> acls) {
this.acls = acls;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public List<Oauth2Credential> getOauth2Credentials() {
return oauth2Credentials;
}
public void setOauth2Credentials(List<Oauth2Credential> oauth2Credentials) {
this.oauth2Credentials = oauth2Credentials;
}
}
Additionally, you must use AnnotationAwareConstructor when parsing:
public class ConfigLoader {
public RootConfig load(String file) {
Yaml yaml = new Yaml(new AnnotationAwareConstructor(RootConfig.class));
InputStream inputStream = this.getClass()
.getClassLoader()
.getResourceAsStream(file);
RootConfig rootConfig = yaml.load(inputStream);
System.out.println(rootConfig);
return rootConfig;
}
}
Related
I have pojos with #JsonProperties. I use these to read JSON and parse to POJO. I am now having to post these pojos formatted as XML.
The Required XML format to successfully post looks like this (note the namespace type, xsi type formatting):
<network_objects>
<network_object xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="subnetNetworkObjectDTO">
<name>TestSubnet</name>
<display_name>TestSubnet</display_name>
<global>false</global>
<application_id>3</application_id>
<type>subnet</type>
<ip>5.207.206.0</ip>
<netmask>255.255.254.0</netmask>
</network_object>
<network_object xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="networkObjectGroupDTO">
<name>Test01Subnets</name>
<display_name>Test01Subnets</display_name>
<application_id>3</application_id>
<type>group</type>
</network_object>
</network_objects>
I pass the created Application Class (shown below) to convert to XML
ObjectMapper mapper = new XmlMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
byte[] val = mapper.writeValueAsBytes(myApp);
The output is a bit off and does not contain the xmlns and the xsi looks different. It also has 'Application' as root:
<Application>
<network_objects>
<network_object>
<network_object>
<#xsi.type>networkObjectGroupDTO</#xsi.type>
<name>name</name>
<display_name>displayName</display_name>
<application_id>3</application_id>
<type>group</type>
</network_object>
</network_object>
</network_objects>
</Application>
When I output the class to JSON, it looks as expected (No "Application" as root).
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
byte[] val = mapper.writeValueAsBytes(myApp);
{
"network_objects" : {
"network_object" : [ {
"#xsi.type" : "networkObjectGroupDTO",
"name" : "name",
"display_name" : "displayName",
"application_id" : 3,
"type" : "group"
}
}
}
What do I need to modify with my XmlMapper() or POJOs in order to get the XML formatted correctly?
Below are the POJOs used for this.
Application Class:
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"network_objects"
})
public class Application {
#JsonProperty("network_objects")
private NetworkObjects networkObjects;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("network_objects")
public NetworkObjects getNetworkObjects() {
return networkObjects;
}
#JsonProperty("network_objects")
public void setNetworkObjects(NetworkObjects networkObjects) {
this.networkObjects = networkObjects;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
NetworkObjects Class:
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"network_object"
})
public class NetworkObjects {
#JsonProperty("network_object")
private List<NetworkObject> networkObject = null;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("network_object")
public List<NetworkObject> getNetworkObject() {
return networkObject;
}
#JsonProperty("network_object")
public void setNetworkObject(List<NetworkObject> networkObject) {
this.networkObject = networkObject;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
NetworkObject Class:
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"#xsi.type",
"id",
"uid",
"name",
"display_name",
"global",
"comment",
"application_id",
"type",
"ip",
"access_allowed",
"member",
"last_ip",
"first_ip",
"netmask"
})
public class NetworkObject {
#JsonProperty("#xsi.type")
private String xsiType;
#JsonProperty("id")
private Integer id;
#JsonProperty("uid")
private String uid;
#JsonProperty("name")
private String name;
#JsonProperty("display_name")
private String displayName;
#JsonProperty("global")
private Boolean global;
#JsonProperty("comment")
private String comment;
#JsonProperty("application_id")
private Integer applicationId;
#JsonProperty("type")
private String type;
#JsonProperty("ip")
private String ip;
#JsonProperty("access_allowed")
private Boolean accessAllowed;
#JsonProperty("member")
private List<Member> member = null;
#JsonProperty("last_ip")
private String lastIp;
#JsonProperty("first_ip")
private String firstIp;
#JsonProperty("netmask")
private String netmask;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("#xsi.type")
public String getXsiType() {
return xsiType;
}
#JsonProperty("#xsi.type")
public void setXsiType(String xsiType) {
this.xsiType = xsiType;
}
#JsonProperty("id")
public Integer getId() {
return id;
}
#JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
#JsonProperty("uid")
public String getUid() {
return uid;
}
#JsonProperty("uid")
public void setUid(String uid) {
this.uid = uid;
}
#JsonProperty("name")
public String getName() {
return name;
}
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
#JsonProperty("display_name")
public String getDisplayName() {
return displayName;
}
#JsonProperty("display_name")
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
#JsonProperty("global")
public Boolean getGlobal() {
return global;
}
#JsonProperty("global")
public void setGlobal(Boolean global) {
this.global = global;
}
#JsonProperty("comment")
public String getComment() {
return comment;
}
#JsonProperty("comment")
public void setComment(String comment) {
this.comment = comment;
}
#JsonProperty("application_id")
public Integer getApplicationId() {
return applicationId;
}
#JsonProperty("application_id")
public void setApplicationId(Integer applicationId) {
this.applicationId = applicationId;
}
#JsonProperty("type")
public String getType() {
return type;
}
#JsonProperty("type")
public void setType(String type) {
this.type = type;
}
#JsonProperty("ip")
public String getIp() {
return ip;
}
#JsonProperty("ip")
public void setIp(String ip) {
this.ip = ip;
}
#JsonProperty("access_allowed")
public Boolean getAccessAllowed() {
return accessAllowed;
}
#JsonProperty("access_allowed")
public void setAccessAllowed(Boolean accessAllowed) {
this.accessAllowed = accessAllowed;
}
#JsonProperty("member")
public List<Member> getMember() {
return member;
}
#JsonProperty("member")
public void setMember(List<Member> member) {
this.member = member;
}
#JsonProperty("last_ip")
public String getLastIp() {
return lastIp;
}
#JsonProperty("last_ip")
public void setLastIp(String lastIp) {
this.lastIp = lastIp;
}
#JsonProperty("first_ip")
public String getFirstIp() {
return firstIp;
}
#JsonProperty("first_ip")
public void setFirstIp(String firstIp) {
this.firstIp = firstIp;
}
#JsonProperty("netmask")
public String getNetmask() {
return netmask;
}
#JsonProperty("netmask")
public void setNetmask(String netmask) {
this.netmask = netmask;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
I used your bean classes and json string. Almost everything is possible with the conversion, but there are some issues. I got this so far, if someone can derive the final solution it will be great.
Application.java
Not really any changes.
NetworkObject.java
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({"#xsi.type", "id", "uid", "name", "display_name", "global", "comment", "application_id", "type", "ip", "access_allowed", "member", "last_ip", "first_ip", "netmask"})
public class NetworkObject {
#JsonProperty("id")
private Integer id;
#JsonProperty("uid")
private String uid;
#JsonProperty("name")
private String name;
#JsonProperty("display_name")
private String displayName;
#JsonProperty("global")
private Boolean global;
#JsonProperty("comment")
private String comment;
#JsonProperty("application_id")
private Integer applicationId;
#JsonProperty("type")
private String type;
#JsonProperty("#xsi.type")
// CHANGE: You cannot have same element name and attribute name, so I had to change this to xtype if someone knows how to tackle this, that will be final answer
#JacksonXmlProperty(localName = "xtype", isAttribute = true, namespace = "http://www.w3.org/2001/XMLSchema-instance")
private String xsiType;
#JsonProperty("ip")
private String ip;
#JsonProperty("access_allowed")
private Boolean accessAllowed;
#JsonProperty("member")
private List<Member> member = null;
#JsonProperty("last_ip")
private String lastIp;
#JsonProperty("first_ip")
private String firstIp;
#JsonProperty("netmask")
private String netmask;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
// CHANGE: We don't really need on getter setters #JsonProperty("#xsi.type")
public String getXsiType() {
return xsiType;
}
// CHANGE: We don't really need on getter setters #JsonProperty("#xsi.type")
public void setXsiType(String xsiType) {
this.xsiType = xsiType;
}
#JsonProperty("id")
public Integer getId() {
return id;
}
#JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
#JsonProperty("uid")
public String getUid() {
return uid;
}
#JsonProperty("uid")
public void setUid(String uid) {
this.uid = uid;
}
#JsonProperty("name")
public String getName() {
return name;
}
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
#JsonProperty("display_name")
public String getDisplayName() {
return displayName;
}
#JsonProperty("display_name")
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
#JsonProperty("global")
public Boolean getGlobal() {
return global;
}
#JsonProperty("global")
public void setGlobal(Boolean global) {
this.global = global;
}
#JsonProperty("comment")
public String getComment() {
return comment;
}
#JsonProperty("comment")
public void setComment(String comment) {
this.comment = comment;
}
#JsonProperty("application_id")
public Integer getApplicationId() {
return applicationId;
}
#JsonProperty("application_id")
public void setApplicationId(Integer applicationId) {
this.applicationId = applicationId;
}
#JsonProperty("type")
public String getType() {
return type;
}
#JsonProperty("type")
public void setType(String type) {
this.type = type;
}
#JsonProperty("ip")
public String getIp() {
return ip;
}
#JsonProperty("ip")
public void setIp(String ip) {
this.ip = ip;
}
#JsonProperty("access_allowed")
public Boolean getAccessAllowed() {
return accessAllowed;
}
#JsonProperty("access_allowed")
public void setAccessAllowed(Boolean accessAllowed) {
this.accessAllowed = accessAllowed;
}
#JsonProperty("member")
public List<Member> getMember() {
return member;
}
#JsonProperty("member")
public void setMember(List<Member> member) {
this.member = member;
}
#JsonProperty("last_ip")
public String getLastIp() {
return lastIp;
}
#JsonProperty("last_ip")
public void setLastIp(String lastIp) {
this.lastIp = lastIp;
}
#JsonProperty("first_ip")
public String getFirstIp() {
return firstIp;
}
#JsonProperty("first_ip")
public void setFirstIp(String firstIp) {
this.firstIp = firstIp;
}
#JsonProperty("netmask")
public String getNetmask() {
return netmask;
}
#JsonProperty("netmask")
public void setNetmask(String netmask) {
this.netmask = netmask;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
NetworkObjects
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({"network_object"})
// CHANGE: To provide root element name
#JacksonXmlRootElement(localName = "network_objects")
public class NetworkObjects {
#JsonProperty("network_object")
#JacksonXmlElementWrapper(useWrapping = false)
// CHANGE: To ignore <network_object><network_object></network_object></network_object>
private List<NetworkObject> networkObject = null;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("network_object")
public List<NetworkObject> getNetworkObject() {
return networkObject;
}
#JsonProperty("network_object")
public void setNetworkObject(List<NetworkObject> networkObject) {
this.networkObject = networkObject;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
Main.java
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
ObjectMapper jsonOM = new ObjectMapper();
String jsomn = Files.readAllLines(Paths.get("sample.json"), StandardCharsets.US_ASCII).stream().collect(Collectors.joining(""));
Application myApp = jsonOM.readValue(jsomn, Application.class);
ObjectMapper mapper = new XmlMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
// Not writing entire object
System.out.println(mapper.writer().writeValueAsString(myApp.getNetworkObjects()));
}
OUPUT
<network_objects>
<network_object xmlns:wstxns1="http://www.w3.org/2001/XMLSchema-instance" wstxns1:xtype="networkObjectGroupDTO">
<name>name</name>
<display_name>displayName</display_name>
<application_id>3</application_id>
<type>group</type>
</network_object>
</network_objects>
You can use this:
XMLInputFactory inputFactory = XMLInputFactory.newFactory();
inputFactory.setProperty("javax.xml.stream.isNamespaceAware", false);
XmlMapper xmlMapper = new XmlMapper(inputFactory);
I am trying to use json patch to update an object using PATCH in my app.
I want to update only 2 fields in my object and they might be null before updating.
Each time I try and update, the whole object gets updated.
How do I restrict this?
I've tried multiple ways.
#PatchMapping("/bmwsales/updateweb/{id}")
public ResponseEntity<?> updateVehicleTagWeb(#PathVariable(value="id") Integer id, #RequestBody Bmwsales v) throws JsonProcessingException{
ObjectMapper objMapper=new ObjectMapper();
JsonPatchBuilder jsonPatchBuilder=Json.createPatchBuilder();
JsonPatch jsonPatch=jsonPatchBuilder.replace("/templocation",v.getTemplocation()).replace("/rfidtag", v.getRfidtag()).build();
Bmwsales vehicle=bmwService.getVin(id).orElseThrow(ResourceNotFoundException::new);
BmwsalesUpdate veh=oMapper.asInput(vehicle);
BmwsalesUpdate vehPatched=patchHelp.patch(jsonPatch, veh, BmwsalesUpdate.class);
oMapper.update(vehicle, vehPatched);
System.out.println("the patched info is: "+vehicle.getRfidtag()+vehicle.getTemplocation());
bmwService.updateVehTag(vehicle);
return new ResponseEntity<>(HttpStatus.OK);
#Override
public void updateVehTag(Bmwsales vehicle) {
bmwsalesRepository.save(vehicle);
}
Jackson config:
#Configuration
public class JacksonConfig {
#Bean
public ObjectMapper objectMapper(){
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.findAndRegisterModules();
}}
Bmwsales class
#Entity(name="bmwsales")
#Table(name="bmwsales")
public class Bmwsales implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
#Column(name="customerfirstname")
private String customerfirstname;
#Column(name="customerlastname")
private String customerlastname;
#Column(name="lastmileage")
private Integer lastmileage;
#Column(name="licensenum")
private String licensenum;
#Column(name="make")
private String make;
#Column(name="currentmileage")
private Integer currentmileage;
#Column(name="model")
private String model;
#Column(name="purchasedhere")
private String purchasedhere;
#JsonSerialize(using = JsonDateSerializer.class)
#Column(name="rfiddate")
private Timestamp rfiddate;
#Column(name="rfidtag")
private String rfidtag;
#Column(name="stocknum")
private String stocknum;
#Column(name="vehiclerole")
private String vehiclerole;
#NotBlank
#Column(name="vin")
private String vin;
#Column(name="year")
private Timestamp year;
#Column(name="vineight")
private String vineight;
#Column(name="taggingsource")
private String taggingsource;
#Column(name="vehicletype")
private String vehicletype;
#Column(name="salutation")
private String customersal;
#Column(name="customermiddlename")
private String customermiddlename;
#Column(name="suffix")
private String suffix;
#Column(name="address1")
private String address1;
#Column(name="address2")
private String address2;
#Column(name="city")
private String city;
#Column(name="state")
private String state;
#Column(name="zip")
private String zip;
#Column(name="county")
private String county;
#Column(name="homephone")
private String homephone;
#Column(name="cellphone")
private String cellphone;
#Column(name="email")
private String email;
#Column(name="cobuyersalutation")
private String cobuyersal;
#Column(name="cobuyerfirstname")
private String cobuyerfirstname;
#Column(name="cobuyermiddlename")
private String cobuyermiddlename;
#Column(name="cobuyerlastname")
private String cobuyerlastname;
#Column(name="salesperson")
private String salesperson;
#Column(name="salesperson2")
private String salesperson2;
#Column(name="purchasedheredate")
private Timestamp purchasedheredate;
#Column(name="carwashmember")
private String carwashmember;
#Column(name="serviceadvisor")
private String serviceadvisor;
#JsonSerialize(using = JsonDateSerializer2.class)
#Column(name="openrodate")
private Date openrodate;
#Column(name="closerodate")
private Timestamp closerodate;
#Column(name="openro")
private String openro;
#Column(name="snstext")
private Timestamp snstext;
#Column(name="carwashexpire")
private Timestamp carwashexpire;
#Column(name="enterrodate")
private Timestamp enterrodate;
#Column(name="servicecarwash")
private String servicecarwash;
#Column(name="templocation")
private String templocation;
public Bmwsales(String vineight){
this.vineight=vineight;
}
public static class Builder{
private Integer id;
private String rfidtag;
//#JsonSerialize(using = JsonDateSerializer.class)
private Timestamp rfiddate;
private String vin;
private String vineight;
private String templocation;
public Builder setVin(String vin) {
this.vin=vin;
return this;
}
public Builder setVineight(String vineight) {
this.vineight=vineight;
return this;
}
public Builder setRfidtag(String rfidtag) {
this.rfidtag=rfidtag;
return this;
}
public Builder setRfiddate(Timestamp rfiddate) {
this.rfiddate=rfiddate;
return this;
}
public Builder setTemplocation(String templocation) {
this.templocation=templocation;
return this;
}
/*public Builder setOpenro(String openro){
this.openro=openro;
return this;
}
public Builder setOpenrodate(Date openrodate){
this.openrodate=openrodate;
return this;
}*/
public Bmwsales build(){
Bmwsales bmwsales=new Bmwsales(vin, vineight,rfidtag,rfiddate,
templocation);
return bmwsales;
}
}
public Bmwsales(String vin, String vineight, String rfidtag, Timestamp
rfiddate, String templocation){
this.vin=vin;
this.vineight=vineight;
this.rfiddate=rfiddate;
this.rfidtag=rfidtag;
this.templocation=templocation;
}
public Bmwsales(String customersal, String customerfirstname, String
customerlastname, String customermiddlename, String suffix,
String make, Integer currentmileage, String model, String
purchasedhere, String vehiclerole, String vin, String vineight,
Timestamp year, String taggingsource, String vehicletype,
String address1, String address2, String city, String state,
String zip, String county, String homephone, String cellphone,
String email, String cobuyersal, String cobuyerfirstname,
String cobuyermiddlename, String cobuyerlastname, String
salesperson, String salesperson2, Timestamp purchasedheredate,
String carwashmember, String serviceadvisor, Date openrodate,
Timestamp closerodate, Timestamp snstext, String openro,
Timestamp carwashexpire, Timestamp enterrodate, String
servicecarwash, Timestamp rfiddate, String rfidtag, String templocation){
super();
this.customersal=customersal;
this.customerfirstname=customerfirstname;
this.customermiddlename=customermiddlename;
this.customerlastname=customerlastname;
this.suffix=suffix;
this.make=make;
this.currentmileage=currentmileage;
this.model=model;
this.purchasedhere=purchasedhere;
this.vehiclerole=vehiclerole;
this.vin=vin;
this.vineight=vineight;
this.year=year;
this.taggingsource=taggingsource;
this.vehicletype=vehicletype;
this.address1=address1;
this.address2=address2;
this.city=city;
this.state=state;
this.zip=zip;
this.county=county;
this.homephone=homephone;
this.cellphone=cellphone;
this.email=email;
this.cobuyersal=cobuyersal;
this.cobuyerfirstname=cobuyerfirstname;
this.cobuyermiddlename=cobuyermiddlename;
this.cobuyerlastname=cobuyerlastname;
this.salesperson=salesperson;
this.salesperson2=salesperson2;
this.purchasedheredate=purchasedheredate;
this.carwashmember=carwashmember;
this.serviceadvisor=serviceadvisor;
this.openrodate=openrodate;
this.closerodate=closerodate;
this.snstext=snstext;
this.openro=openro;
this.carwashexpire=carwashexpire;
this.enterrodate=enterrodate;
this.servicecarwash=servicecarwash;
this.rfiddate=rfiddate;
this.rfidtag=rfidtag;
this.templocation=templocation;
};
public Bmwsales(){
}
public void setId(Integer id) {
this.id=id;
}
public Integer getId() {
return id;
}
public void setCustomersal(String customersal) {
this.customersal=customersal;
}
public String getCustomersal() {
return customersal;
}
public void setCustomerfirstname(String customerfirstname) {
this.customerfirstname=customerfirstname;
}
public String getCustomerfirstname() {
return customerfirstname;
}
public void setCustomermiddlename(String customermiddlename) {
this.customermiddlename=customermiddlename;
}
public String getCustomermiddlename() {
return customermiddlename;
}
public void setCustomerlastname(String customerlastname) {
this.customerlastname=customerlastname;
}
public String getCustomerlastname() {
return customerlastname;
}
public void setSuffix(String suffix) {
this.suffix=suffix;
}
public String getSuffix() {
return suffix;
}
public void setMake(String make) {
this.make=make;
}
public String getMake() {
return make;
}
public void setCurrentmileage(Integer currentmileage) {
this.currentmileage=currentmileage;
}
public Integer getCurrentmileage() {
return currentmileage;
}
public void setModel(String model) {
this.model=model;
}
public String getModel() {
return model;
}
public void setPurchasedhere(String purchasedhere) {
this.purchasedhere=purchasedhere;
}
public String getPurchasedhere() {
return purchasedhere;
}
public void setVehiclerole(String vehiclerole) {
this.vehiclerole=vehiclerole;
}
public String getVehiclerole() {
return vehiclerole;
}
public void setVin(String vin) {
this.vin=vin;
}
public String getVin() {
return vin;
}
public void setVineight(String vineight) {
this.vineight=vineight;
}
public String getVineight() {
return vineight;
}
public void setYear(Timestamp year) {
this.year=year;
}
public Timestamp getYear() {
return year;
}
public void setTaggingsource(String taggingsource) {
this.taggingsource=taggingsource;
}
public String getTaggingsource() {
return taggingsource;
}
public void setVehicletype(String vehicletype) {
this.vehicletype=vehicletype;
}
public String getVehicletype() {
return vehicletype;
}
public void setAddress1(String address1) {
this.address1=address1;
}
public String getAddress1() {
return address1;
}
public void setAddress2(String address2) {
this.address2=address2;
}
public String getAddress2() {
return address2;
}
public void setCity(String city) {
this.city=city;
}
public String getCity() {
return city;
}
public void setState(String state) {
this.state=state;
}
public String getState() {
return state;
}
public void setZip(String zip) {
this.zip=zip;
}
public String getZip() {
return zip;
}
public void setCounty(String county) {
this.county=county;
}
public String getCounty() {
return county;
}
public void setHomephone(String homephone) {
this.homephone=homephone;
}
public String getHomephone() {
return homephone;
}
public void setCellphone(String cellphone) {
this.cellphone=cellphone;
}
public String getCellphone() {
return cellphone;
}
public void setEmail(String email) {
this.email=email;
}
public String getEmail() {
return email;
}
public void setCobuyersal(String cobuyersal) {
this.cobuyersal=cobuyersal;
}
public String getCobuyersal() {
return cobuyersal;
}
public void setCobuyerfirstname(String cobuyerfirstname) {
this.cobuyerfirstname=cobuyerfirstname;
}
public String getCobuyerfirstname() {
return cobuyerfirstname;
}
public void setCobuyermiddlename(String cobuyermiddlename) {
this.cobuyermiddlename=cobuyermiddlename;
}
public String getCobuyermiddlename() {
return cobuyermiddlename;
}
public void setCobuyerlastname(String cobuyerlastname) {
this.cobuyerlastname=cobuyerlastname;
}
public String getCobuyerlastname() {
return cobuyerlastname;
}
public void setSalesperson(String salesperson) {
this.salesperson=salesperson;
}
public String getSalesperson() {
return salesperson;
}
public void setSalesperson2(String salesperson2) {
this.salesperson2=salesperson2;
}
public String getSalesperson2() {
return salesperson2;
}
public void setPurchasedheredate(Timestamp purchasedheredate) {
this.purchasedheredate=purchasedheredate;
}
public Timestamp getPurchasedheredate() {
return purchasedheredate;
}
public void setCarwashmember(String carwashmember) {
this.carwashmember=carwashmember;
}
public String getCarwashmember() {
return carwashmember;
}
public void setServiceadvisor(String serviceadvisor) {
this.serviceadvisor=serviceadvisor;
}
public String getServiceadvisor() {
return serviceadvisor;
}
public void setOpenrodate(Date openrodate) {
this.openrodate=openrodate;
}
public Date getOpenrodate() {
return openrodate;
}
public void setCloserodate(Timestamp closerodate) {
this.closerodate=closerodate;
}
public Timestamp getCloserodate() {
return closerodate;
}
public void setSnstext(Timestamp snstext) {
this.snstext=snstext;
}
public Timestamp getSnstext() {
return snstext;
}
public void setOpenro(String openro) {
this.openro=openro;
}
public String getOpenro() {
return openro;
}
public void setCarwashexpire(Timestamp carwashexpire) {
this.carwashexpire=carwashexpire;
}
public Timestamp getCarwashexpire() {
return carwashexpire;
}
public void setEnterrodate(Timestamp enterrodate) {
this.enterrodate=enterrodate;
}
public Timestamp getEnterrodate() {
return enterrodate;
}
public void setServicecarwash(String servicecarwash) {
this.servicecarwash=servicecarwash;
}
public String getServicecarwash() {
return servicecarwash;
}
public void setRfiddate(Timestamp rfiddate) {
this.rfiddate=rfiddate;
}
public Timestamp getRfiddate() {
return rfiddate;
}
public void setRfidtag(String rfidtag) {
this.rfidtag=rfidtag;
}
public String getRfidtag() {
return rfidtag;
}
public void setTemplocation(String templocation) {
this.templocation=templocation;
}
public String getTemplocation() {
return templocation;
}
public static Object Builder() {
return new Bmwsales.Builder();
}
}
How do I update only these fields?
Your code is long one why are you code getters/setters/constructors from typing.it will get a long time to develop.
Then what you must add this dependency into your POM.xml file
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
And adding this dependency you can generate your getters/setters and constructors from giving simple annotations like this.do not type those in your fingers.:-)
Then your code will be more easy to readable.
#Data //this will create all getters,setters,toString
#NoArgsConstructor //this will create default constructor
#AllArgsConstructor //this will create all argivements constructor
#Entity(name="bmwsales") //name means table name
public class Bmwsales implements Serializable{
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
// like this do all your columns
#NotNull(message="customer First Name is compulsory")
#Column(name="customerfirstname")
private String customerfirstname;
//your entity mapping here etc.
}
After that, if the user does not fill the required fields that message will trigger.
And your controller class that means your endpoint calling place should use #Valid annotation to your Entity class or DTO class(you do not get DTO).
#PatchMapping("/bmwsales/updateweb/{id}")
public ResponseEntity<String> updateVehicleTagWeb(#PathVariable(value="id") Integer id, #Valid #RequestBody Bmwsales v) throws JsonProcessingException{
ObjectMapper objMapper=new ObjectMapper();
JsonPatchBuilder jsonPatchBuilder=Json.createPatchBuilder();
JsonPatch jsonPatch=jsonPatchBuilder.replace("/templocation",v.getTemplocation()).replace("/rfidtag", v.getRfidtag()).build();
Bmwsales vehicle=bmwService.getVin(id).orElseThrow(ResourceNotFoundException::new);
BmwsalesUpdate veh=oMapper.asInput(vehicle);
BmwsalesUpdate vehPatched=patchHelp.patch(jsonPatch, veh, BmwsalesUpdate.class);
oMapper.update(vehicle, vehPatched);
System.out.println("the patched info is: "+vehicle.getRfidtag()+vehicle.getTemplocation());
bmwService.updateVehTag(vehicle);
return ResponseEntity.ok("Input is valid");
For more understanding what I said to refer to this link:-
https://www.baeldung.com/spring-boot-bean-validation
I'm testing a new rest service that I've implemented. This service returns a Json through #ResponseBody. In each controller, I return the same structure:
-code
-message
-list of objects
The object that i return is a message with a list which extends to its parent class getting the code and message. These are my classes:
private class SimpleMessage{
ResponseCode code;
String message;
public ResponseCode getCode() {
return code;
}
public void setCode(ResponseCode code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void setCodeAndMessage(ResponseCode code, String message){
this.code = code;
this.message = message;
}
}
private class MessageResponse<T> extends SimpleMessage{
List<T> list;
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
If I try to return the SimpleMessage, it works fine. But the problem is relative to the MessageResponse class. If I return this class with an instance of the class User for example in the list, it runs in an infinite loop until I stop the tomcat server.
This is my controller
public #ResponseBody SimpleMessage isUserSuscribed(#RequestBody String data){
MessageResponse<User> msg = new MessageResponse<User>();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
JsonNode node;
try {
node = mapper.readTree(data);
BasicUser manager = mapper.convertValue(node.get("manager"), BasicUser.class);
User user = userService.getUserByOpenid(mapper.convertValue(node.get("openid"), String.class));
msg.setList(Lists.newArrayList(user));
} catch (JsonProcessingException e) {
log.debug(e.toString());
msg.setCodeAndMessage(ResponseCode.error, "Malformed JSON \n" + e.getMessage());
} catch (IOException e1) {
log.debug(e1.toString());
msg.setCodeAndMessage(ResponseCode.error, "Application error");
}
msg.setCodeAndMessage(ResponseCode.success, "success");
return msg;
}
The User class:
public class User extends AbstractPropertySearcher{
private String username;
private String password;
private String email;
private Boolean active;
private String metadata;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public String getMetadata() {
return getMeta().getMetadata();
}
public void setMetadata(String metadata) {
this.metadata = metadata;
}
public enum KnownUsers{
TEST, SYSTEM
}
public User() {
this.roles = new HashSet<String>();
this.profiles = new HashSet<String>();
this.geoareas = new HashSet<String>();
this.properties = new HashSet<Property>();
}
public User(String username) {
this.username = username;
this.roles = new HashSet<String>();
this.profiles = new HashSet<String>();
this.geoareas = new HashSet<String>();
this.properties = new HashSet<Property>();
}
public User(User o) {
try{
PropertyUtils.copyProperties(this, o);
}
catch (Exception e) {
e.printStackTrace();
}
}
private Set<String> roles;
private Set<String> profiles;
private Set<String> geoareas;
public Set<String> getRoles() {
return roles;
}
public void setRoles(Set<String> roles) {
this.roles = roles;
}
public Set<String> getProfiles() {
return profiles;
}
public void setProfiles(Set<String> profiles) {
this.profiles = profiles;
}
public Set<String> getGeoareas() {
return geoareas;
}
public void setGeoareas(Set<String> geoareas) {
this.geoareas = geoareas;
}
private Set<Property> properties;
private Map<String,Property> mappedProperties;
public Map<String,Property> getMappedProperties(){
if(mappedProperties==null){
mappedProperties = new HashMap<String,Property>();
for(Property prop : getProperties()){
mappedProperties.put(prop.getProperty(),prop);
}
}
return mappedProperties;
}
public Property getPropertyByName(KnownProperty knownProperty) throws PropertyNotFoundException{
return getPropertyByName(knownProperty.getPropertyName());
}
public void setProperty(Property property){
setProperty(properties, property);
}
public boolean hasRole(Role.KnownRoles role){
return roles.contains(role.name());
}
public Set<Property> getProperties() {
return properties;
}
public void setProperties(Set<Property> properties) {
this.properties = properties;
}
public String toString(){
return getUsername();
}
public int hashCode(){
return toString().hashCode();
}
public boolean equals(Object o){
if(o instanceof User){
return getUsername().equals(((User) o).getUsername());
}
return false;
}
public Property getBannerProperty() throws PropertyNotFoundException{
return AbstractPropertySearcher.getPropertyByName(getProperties(), KnownProperty.BANNER.getPropertyName());
}
private Metadata meta;
public Metadata getMeta(){
if(meta == null){
meta = new Metadata(metadata);
}
return meta;
}
public enum KnownMetaProperty{
REGISTRATION_DATE, LAST_ACCESS_DATE
}
public String getRegistrationDate(){
return getMeta().getVariable(KnownMetaProperty.REGISTRATION_DATE.name());
}
public String getLastAccessDate(){
return getMeta().getVariable(KnownMetaProperty.LAST_ACCESS_DATE.name());
}
}
This is the error in the log:
org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.StackOverflowError
Could anybody help me with this issue?
Thank you
This is register.jsp page. Here setting the countryList in dropdownlist from Action class
<s:select name="country" list="countryList" listKey="countryId" listValue="countryName" headerKey="0" headerValue="Country" label="Select a country">
Here I am getting all the list from Action;
when I submit action , I am getting key instead of value on success.jsp.
<s:property value="country"/>
Here I am getting selected key like 0,1,2 instead of country value.
My Action class
public class RegisterAction extends ActionSupport {
private List<String> communityList;
private List<Country> countryList;
private String country;
private String userName;
private String password;
private String gender;
private String about;
private String[] community;
private boolean mailingList;
public String execute() {
return SUCCESS;}
public String populate(){
communityList = new ArrayList<String>();
countryList = new ArrayList<Country>();
countryList.add(new Country(1,"India"));
countryList.add(new Country(2,"US"));
countryList.add(new Country(3,"UK"));
communityList.add("JAVA");
communityList.add(".NET");
communityList.add("SOA");
community=new String[]{"JAVA",".NET"};
mailingList = true;
return "populate";
}
public List<String> getCommunityList() {
return communityList;
}
public void setCommunityList(List<String> communityList) {
this.communityList = communityList;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
public String[] getCommunity() {
return community;
}
public void setCommunity(String[] community) {
this.community = community;
}
public boolean isMailingList() {
return mailingList;
}
public void setMailingList(boolean mailingList) {
this.mailingList = mailingList;
}
public List<Country> getCountryList() {
return countryList;
}
public void setCountryList(List<Country> countryList) {
this.countryList = countryList;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
Country.java
public class Country {
private String countryName;
private int countryId;
public Country(){}
public Country(int countryId,String countryName){
this.countryId=countryId;
this.countryName=countryName;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public int getCountryId() {
return countryId;
}
public void setCountryId(int countryId) {
this.countryId = countryId;
}
}
You can get the value from the request object.
HttpServletRequest request = (HttpServletRequest)(ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST));
Country value = (Country)request.getParameter("country");
use listKey="countryName" listValue="countryName" in this way you will receive value
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();