Spring MVC-Angularjs : How do I bind object property - json

I dont understand why I am getting this error when i try sumbit my form ,so I have an Invalid property ‘siteesTypeSite[idTypeSite]’ of bean class in my web application ,I have tried to find the solution, but still no luck.
org.springframework.beans.InvalidPropertyException: Invalid property ‘siteesTypeSite[idTypeSite]’ of bean class [model.Sites]:
Property referenced in indexed property path ‘siteesTypeSite[idTypeSite]’ is neither an array nor a List nor a Map; returned value was [2]
Is there something wrong with my mapping?
Sites.java mapping
public class Sites implements java.io.Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#JsonBackReference("site-typeSite")
#LazyCollection(LazyCollectionOption.FALSE)
#ManyToOne
#JoinColumn(name = “idTypeSite”)
private TypeSites siteesTypeSite;
Getter/setters
}
TypeSites.java mapping :
public class TypeSites implements java.io.Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="idTypeSite")
private int idTypeSite;
private String typeSite;
#LazyCollection(LazyCollectionOption.FALSE)
#JsonManagedReference("site-typeSite")
#OneToMany(mappedBy = “siteesTypeSite”,fetch = FetchType.LAZY)
// private Set<Sites> sitees= new HashSet<Sites>(0);
private List<Sites> sitees = new AutoPopulatingList<Sites>(Sites.class);
Getter/setters
}
controller class :
#RequestMapping(method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<?> create(#ModelAttribute("site") #Valid Sites site,
#ModelAttribute("typeSites") TypeSites typeSites,
#RequestParam(required = false) String searchFor,
#RequestParam(required = false,
defaultValue = DEFAULT_PAGE_DISPLAYED_TO_USER) int page,
Locale locale) {
// TypeSites test=new TypeSites("test");
// site.setSiteesTypeSite(typeSites);
// Set type = new HashSet ();
// type.add(typeSites);
siteService.save(site);
}
Angularjs code :
$scope.createObject = function (newObjectForm) {
if (!newObjectForm.$valid) {
$scope.displayValidationError = true;
return;
}
$scope.lastAction = ‘create';
var url = $scope.url;
var config = {headers: {‘Content-Type': ‘application/x-www-form-urlencoded; charset=UTF-8′}};
$scope.addSearchParametersIfNeeded(config, false);
$scope.startDialogAjaxRequest();
$scope.sites.siteesTypeSite =JSON.parse($scope.sites.siteesTypeSite);
$http.post(url, $.param($scope.sites), config)
.success(function (data) {
$scope.finishAjaxCallOnSuccess(data, “#addObjectsModal”, false);
})
.error(function(data, status, headers, config) {
$scope.handleErrorInDialogs(status);
});
};
JSP :
<select required
ng-model=”sites.siteesTypeSite”
name=”siteesTypeSite”
>
<option ng-repeat=”typesites in page.source” value=”{{typesites}}” >{{typesites.typeSite}}</option>
</select>
and i have this before submit in browser :
Object {codeOracle: "test", codeGSM: "test", area: "test", siteesTypeSite: Object}
area: "test"
codeGSM: "test"
codeOracle: "test"
siteesTypeSite: Object
idTypeSite: 2
sitees: Array[0]
typeSite: "Public"
__proto__: Object
__proto__: Object
Edite 1 :
i was trying to use MAP like this , but the same error
#LazyCollection(LazyCollectionOption.FALSE)
#JsonManagedReference("site-typeSite")
#OneToMany(mappedBy="siteesTypeSite")
#MapKey//(name="typeSite")
public Map<Integer, Sites> getSitees() {
return sitees;
}
Edite 2 :
i have edite my siteType class like bellow , but i get the same error :
#Entity
#Table(name = "TypeSites")
#JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property="idTypeSite")
public class TypeSites implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private int idTypeSite;
private String typeSite;
//private List<Sites> sitees = new AutoPopulatingList<Sites>(Sites.class);;
private Map<Integer, Sites> sitees;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="idTypeSite")
public int getIdTypeSite() {
return idTypeSite;
}
public void setIdTypeSite(int idTypeSite) {
this.idTypeSite = idTypeSite;
}
#LazyCollection(LazyCollectionOption.FALSE)
#JsonManagedReference("site-typeSite")
#OneToMany(mappedBy = "siteesTypeSite", cascade = CascadeType.ALL,fetch = FetchType.LAZY)
#MapKey(name="id")
public Map<Integer, Sites> getSitees() {
return sitees;
}
public void setSitees(Map<Integer, Sites> sitees) {
this.sitees = sitees;
}
#SuppressWarnings("unchecked")
public TypeSites() {
this.sitees = MapUtils.lazyMap(new HashMap<Integer,Object>(), new Factory() {
public Object create() {
return LazyList.decorate(new ArrayList<Sites>(),
FactoryUtils.instantiateFactory(Sites.class));
}
});
}

Related

Values of selected options in dynamic h:selectManyListbox dont change

I'm creating dynamic h:selectManyListbox(es) using c:forEach but it seems that when I select different options from the h:selectManyListbox, the value corresponding to the selected options doesn't change. Here is my code. Please help I'm new with JSF 2.
This is my xhtml section (#{item.selectedBranches} not updated when options are selected) :
<h:body>
Hi
<h:form id="hehe">
<c:forEach items="#{branchesController.dynamicListBoxBean}" var="item" >
<h3> <h:outputLabel value="#{item.category}"/> </h3>
<h:selectManyListbox size="20" style="width: 300px" value="#{item.selectedBranches}" id="#{item.category}" >
<f:selectItems value="#{item.specificBranches}" >
</f:selectItems>
</h:selectManyListbox>
</c:forEach>
</h:form>
</h:body>
This is my Controller Code :
#ManagedBean(name = "branchesController")
#RequestScoped
public class BranchesController implements Serializable {
#EJB
private entities.BranchesFacade ejbFacade;
private List<Branches> items = null;
private List<Branches> selectedItems = null;
private List<DynamicListBoxBean> dynamicListBoxBean = new ArrayList<>();
public BranchesController() {
}
private BranchesFacade getFacade() {
return ejbFacade;
}
public List<Branches> getItems() {
if (items == null) {
items = getFacade().findAll();
}
return items;
}
public List<DynamicListBoxBean> getDynamicListBoxBean() {
List<Branches> a = new ArrayList<>();
a= getFacade().findAll();
/* a.set(0, new Branches("1","Bib","Small"));
a.set(1, new Branches("2","Bob","Small"));
a.set(2, new Branches("3","jbb","Small"));*/
List<Branches> s = new ArrayList<>();
s = getFacade().findAll();
/* s.set(0, new Branches("1","Bib","Small"));
s.set(1, new Branches("2","Bob","Small"));
s.set(2, new Branches("3","jbb","Small"));*/
DynamicListBoxBean x = new DynamicListBoxBean("Small",0,a,s);
List<DynamicListBoxBean> abc = new ArrayList<DynamicListBoxBean>();
abc.add(0, x);
dynamicListBoxBean = abc;
return dynamicListBoxBean;
}
public void setDynamicListBoxBean(List<DynamicListBoxBean>
dynamicListBoxBean) {
this.dynamicListBoxBean = dynamicListBoxBean;
}
#FacesConverter(forClass = Branches.class)
public static class BranchesControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent
component, String value) {
if (value == null || value.length() == 0) {
return null;
}
BranchesController controller = (BranchesController)
facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null,
"branchesController");
return controller.getFacade().find(getKey(value));
}
java.lang.String getKey(String value) {
java.lang.String key;
key = value;
return key;
}
String getStringKey(java.lang.String value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent
component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Branches) {
Branches o = (Branches) object;
return getStringKey(o.getId());
} else {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE,
"object {0} is of type {1}; expected type: {2}", new Object[]{object,
object.getClass().getName(), Branches.class.getName()});
return null;
}
}
}
this is my Branches class :
public class Branches implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 20)
#Column(name = "ID")
private String id;
#Size(max = 20)
#Column(name = "NAME")
private String name;
#Size(max = 20)
#Column(name = "CATEGORY")
private String category;
public Branches() {
}
public Branches(String id, String name, String category) {
this.id = id;
this.name = name;
this.category = category;
}
And finally this is my DynamicListBoxBean :
public class DynamicListBoxBean {
private String category;
private int cbValue;
private List<Branches> specificBranches;
private List<Branches> selectedBranches;
public DynamicListBoxBean(String category, int cbValue, List<Branches>
specificBranches, List<Branches> selectedBranches) {
this.category = category;
this.cbValue = cbValue;
this.specificBranches = specificBranches;
this.selectedBranches = selectedBranches;
}
With gettters and setters ...
I really dont understand what's happening.. Shouldn't the item.selectedBranches points to the property in the managedbean ?

Dynamic h:selectManyListbox using p:datatable

I'm new with JSF2. and I'm trying to create dynamic h:selectManyListbox using p:dataTable but unfortunately the xhtml page is always blank, Can you help me plz :
This is my xhtml section :
<h:body>
Hi
<p:dataTable id="dataTable" value="#{branchesController.dynamicListBoxBean}" var="item">
Hi Man
#{item.category}
<h:selectManyListbox size="20" style="width: 300px" value="#{item.selectedBranches}" >
<f:selectItems value="#{item.specificBranches}">
</f:selectItems>
</h:selectManyListbox>
</p:dataTable>
</h:body>
This is my Controller Code :
#ManagedBean(name = "branchesController")
#RequestScoped
public class BranchesController implements Serializable {
#EJB
private entities.BranchesFacade ejbFacade;
private List<Branches> items = null;
private List<Branches> selectedItems = null;
private List<DynamicListBoxBean> dynamicListBoxBean = new ArrayList<>();
public BranchesController() {
}
private BranchesFacade getFacade() {
return ejbFacade;
}
public List<Branches> getItems() {
if (items == null) {
items = getFacade().findAll();
}
return items;
}
public List<DynamicListBoxBean> getDynamicListBoxBean() {
List<Branches> a = new ArrayList<>();
a= getFacade().findAll();
/* a.set(0, new Branches("1","Bib","Small"));
a.set(1, new Branches("2","Bob","Small"));
a.set(2, new Branches("3","jbb","Small"));*/
List<Branches> s = new ArrayList<>();
s = getFacade().findAll();
/* s.set(0, new Branches("1","Bib","Small"));
s.set(1, new Branches("2","Bob","Small"));
s.set(2, new Branches("3","jbb","Small"));*/
DynamicListBoxBean x = new DynamicListBoxBean("Small",0,a,s);
List<DynamicListBoxBean> abc = new ArrayList<DynamicListBoxBean>();
abc.add(0, x);
dynamicListBoxBean = abc;
return dynamicListBoxBean;
}
public void setDynamicListBoxBean(List<DynamicListBoxBean> dynamicListBoxBean) {
this.dynamicListBoxBean = dynamicListBoxBean;
}
#FacesConverter(forClass = Branches.class)
public static class BranchesControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
BranchesController controller = (BranchesController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "branchesController");
return controller.getFacade().find(getKey(value));
}
java.lang.String getKey(String value) {
java.lang.String key;
key = value;
return key;
}
String getStringKey(java.lang.String value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Branches) {
Branches o = (Branches) object;
return getStringKey(o.getId());
} else {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), Branches.class.getName()});
return null;
}
}
}
this is my Branches class :
public class Branches implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 20)
#Column(name = "ID")
private String id;
#Size(max = 20)
#Column(name = "NAME")
private String name;
#Size(max = 20)
#Column(name = "CATEGORY")
private String category;
public Branches() {
}
public Branches(String id, String name, String category) {
this.id = id;
this.name = name;
this.category = category;
}
And finally this is my DynamicListBoxBean :
public class DynamicListBoxBean {
private String category;
private int cbValue;
private List<Branches> specificBranches;
private List<Branches> selectedBranches;
public DynamicListBoxBean(String category, int cbValue, List<Branches> specificBranches, List<Branches> selectedBranches) {
this.category = category;
this.cbValue = cbValue;
this.specificBranches = specificBranches;
this.selectedBranches = selectedBranches;
}
With gettters and setters ...
Please help me with this. I'm new with JSF 2 ... and Its always giving me a blank page ... What should I do ?

How to parse 2 entities as JSON for Controller (which have 2x#RequestBody parameters)

I'm wondering is it possible to parse 2 entities as one JSON for my Controller which do have 2x#RequestBody(for each entity),first i want to check if that is possible, because i would like to have one controller with 3x#RequestBody(3 entities).
Controller looks like this :
#RequestMapping(method = RequestMethod.POST)
public ResponseEntity<KoordynatorzyPraktykEntity> addCoordinator(#RequestBody KoordynatorzyPraktykEntity koordynatorzyPraktykEntity, #RequestBody OsobyEntity osobyEntity) {
KoordynatorzyPraktykEntity addCoordinator = ikoordynatorzyPraktykService.addCoordinator(koordynatorzyPraktykEntity);
OsobyEntity addPerson = ikoordynatorzyPraktykService.addPerson(osobyEntity, koordynatorzyPraktykEntity);
if (addCoordinator !=null && addPerson !=null) {
return new ResponseEntity<KoordynatorzyPraktykEntity>(addCoordinator, HttpStatus.OK);
}
else {
return new ResponseEntity<KoordynatorzyPraktykEntity>(HttpStatus.NOT_FOUND);
}
}
Service:
#Override
public OsobyEntity addPerson(OsobyEntity osobyEntity, KoordynatorzyPraktykEntity koordynatorzyPraktykEntity) {
OsobyEntity newPerson = iosobyDAO.addPerson(osobyEntity);
newPerson.setKoordynator(koordynatorzyPraktykEntity);
int idOsoby = newPerson.getIdOsoby();
koordynatorzyPraktykEntity.setIdOsoby(idOsoby);
koordynatorzyPraktykEntity.setKoordynatorByIdOsoby(newPerson);
return newPerson;
}
Osoby(person)Entity
#Entity
#Table(name = "osoby", schema = "public", catalog = "praktykidb")
public class OsobyEntity {
private int idOsoby;
/*
some stuff
*/
private KoordynatorzyPraktykEntity koordynator;
#Id
#GeneratedValue
#Column(name = "id_osoby")
public int getIdOsoby() {
return idOsoby;
}
public void setIdOsoby(int idOsoby) {
this.idOsoby = idOsoby;
}
/*
some stuff
*/
#OneToOne(mappedBy = "koordynatorByIdOsoby", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
public KoordynatorzyPraktykEntity getKoordynator() {
return koordynator;
}
public void setKoordynator(KoordynatorzyPraktykEntity koordynator) {
this.koordynator = koordynator;
}
and Koordynatorzy(Coordinators)Entity:
#Entity
#Table(name = "koordynatorzy_praktyk", schema = "public", catalog = "praktykidb")
public class KoordynatorzyPraktykEntity {
private int idKoordynatoraPraktyk;
private int idOsoby;
private String doTestow;
private OsobyEntity koordynatorByIdOsoby;
private Collection<KoordynatorzyKierunkowiEntity> koordynatorzyByIdKierunku;
#Id
#GeneratedValue
#Column(name = "id_koordynatora_praktyk")
public int getIdKoordynatoraPraktyk() {
return idKoordynatoraPraktyk;
}
public void setIdKoordynatoraPraktyk(int idKoordynatoraPraktyk) {
this.idKoordynatoraPraktyk = idKoordynatoraPraktyk;
}
#Basic
#Column(name = "id_osoby")
public int getIdOsoby() {
return idOsoby;
}
public void setIdOsoby(int idOsoby) {
this.idOsoby = idOsoby;
/*
some stuff
*/
#JsonIgnore
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "id_osoby", referencedColumnName = "id_osoby", insertable = false , updatable = false)
public OsobyEntity getKoordynatorByIdOsoby() {
return koordynatorByIdOsoby;
}
public void setKoordynatorByIdOsoby(OsobyEntity koordynatorByIdOsoby) {
this.koordynatorByIdOsoby = koordynatorByIdOsoby;
}
#JsonIgnore
#OneToMany(mappedBy = "koordynatorzyByIdKierunku", cascade = CascadeType.ALL)
#LazyCollection(LazyCollectionOption.FALSE)
public Collection<KoordynatorzyKierunkowiEntity> getKoordynatorzyByIdKierunku() {
return koordynatorzyByIdKierunku;
}
public void setKoordynatorzyByIdKierunku(Collection<KoordynatorzyKierunkowiEntity> koordynatorzyByIdKierunku) {
this.koordynatorzyByIdKierunku = koordynatorzyByIdKierunku;
}
I know i can easilly make Person in PersonEntity and attach coordinator to this {PersonID} with #RequestMapping (value = "/{PersonID}/coordinator, method = POST (parse CoordinatorEntity as JSON and set relations for each entity), but i would like to test if something simillar (with 2xrequestBody) can work because in near future (tomorrow maybe...) i'm going to make new stuff for existing relation which looks now like this now.
[StudentEntity] [AddressEntity]
idOfStudent (PK) /--------idOfAddress (PK)
idOfAddress (FK)<-----/
idOfPerson (FK)<-----\ [PersonEntity]
\--------idOfPerson (PK)
With 2 entity it's not a problem, but with 3 i don't know what to do because when i make Student it assigns ID of Address and Person as 0, then when i want to add for example Address i want to search (em.find) student with his id, but he is also looking for rows in Address and Person Entity with idOfAddress = 0 and idOfPerson = 0. Maybe there is a way to make these IDs null when i persist Student into entity? Some other ideas maybe?
This is a wrong way, because the request body can be consumed only once, all subsequent attempts to process the body again will cause an IOException saying stream closed.
What you should do instead is build and register a custom argument resolver for your types OsobyEntity and KoordynatorzyPraktykEntity and achieve the same effect.

Excluding properties from JSON processing in Struts2

I have the following (full) entity class.
public class StateTable implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "state_id", nullable = false)
private Long stateId;
#Column(name = "state_name", length = 45)
private String stateName;
#OneToMany(mappedBy = "stateId", fetch = FetchType.LAZY)
private Set<UserTable> userTableSet;
#OneToMany(mappedBy = "stateId", fetch = FetchType.LAZY)
private Set<City> citySet;
#OneToMany(mappedBy = "stateId", fetch = FetchType.LAZY)
private Set<Inquiry> inquirySet;
#OneToMany(mappedBy = "shippingState", fetch = FetchType.LAZY)
private Set<OrderTable> orderTableSet;
#OneToMany(mappedBy = "paymentState", fetch = FetchType.LAZY)
private Set<OrderTable> orderTableSet1;
#JoinColumn(name = "country_id", referencedColumnName = "country_id")
#ManyToOne(fetch = FetchType.LAZY)
private Country countryId;
public StateTable() {
}
public StateTable(Long stateId) {
this.stateId = stateId;
}
public Long getStateId() {
return stateId;
}
public void setStateId(Long stateId) {
this.stateId = stateId;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
#XmlTransient
public Set<UserTable> getUserTableSet() {
return userTableSet;
}
public void setUserTableSet(Set<UserTable> userTableSet) {
this.userTableSet = userTableSet;
}
#XmlTransient
public Set<City> getCitySet() {
return citySet;
}
public void setCitySet(Set<City> citySet) {
this.citySet = citySet;
}
#XmlTransient
public Set<Inquiry> getInquirySet() {
return inquirySet;
}
public void setInquirySet(Set<Inquiry> inquirySet) {
this.inquirySet = inquirySet;
}
#XmlTransient
public Set<OrderTable> getOrderTableSet() {
return orderTableSet;
}
public void setOrderTableSet(Set<OrderTable> orderTableSet) {
this.orderTableSet = orderTableSet;
}
#XmlTransient
public Set<OrderTable> getOrderTableSet1() {
return orderTableSet1;
}
public void setOrderTableSet1(Set<OrderTable> orderTableSet1) {
this.orderTableSet1 = orderTableSet1;
}
public Country getCountryId() {
return countryId;
}
public void setCountryId(Country countryId) {
this.countryId = countryId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (stateId != null ? stateId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof StateTable)) {
return false;
}
StateTable other = (StateTable) object;
if ((this.stateId == null && other.stateId != null) || (this.stateId != null && !this.stateId.equals(other.stateId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "model.StateTable[ stateId=" + stateId + " ]";
}
}
I need only two properties from this class as a JSON response namely, stateId and stateName. The rest of the properties must be ignored from being processed/serialized by JSON.
I have tried to set json.excludeProperties to the json interceptor as follows.
#Namespace("/admin_side")
#ResultPath("/WEB-INF/content")
#ParentPackage(value="json-default")
public final class StateListAction extends ActionSupport implements Serializable, ValidationAware
{
#Autowired
private final transient SharableService sharableService=null;
private static final long serialVersionUID = 1L;
private Long id;
List<StateTable>stateTables=new ArrayList<StateTable>();
public StateListAction() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#JSON(name="stateTables")
public List<StateTable> getStateTables() {
return stateTables;
}
public void setStateTables(List<StateTable> stateTables) {
this.stateTables = stateTables;
}
#Action(value = "PopulateStateList",
results = {
#Result(type="json", name=ActionSupport.SUCCESS, params={"json.enableSMD", "true", "json.enableGZIP", "true", "json.excludeNullProperties", "true", "json.root", "stateTables", "json.excludeProperties", "userTableSet, citySet, inquirySet, orderTableSet, orderTableSet1, countryId", "validation.validateAnnotatedMethodOnly", "true"})})
public String populateStateList() throws Exception
{
System.out.println("countryId = "+id);
stateTables=sharableService.findStatesByCountryId(id);
return ActionSupport.SUCCESS;
}
}
The remaining properties are expected to be ignored after doing this but it doesn't seem to work. Number of SQL statements associated with all of the entity classes are generated which in turn causes other severe errors to occur like,
org.apache.struts2.json.JSONException: java.lang.IllegalAccessException: Class
org.apache.struts2.json.JSONWriter can not access a member of class
org.joda.time.tz.DateTimeZoneBuilder$PrecalculatedZone with modifiers "public"
What am I missing here? How to ignore all the properties except stateId and stateName?
I'm using Struts2-json-plugin-2.3.16.
You need to configure includeProperties in the json result. For example
#Result(type="json", params = {"contentType", "text/javascript", "includeProperties",
"stateTables\\[\\d+\\]\\.stateId,stateTables\\[\\d+\\]\\.stateName"})

JSON to POJO using Apache Camel and hibernate

Apache camel is using a route wich is listening to a specific url. the json from this url is then transformed to pojo classes and inserted in a mySQL database. Everything is working fine, except my foreign key still remains null. I'm using spring framework btw.
Here is the url where you can find the data:
https://builds.apache.org:443/job/Accumulo-1.5/api/json
Here is my routedefinition for camel
#Component
public class JenkinsConfigurationRouteBuilder extends SpringRouteBuilder {
private Logger logger = LoggerFactory.getLogger(JenkinsConfigurationRouteBuilder.class);
#Override
public void configure() throws Exception {
logger.info("Configuring route");
//Properties die hij niet vindt in de klasse negeren
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
DataFormat jenkinsConfigFormat = new JacksonDataFormat(objectMapper, JenkinsConfiguration.class);
from("timer://foo?fixedRate=true&delay=0&period=200000&repeatCount=1")
.routeId("jsonToJenkinsConfiguration")
.setHeader(Exchange.HTTP_METHOD, constant("GET"))
.to("https://builds.apache.org:443/job/Accumulo-1.5/api/json")
.convertBodyTo(String.class)
.unmarshal(jenkinsConfigFormat) //instance van JenkinsConfiguration
.log(LoggingLevel.DEBUG, "be.kdg.teamf", "Project: ${body}")
.to("hibernate:be.kdg.teamf.model.JenkinsConfiguration");
}
}
My POJO class
#Entity(name = "jenkinsConfiguration")
public class JenkinsConfiguration extends Configuration implements Serializable {
#Column
#JsonProperty("displayName")
private String name;
#JsonProperty("healthReport")
#JsonIgnore
#LazyCollection(LazyCollectionOption.FALSE)
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = ("jenkinsConfig"))
private Collection<HealthReport> healthReport;
#JsonProperty("builds")
#JsonIgnore
#LazyCollection(LazyCollectionOption.FALSE)
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = ("jenkinsConfig"))
private Collection<Build> builds;
#JsonProperty("modules")
#JsonIgnore
#LazyCollection(LazyCollectionOption.FALSE)
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = ("jenkinsConfig"))
private Collection<Module> modules;
public JenkinsConfiguration() {
}
public JenkinsConfiguration(Collection<Build> builds, Collection<HealthReport> healthReport, Collection<Module> modules, String name) {
this.builds = builds;
this.healthReport = healthReport;
this.modules = modules;
this.name = name;
}
public Collection<Build> getBuilds() {
return builds;
}
public Collection<HealthReport> getHealthReport() {
return healthReport;
}
public Collection<Module> getModules() {
return modules;
}
public String getName() {
return name;
}
public void setBuilds(Collection<Build> builds) {
this.builds = builds;
}
public void setHealthReport(Collection<HealthReport> healthReport) {
this.healthReport = healthReport;
}
public void setModules(Collection<Module> modules) {
this.modules = modules;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
Let us take the builds for instance.
As you can see, this pojo class contains a list from builds. A JenkinsConfiguration can contain more builds. One build belongs to one JenkinsConfiguration.
This is my Build class:
#XmlRootElement(name = "builds")
#Entity(name = "build")
public class Build implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int Id;
#Column
#JsonProperty("number")
private Integer number;
#Column
#JsonProperty("url")
private String url;
#JsonBackReference
#OnDelete(action = OnDeleteAction.CASCADE)
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "jenkinsConfig")
private JenkinsConfiguration jenkinsConfig;
public Build() {
}
public Build(JenkinsConfiguration jenkinsConfig, Integer number, String url) {
this.jenkinsConfig = jenkinsConfig;
this.number = number;
this.url = url;
}
public int getId() {
return Id;
}
public JenkinsConfiguration getJenkinsConfig() {
return jenkinsConfig;
}
public Integer getNumber() {
return number;
}
public String getUrl() {
return url;
}
public void setId(int id) {
Id = id;
}
public void setJenkinsConfig(JenkinsConfiguration jenkinsConfig) {
this.jenkinsConfig = jenkinsConfig;
}
public void setNumber(Integer number) {
this.number = number;
}
public void setUrl(String url) {
this.url = url;
}
}
My question: how come that my foreign key is not set for the build class? it remains null.
Doe I need to update it manually or something? If so, how do I do that in spring?
Any help would me much appreciated!
Fixed it by updating the records in my database like so:
Camel:
from("hibernate:be.kdg.teamf.model.Build?delay=1s")
.routeId("buildFkBuild")
.startupOrder(3)
.shutdownRunningTask(ShutdownRunningTask.CompleteAllTasks)
.to("bean:buildFK?method=processBuild")
.log(LoggingLevel.DEBUG, "be.kdg.teamf", "Project: ${body}")
.to("hibernate:be.kdg.teamf.model.Build");
Bean:
#Consumed
public Build processBuild(Build build) {
//updaten van foreign key
build.setJenkinsConfig(jenkinsConfiguration);
return build;
}