Relationship issue on neo4j.ogm using spring boot application - spring

In my project i am using org.neo4j.ogm with spring boot. While i am trying to create a relationship using #RelationshipEntity means it will created successfully. But it does not support multiple to one relation.
Here i am creating relationship for Blueprint to ScTaxonomy at the relationship on RELATED_TO_ScTaxonomy. And i want to add relationship properties for catalogueBlueprint class.
I mean Blueprint-(RELATED_TO_ScTaxonomy)-ScTaxonomy with catalogueBlueprint class values was saved on RELATED_TO_ScTaxonomy.
once i restart the service then i'll create a new connection means already created relations are lost and only the newly created relations only saved.
I am using the query for
package nuclei.domain;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.neo4j.ogm.annotation.Relationship;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class Blueprint extends Entity {
private String blueprint;
private String onIaas;
private String script;
private String isDeleted;
#Relationship(type = "iaaSTemplate", direction = Relationship.INCOMING)
IaaSTemplate iaaSTemplate;
#Relationship(type = "iaasParameters")
List<IaasParameters> iaasParameters;
#Relationship(type = "tasks")
List<Tasks> tasks;
#Relationship(type = "RELATED_TO_ScTaxonomy")
#JsonIgnore
public List<CatalogueBlueprint> relations;
public Blueprint() {
iaaSTemplate = new IaaSTemplate();
iaasParameters = new ArrayList<IaasParameters>();
tasks = new ArrayList<Tasks>();
relations = new ArrayList<CatalogueBlueprint>();
}
public void addRelation(ScTaxonomy scTaxonomyRelation,CatalogueBlueprint catalogueBlueprint) {
catalogueBlueprint.blueprintRelation = this;
catalogueBlueprint.scTaxonomyRelation = scTaxonomyRelation;
relations.add(catalogueBlueprint);
/* relations.setCatalogueBlueprintId(catalogueBlueprint.getCatalogueBlueprintId());
relations.setOnIaas(catalogueBlueprint.getOnIaas());
relations.setScript(catalogueBlueprint.getScript());
relations.setX_axis(catalogueBlueprint.getX_axis());
relations.setY_axis(catalogueBlueprint.getY_axis());
relations.setStep(catalogueBlueprint.getStep());
relations.setIsDeleted(catalogueBlueprint.getIsDeleted());*/
scTaxonomyRelation.relations.add(catalogueBlueprint);
}
public Blueprint(String blueprint, String onIaas, String script,
String isDeleted) {
this.blueprint = blueprint;
this.onIaas = onIaas;
this.script = script;
this.isDeleted = isDeleted;
}
public String getBlueprint() {
return blueprint;
}
public void setBlueprint(String blueprint) {
this.blueprint = blueprint;
}
public String getOnIaas() {
return onIaas;
}
public void setOnIaas(String onIaas) {
this.onIaas = onIaas;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
public String getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(String isDeleted) {
this.isDeleted = isDeleted;
}
public List<IaasParameters> getIaasParameters() {
return iaasParameters;
}
public void setIaasParameters(List<IaasParameters> iaasParameters) {
this.iaasParameters = iaasParameters;
}
public List<Tasks> getTasks() {
return tasks;
}
public void setTasks(List<Tasks> tasks) {
this.tasks = tasks;
}
public IaaSTemplate getIaaSTemplate() {
return iaaSTemplate;
}
public void setIaaSTemplate(IaaSTemplate iaaSTemplate) {
this.iaaSTemplate = iaaSTemplate;
}
public List<CatalogueBlueprint> getRelations() {
return relations;
}
public void setRelations(List<CatalogueBlueprint> relations) {
this.relations = relations;
}
}
/**
*
*/
package nuclei.domain;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.neo4j.ogm.annotation.Relationship;
/**
* #author Karthikeyan
*
*/
public class ScTaxonomy extends Entity {
private String taxName;
private String description;
private String isDeleted;
private String step;
private String serviceCatalogueStep;
private String x_axis;
private String y_axis;
#Relationship(type = "RELATED_TO_ScTaxonomy", direction = "INCOMING")
public List<CatalogueBlueprint> relations;
public ScTaxonomy() {
relations = new ArrayList<>();
}
public ScTaxonomy(String taxName, String description, String isDeleted,String step,String serviceCatalogueStep,
String x_axis,String y_axis) {
this.taxName=taxName;
this.description = description;
this.isDeleted = isDeleted;
this.step=step;
this.serviceCatalogueStep=serviceCatalogueStep;
this.x_axis=x_axis;
this.y_axis=y_axis;
}
public String getTaxName() {
return taxName;
}
public void setTaxName(String taxName) {
this.taxName = taxName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(String isDeleted) {
this.isDeleted = isDeleted;
}
public String getStep() {
return step;
}
public void setStep(String step) {
this.step = step;
}
public String getServiceCatalogueStep() {
return serviceCatalogueStep;
}
public void setServiceCatalogueStep(String serviceCatalogueStep) {
this.serviceCatalogueStep = serviceCatalogueStep;
}
public String getX_axis() {
return x_axis;
}
public void setX_axis(String x_axis) {
this.x_axis = x_axis;
}
public String getY_axis() {
return y_axis;
}
public void setY_axis(String y_axis) {
this.y_axis = y_axis;
}
public List<CatalogueBlueprint> getRelations() {
return relations;
}
public void setRelations(List<CatalogueBlueprint> relations) {
this.relations = relations;
}
}
package nuclei.domain;
import java.util.List;
import org.neo4j.ogm.annotation.EndNode;
import org.neo4j.ogm.annotation.RelationshipEntity;
import org.neo4j.ogm.annotation.StartNode;
#RelationshipEntity(type="catalogueBlueprint")
public class CatalogueBlueprint extends Entity {
private long catalogueBlueprintId;
private String onIaas;
private String script;
private String x_axis;
private String y_axis;
private String step;
private String isDeleted;
#StartNode
public Blueprint blueprintRelation;
#EndNode
public ScTaxonomy scTaxonomyRelation;
public CatalogueBlueprint() {
}
public CatalogueBlueprint(ScTaxonomy to,Blueprint from, String onIaas, String script,long catalogueBlueprintId,
String isDeleted,String x_axis,String y_axis,String step) {
this.scTaxonomyRelation=to;
this.blueprintRelation=from;
this.onIaas = onIaas;
this.script = script;
this.isDeleted = isDeleted;
this.x_axis=x_axis;
this.y_axis=y_axis;
this.step=step;
this.catalogueBlueprintId=catalogueBlueprintId;
}
public long getCatalogueBlueprintId() {
return catalogueBlueprintId;
}
public void setCatalogueBlueprintId(long catalogueBlueprintId) {
this.catalogueBlueprintId = catalogueBlueprintId;
}
public String getOnIaas() {
return onIaas;
}
public void setOnIaas(String onIaas) {
this.onIaas = onIaas;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
public String getX_axis() {
return x_axis;
}
public void setX_axis(String x_axis) {
this.x_axis = x_axis;
}
public String getY_axis() {
return y_axis;
}
public void setY_axis(String y_axis) {
this.y_axis = y_axis;
}
public String getStep() {
return step;
}
public void setStep(String step) {
this.step = step;
}
public String getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(String isDeleted) {
this.isDeleted = isDeleted;
}
public ScTaxonomy getScTaxonomyRelation() {
return scTaxonomyRelation;
}
public void setScTaxonomyRelation(ScTaxonomy scTaxonomyRelation) {
this.scTaxonomyRelation = scTaxonomyRelation;
}
public Blueprint getBlueprintRelation() {
return blueprintRelation;
}
public void setBlueprintRelation(Blueprint blueprintRelation) {
this.blueprintRelation = blueprintRelation;
}
}
/**
*
*/
package nuclei.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nuclei.domain.CatalogueBlueprint;
import nuclei.domain.IaaSTemplate;
import nuclei.domain.IaasParameters;
import nuclei.domain.ScTaxonomy;
import nuclei.domain.Tasks;
import nuclei.domain.Blueprint;
import nuclei.response.BlueprintMessage;
import nuclei.response.BlueprintsMessage;
import nuclei.response.CatalogueBlueprintMessage;
import nuclei.response.ResponseStatus;
import nuclei.response.ResponseStatusCode;
import nuclei.service.CatalogueBlueprintService;
import nuclei.service.MainService;
import nuclei.service.BlueprintService;
import nuclei.service.ScTaxonomyService;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.sun.jersey.multipart.FormDataParam;
/**
* #author Karthikeyan
*
*/
// #RestController
#Controller
public class BlueprintController extends MainController<Blueprint> {
#Autowired
private CatalogueBlueprintService catalogueBlueprintService;
#Autowired
private ScTaxonomyService scTaxonomyService;
#Autowired
private BlueprintService blueprintService;
//create scTaxonomy relation
#RequestMapping(value = "/createScTaxonomyRelation", method = RequestMethod.POST)
public #ResponseBody BlueprintMessage relationTest(
#FormDataParam("ScTaxonomyId") String ScTaxonomyId,
#FormDataParam("blueprintId") String blueprintId,
#FormDataParam("catalogueBlueprintId") String catalogueBlueprintId,
#FormDataParam("onIaas") String onIaas,
#FormDataParam("script") String script,
#FormDataParam("step") String step,
#FormDataParam("x_axis") String x_axis,
#FormDataParam("y_axis") String y_axis,
final HttpServletResponse response) {
ResponseStatus status = null;
Long blueptId = Long.parseLong(blueprintId);
Long taxonomyId = Long.parseLong(ScTaxonomyId);
List<CatalogueBlueprint> catalogueBPList = new ArrayList<CatalogueBlueprint>();
CatalogueBlueprint catalogueBP=new CatalogueBlueprint();
Blueprint blueprint=null;
ScTaxonomy taxonomy = null;
try {
Long catalogueID=Long.parseLong(catalogueBlueprintId);
taxonomy = scTaxonomyService.find(taxonomyId);
blueprint=blueprintService.find(blueptId);
catalogueBP.setBlueprintRelation(blueprint);
catalogueBP.setScTaxonomyRelation(taxonomy);
catalogueBP.setOnIaas(onIaas);
catalogueBP.setCatalogueBlueprintId(catalogueID);
catalogueBP.setScript(script);
catalogueBP.setStep(step);
catalogueBP.setX_axis(x_axis);
catalogueBP.setY_axis(y_axis);
catalogueBP.setIsDeleted("0");
catalogueBPList.add(catalogueBP);
blueprint.addRelation(taxonomy, catalogueBP);
super.create(blueprint);
//super.update(blueptId, blueprint);
status = new ResponseStatus(ResponseStatusCode.STATUS_OK, "SUCCESS");
} catch (Exception e) {
e.printStackTrace();
}
return new BlueprintMessage(status, blueprint);
}
#Override
public MainService<Blueprint> getService() {
return blueprintService;
}
}

I am removed all the dependencies and add updated versions for all the dependency then the error was not showing and the application was running successfully.

Related

#OneToOne(cascade = {CascadeType.ALL}) problem

I have a problem with my code. I do a little CarRent webservice and when i try to assign Errand to the car, errand which i want to assign is add to list of errands...
this is controller of errand
package com.RentCar.Rent_A_car.domain.Controllers;
import com.RentCar.Rent_A_car.domain.Car;
import com.RentCar.Rent_A_car.domain.Errand;
import com.RentCar.Rent_A_car.domain.Services.CarService;
import com.RentCar.Rent_A_car.domain.Services.ErrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
#Controller
public class ErrandController {
#Autowired
CarService carService;
#Autowired
ErrandService errandService;
#RequestMapping("/assignErrand")
public String assignQuest(#RequestParam("plate") String plate, Model model){
Car car = carService.getCar(plate);
List<Errand> errandList = errandService.getAllCurrentErrands();
model.addAttribute("car",car);
model.addAttribute("errands",errandList);;
return "assignErrand";
}
#RequestMapping(value = "/assignErrand", method = RequestMethod.POST)
public String assignQuest(Car car){
carService.updateCar(car);
System.out.println("assignquest");
return "redirect:/cars";
}
These are my repositories
#Repository
public class CarsRepository {
// class to do CRUD operation on cars and errands
Map<String, Car> CarList = new HashMap<>();
#PersistenceContext
private EntityManager em;
#Transactional
public void AddCar (String mark, String plate, int mileage){
Car newCar = new Car(mark, plate, mileage);
em.persist(newCar);
}
//pobiera aktualne id i dodaje do mapy
#Transactional
public void AddCar(Car car) {
em.persist(car);
}
// dla każdego "powyzej" usuniętego trzeba zmniejszyć id o 1 ; pętla o dlugosci pozostałych aut id--; KONIECZNE FINALNIE, do budowy nie
#Transactional
public void DellateCar(String plate){
Car c = em.find(Car.class, plate);
em.remove(c);
}
public Car getCar(String plate){
Car car = em.createQuery("from Car c where c.plate=:plate", Car.class)
.setParameter("plate", plate).getSingleResult();
return car;
}
public Collection<Car> getAllCars() {
return em.createQuery("from Car",Car.class).getResultList();
}
#Transactional
public void updateCar(Car car) {
em.merge(car);
}
// public String getPlate() {
// if (CarList.isEmpty()) {
// return "Car list is empty";
// } else {
// return (String)CarList.keySet();
// }
// }
// #PostConstruct
// public void build() {
// AddCar("BMW","DW",100000);
// AddCar("Opel","DTR",100043);
// AddCar("Toyota","WB",1012300);
// AddCar("Audi","DST",102340);
//
// }
#Override
public String toString() {
return "CarsRepository{" +
"CarList=" +
'}' + "\n";
}
}
Nr
#Repository
public class ErrandRepository {
#PersistenceContext
private EntityManager ee;
List<Errand> ErrandList = new ArrayList<>();
#Transactional
public void createErrand(String description) {
Errand newErrand = new Errand(description);
ee.persist(newErrand);
System.out.println(newErrand);
}
public void createErrand(Errand errand){ErrandList.add(errand);}
public List<Errand> getAll () {
return ee.createQuery("from Errand", Errand.class).getResultList();
}
public void delateErrand(Errand errand) {
ee.remove(errand);
}
#Transactional
public void delateErrand(int x) {
ErrandList.remove(x);
}
public Errand getErrandId(Integer x){
return ee.find(Errand.class, x );
}
#PostConstruct
#Transactional
public void init(){
Errand e1 = new Errand("zlecenie na wrocław");
Errand e2 = new Errand("zlecenie na wasdw");
Errand e3 = new Errand("zlecenie na wfgasfdław");
}
#Override
public String toString() {
return "ErrandRepository{" +
"ErrandList=" + ErrandList +
'}';
}
}
this is a part of CarService
public void updateCar(Car car) {
carsRepository.updateCar(car);
System.out.println("tu sie wywołuje updatecar");
}
i don't know what is a problem... can you help me ?
edit, i add car and errand class
package com.RentCar.Rent_A_car.domain;
import javax.persistence.*;
import javax.persistence.Entity;
#Entity
public class Car {
// #Id
// #GeneratedValue(strategy = GenerationType.AUTO)
// public int id;
String mark;
#Id
String plate;
int mileage;
#OneToOne(cascade = CascadeType.ALL)
public Errand errand;
public Car() { }
public Car(String mark, String plate, int mileage) {
this.mark = mark;
this.plate = plate;
this.mileage = mileage;
}
public void setErrand(Errand errand) {
this.errand = errand;
}
public String getMark() {
return mark;
}
public void setMark(String mark) {
this.mark = mark;
}
public String getPlate() {
return plate;
}
public void setPlate(String plate) {
this.plate = plate;
}
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
public Errand getErrand() {
return errand;
}enter code here
And errand class
package com.RentCar.Rent_A_car.domain;
import net.bytebuddy.dynamic.loading.InjectionClassLoader;
import javax.persistence.*;
import javax.persistence.Entity;
#Entity
public class Errand {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public int Id;
public String description;
public Errand() {
}
public Errand(String description) {
this.description = description;
}
#Override
public String toString() {
return description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
I'm not quite sure about what is the actual problem. But anyway, I can make you some recommendations:
use plural nouns for REST uris, like:
#GetMapping("cars")
#GetMapping("errands")
and so on. Not verbs, like: assignErrand
If you split Repositories and Services, do not put login in repos, like
#Transactional
public void createErrand(String description) {
Errand newErrand = new Errand(description);
ee.persist(newErrand);
System.out.println(newErrand);
}
In the repos you should do just the persistence job. Leave the logic to the service
To add errands, I would go with something like this:
#PostMapping("/cars/{carId}/errands")
public Car addErranr(#PathVariable int carId, #RequestBody Errand errand){
Car car = this.carService.findById(carId);
car.getErrands().add(errand);
return this.carService.save(car);
}

HATEOAS PagedModel deserialization problems in Spring Webflux

I'm trying to test a Reactive Controller in Spring Boot but I cannot deserialize the returned object even if the received byte stream is OK, as shown in the following code...
#Test
public void testListTemp(#Autowired HypermediaWebTestClientConfigurer configurer) {
Page<T> page = new PageImpl<T>(Arrays.asList(getEntity()), PageRequest.of(0, 7), 1);
when(getRepository().findAll(any(SearchQuery.class), any(Pageable.class))).thenReturn(Mono.just(page));
//#formatter:off
WebTestClient
.bindToController(getController())
.argumentResolvers((argsConfigurer) -> {
Integer MAX_PAGE_SIZE = 100;
ReactivePageableHandlerMethodArgumentResolver pageableResolver = new ReactivePageableHandlerMethodArgumentResolver();
pageableResolver.setMaxPageSize(MAX_PAGE_SIZE);
pageableResolver.setFallbackPageable(SearchQuery.getDefaultPageable());
argsConfigurer.addCustomResolver(pageableResolver);
}).build()
.mutateWith(configurer)
.get()
.uri(getBaseUri()+"/")
.accept(MediaTypes.HAL_JSON)
.exchange()
.expectBody(String.class)
.consumeWith(result -> {
String model = result.getResponseBody();
System.err.println("model: " + model);
});
//#formatter:on
}
... where model:
{
"links":[
{
"rel":"self",
"href":"/test/exampleRoot/example/?includedDeleted=false&langCode=en-US&page=0&size=7",
"title":"Misma página"
},
{
"rel":"first",
"href":"/test/exampleRoot/example/?includedDeleted=false&langCode=en-US&page=0&size=7",
"title":"Primera página"
},
{
"rel":"prev",
"href":"/test/exampleRoot/example/?includedDeleted=false&langCode=en-US&page=0&size=7",
"title":"Página previa"
},
{
"rel":"next",
"href":"/test/exampleRoot/example/?includedDeleted=false&langCode=en-US&page=0&size=7",
"title":"Siguiente página"
},
{
"rel":"last",
"href":"/test/exampleRoot/example/?includedDeleted=false&langCode=en-US&page=0&size=7",
"title":"Última página"
},
{
"rel":"page-1",
"href":"/test/exampleRoot/example/?includedDeleted=false&langCode=en-US&page=0&size=7",
"title":"1"
},
{
"rel":"create",
"href":"/test/exampleRoot/example/?langCode=en-US"
}
],
"content": [
{
"createdBy":null,
"createdDate":null,
"lastModifiedBy":null,
"lastModifiedDate":null,
"deletedBy":null,
"deletedDate":null,
"businessId":2,
"field01":"FieldE2_01",
"field02":2,
"links":[
{
"rel":"self",
"href":"/test/exampleRoot/example/2?langCode=en-US&includeDeleted=false"
},
{
"rel":"all",
"href":"/test/exampleRoot/example/"
},
{
"rel":"delete",
"href":"/test/exampleRoot/example/2"
},
{
"rel":"update",
"href":"/test/exampleRoot/example/2?langCode=en-US"
}]
}],
"page":
{
"size":7,
"totalElements":1,
"totalPages":1,
"number":0
}
}
But doesn't work in the following code:
#Test
public void testListTemp(#Autowired HypermediaWebTestClientConfigurer configurer) {
Page<T> page = new PageImpl<T>(Arrays.asList(getEntity()), PageRequest.of(0, 7), 1);
when(getRepository().findAll(any(SearchQuery.class), any(Pageable.class))).thenReturn(Mono.just(page));
WebTestClient
.bindToController(getController())
.argumentResolvers((argsConfigurer) -> {
Integer MAX_PAGE_SIZE = 100;
ReactivePageableHandlerMethodArgumentResolver pageableResolver = new ReactivePageableHandlerMethodArgumentResolver();
pageableResolver.setMaxPageSize(MAX_PAGE_SIZE);
pageableResolver.setFallbackPageable(SearchQuery.getDefaultPageable());
argsConfigurer.addCustomResolver(pageableResolver);
}).build()
.mutateWith(configurer)
.get()
.uri(getBaseUri()+"/")
.accept(MediaTypes.HAL_JSON)
.exchange()
.expectBody(new TypeReferences.PagedModelType<ExampleDto>() {})
.consumeWith(result -> {
PagedModel<ExampleDto> model = result.getResponseBody();
System.err.println("model: " + model);
});
//#formatter:on
}
Where the returned object is:
PagedResource { content: [], metadata: Metadata { number: 0, total pages: 1, total elements: 1, size: 7 }, links: }
So no content nor links have been deserialized.
As for your information, here you have the ExampleDto class, and the root of the hierarchy
package net.crezco.api.example;
import javax.validation.constraints.Positive;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import net.crezco.api.CzcDto;
#Getter
#Setter
#NoArgsConstructor
#JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
public class ExampleDto extends CzcDto<ExampleDto> {
#Size(max = 20)
private String field01;
#Positive
private Integer field02;
}
And the root of the hierarchy:
package net.crezco.api;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.persistence.Transient;
import javax.validation.constraints.Null;
import javax.validation.constraints.Positive;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.hateoas.RepresentationModel;
import org.springframework.util.ReflectionUtils;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.crezco.validation.onCreate;
import net.crezco.validation.onUpdate;
#JsonIgnoreProperties(ignoreUnknown = true)
public abstract class CzcDto<T extends RepresentationModel<? extends T>> extends RepresentationModel<T> {
#Transient
#JsonIgnore
private final List<String> reserved = Arrays.asList("reserved", "id", "version", "createdBy", "createdDate", "lastModifiedBy", "lastModifiedDate", "deletedBy", "deletedDate", "_log");
/**
* Created by
*/
#JsonProperty
private String createdBy;
/**
* Created date
*/
#JsonProperty
private Date createdDate;
/**
* Last modified by
*/
#JsonProperty
private String lastModifiedBy;
/**
* Last modified date
*/
#JsonProperty
private Date lastModifiedDate;
/**
* Deleted by
*/
#JsonProperty
private String deletedBy;
/**
* Deleted date
*/
#JsonProperty
private Date deletedDate;
/**
* ID of the entity
*/
#Null(groups = onCreate.class)
#Positive(groups = onUpdate.class)
#JsonProperty
private Long businessId;
public CzcDto() {
super();
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public Date getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Date lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
public String getDeletedBy() {
return deletedBy;
}
public void setDeletedBy(String deletedBy) {
this.deletedBy = deletedBy;
}
public Date getDeletedDate() {
return deletedDate;
}
public void setDeletedDate(Date deletedDate) {
this.deletedDate = deletedDate;
}
public Long getBusinessId() {
return businessId;
}
public void setBusinessId(Long businessId) {
this.businessId = businessId;
}
/************************************
*
* UTILITY NETHODS
*
************************************/
#Override
public String toString() {
return ReflectionToStringBuilder.toStringExclude(this, "reserved", "id", "version", "createdBy", "createdDate", "lastModifiedBy", "lastModifiedDate", "deletedBy", "deletedDate", "_log");
}
#Override
public int hashCode() {
HashCodeBuilder hcb = new HashCodeBuilder(17, 37);
//#formatter:off
FieldUtils.getAllFieldsList(getClass()).stream()
.forEach(field -> {
if (!reserved.contains(field.getName()))
hcb.append(field);
});
//#formatter:on
return hcb.build();
}
#Override
public boolean equals(Object that) {
if (that == this)
return true;
if (!that.getClass().isInstance(this))
return false;
EqualsBuilder eb = new EqualsBuilder();
//#formatter:off
FieldUtils.getAllFieldsList(getClass()).stream()
.forEach(field -> {
field.setAccessible(true);
if (!reserved.contains(field.getName())) {
eb.append(ReflectionUtils.getField(field, this), ReflectionUtils.getField(field, that));
}
});
//#formatter:on
return eb.isEquals();
}
}
Had a similar problem this is what fixed it for me:
spring.hateoas:
use-hal-as-default-json-media-type: false

methods in an ejb session bean for an entity dont work in a spring MVC project

I created a maven entreprise application project, in the ejb module i put my entities in a package and i generated my session beans in an other package and i deployed my ejb module in glassfish,in the web module i added dependencies of spring and I created a controller that search the session bean and call the methode find all() but it doesnt get my objects stored in database, what should i do?
Category entity
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.entities;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author DELL
*/
#Entity
#Table(name = "categorie")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Categorie.findAll", query = "SELECT c FROM Categorie c"),
#NamedQuery(name = "Categorie.findByIdCategorie", query = "SELECT c FROM Categorie c WHERE c.idCategorie = :idCategorie"),
#NamedQuery(name = "Categorie.findByDescription", query = "SELECT c FROM Categorie c WHERE c.description = :description"),
#NamedQuery(name = "Categorie.findByName", query = "SELECT c FROM Categorie c WHERE c.name = :name"),
#NamedQuery(name = "Categorie.findByNomPhoto", query = "SELECT c FROM Categorie c WHERE c.nomPhoto = :nomPhoto")})
public class Categorie implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idCategorie")
private Integer idCategorie;
#Size(max = 255)
#Column(name = "description")
private String description;
#Size(max = 20)
#Column(name = "name")
private String name;
#Size(max = 255)
#Column(name = "nomPhoto")
private String nomPhoto;
#Lob
#Column(name = "photo")
private byte[] photo;
#OneToMany(mappedBy = "idCategorie")
private List<Produit> produitList;
public Categorie() {
}
public Categorie(Integer idCategorie) {
this.idCategorie = idCategorie;
}
public Integer getIdCategorie() {
return idCategorie;
}
public void setIdCategorie(Integer idCategorie) {
this.idCategorie = idCategorie;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNomPhoto() {
return nomPhoto;
}
public void setNomPhoto(String nomPhoto) {
this.nomPhoto = nomPhoto;
}
public byte[] getPhoto() {
return photo;
}
public void setPhoto(byte[] photo) {
this.photo = photo;
}
#XmlTransient
public List<Produit> getProduitList() {
return produitList;
}
public void setProduitList(List<Produit> produitList) {
this.produitList = produitList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idCategorie != null ? idCategorie.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 Categorie)) {
return false;
}
Categorie other = (Categorie) object;
if ((this.idCategorie == null && other.idCategorie != null) || (this.idCategorie != null && !this.idCategorie.equals(other.idCategorie))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.mycompany.entities.Categorie[ idCategorie=" + idCategorie + " ]";
}
}
AbstractFacade
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dao;
import java.util.List;
import javax.persistence.EntityManager;
/**
*
* #author DELL
*/
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
CategorieFacade
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dao;
import com.mycompany.entities.Categorie;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* #author DELL
*/
#Stateless
public class CategorieFacade extends AbstractFacade<Categorie> implements CategorieFacadeLocal {
#PersistenceContext(unitName = "com.mycompany_ProjetCommerce-ejb_ejb_1.0-SNAPSHOTPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public CategorieFacade() {
super(Categorie.class);
}
}
CategorieFacadeLocal
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dao;
import com.mycompany.entities.Categorie;
import java.util.List;
import javax.ejb.Local;
/**
*
* #author DELL
*/
#Local
public interface CategorieFacadeLocal {
void create(Categorie categorie);
void edit(Categorie categorie);
void remove(Categorie categorie);
Categorie find(Object id);
List<Categorie> findAll();
List<Categorie> findRange(int[] range);
int count();
}
CategorieController
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.controlleur;
import com.mycompany.dao.CategorieFacadeLocal;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.springframework.stereotype.*;
import org.springframework.ui.*;
import org.springframework.web.bind.annotation.*;
#Controller
#RequestMapping("categorie")
public class CategorieController {
CategorieFacadeLocal categorieFacade = lookupCategorieFacadeLocal();
#RequestMapping(method = RequestMethod.GET)
public String index(ModelMap modelmap){
modelmap.put("listeCategorie", categorieFacade.findAll());
return "index";
}
private CategorieFacadeLocal lookupCategorieFacadeLocal() {
try {
Context c = new InitialContext();
return (CategorieFacadeLocal) c.lookup("java:global/com.mycompany_ProjetCommerce-ear_ear_1.0-SNAPSHOT/com.mycompany_ProjetCommerce-ejb_ejb_1.0-SNAPSHOT/CategorieFacade!com.mycompany.dao.CategorieFacadeLocal");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
}

form:select does not set the selected value

Basically I need a CRUD application for payments. Each payment is assigned to one account.
My jsp page shows the correct list of "account" objects but it does not set the selected account.
Question: How can I achieve a dropdown box with the assigned account pre-selected?
Question: The assignment (account to payment) works, but only with the below code in my PaymentDaoImpl.java (marked as workaround). Why is this the case?
PaymentDaoImpl.java
..
#Override
#Transactional
public int insertRow(Payment obj) {
// Session session = HibernateUtil.getSessionFactory().openSession();
Session session = sessionFactory.openSession();
// !!!! workaround?? If I don't do this, account won't be assigned
int accountId = obj.getAccount().getId();
Account account = (Account) session.get(Account.class, accountId);
obj.setAccount(account);
Transaction tx = session.beginTransaction();
session.saveOrUpdate(obj);
tx.commit();
Serializable id = session.getIdentifier(obj);
session.close();
return (Integer) id;
}
..
jsp:
<form:select path="account.id" >
<form:option value="-1" label="Select Account" />
<form:options items="${accountList}" itemValue="id" itemLabel="iban" />
</form:select>
Domain Account.java:
package com.beingjavaguys.domain;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.*;
import org.springframework.beans.factory.annotation.Autowired;
#Entity
public class Account {
#Id
#GeneratedValue
private int id;
private String iban;
private String bank;
private String beschreibung;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIban() {
return iban;
}
public void setIban(String iban) {
this.iban = iban;
}
public String getBank() {
return bank;
}
public void setBank(String bank) {
this.bank = bank;
}
public String getBeschreibung() {
return beschreibung;
}
public void setBeschreibung(String beschreibung) {
this.beschreibung = beschreibung;
}
}
Domain Payment
package com.beingjavaguys.domain;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.springframework.beans.factory.annotation.Autowired;
#Entity
public class Payment {
private int id;
private Account account;
private float amount;
private String text;
private String comment;
#Id
#GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#ManyToOne(cascade = CascadeType.ALL, targetEntity = Account.class, fetch=FetchType.EAGER)
#JoinColumn(name="fk_account")
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
PaymentController.java
package com.beingjavaguys.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.beingjavaguys.domain.Payment;
import com.beingjavaguys.services.AccountService;
import com.beingjavaguys.services.PaymentService;
#Controller
#RequestMapping("/payment")
public class PaymentController {
#Autowired
PaymentService dataService;
#Autowired
AccountService accountService;
#RequestMapping("form")
public ModelAndView getForm(#ModelAttribute Payment obj) {
ModelAndView mav = new ModelAndView("payment/form");
mav.addObject("accountList", accountService.getList());
return mav;
}
#RequestMapping("insert")
public ModelAndView insert(#ModelAttribute Payment obj) {
dataService.insertRow(obj);
return new ModelAndView("redirect:list");
}
#RequestMapping("list")
public ModelAndView getList() {
List objList = dataService.getList();
return new ModelAndView("payment/list","objList",objList);
}
#RequestMapping("delete")
public ModelAndView deleteUser(#RequestParam int id) {
dataService.deleteRow(id);
return new ModelAndView("redirect:list");
}
#RequestMapping("edit")
public ModelAndView editUser(#RequestParam int id,#ModelAttribute Payment obj) {
ModelAndView mav = new ModelAndView("payment/form");
Payment paymentObj = dataService.getRowById(id);
mav.addObject("accountList", accountService.getList());
mav.addObject("paymentObj", paymentObj);
return mav;
}
#RequestMapping("update")
public ModelAndView updateUser(#ModelAttribute Payment obj) {
dataService.updateRow(obj);
return new ModelAndView("redirect:list");
}
}
Can you have a look on my implementation of the AccountEditor? I need the AccountService to lookup the account, or not? However, I don't get the service instantiated here..
public class AccountEditor extends PropertyEditorSupport {
#Autowired
AccountService dataService; // == null ??
#Override
public void setAsText(String text) {
Account account = lookupAccount(text); // lookup account by accountId
// text
setValue(account);
}
private Account lookupAccount(String text) {
int id = Integer.parseInt(text);
return dataService.getRowById(id);
}
}
What you need is a PropertyEditor implementation to convert from a String accountId to an Account object. Then in your jsp you use the path form:select path="account" instead of form:select path="account.id"
Implement a PropertyEditor as follows
public class AccountEditor extends PropertyEditorSupport{
#Override
public void setAsText(String text){
Account account = lookupAccount(text); //lookup account by accountId text
setValue(account);
}
}
Then register your AccountEditor in your controller
#InitBinder
public void initBinder(WebDataBinder binder){
binder.registerCustomEditor(Account.class , new AccountEditor());
}
With the above changes you wont need your workaround. Your solution is only setting the id property of the account and not the whole object

Spring JPA annotation based web app

I am have JSON message as request object coming into Controller.
I am trying to map the object to model class in the Controller class but unable to do so.
Can anyone help me with the procedure.
package com.firm.trayportal.contoller;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.firm.trayportal.jparepository.trayMoveRepository;
import com.firm.trayportal.jparepository.LocationRepository;
import com.firm.trayportal.jparepository.StopoffRepository;
import com.firm.trayportal.model.trayMove;
import com.firm.trayportal.model.Location;
import com.firm.trayportal.model.Stopoff;
import com.firm.trayportal.service.trayMoveService;
#RestController
public class trayPortalquoteController {
/* #Autowired
JdbcTemplate template;*/
private trayMove trayMove;
private Location location;
private Stopoff stopoff;
// Service Layer
private trayMoveService trayMoveService;
private static final Logger logger = Logger
.getLogger(trayPortalquoteController.class);
#RequestMapping(value = "/quote", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE} )
public ThumbsUp getActivetrayOrder(HttpServletRequest request, #RequestBody trayquoteRto rto) {
logger.debug("Start processing");
if (rto != null) {
logger.debug(String.format("Driver: %s/Load Number: %s/Stop %s",
rto.getDriver(), rto.getLn(), rto.getStops() != null
&& rto.getStops().get(0) != null ? rto.getStops()
.get(0).getStop() : "?"));
/*
* Querying String insertSql =
* "insert into tray_move (move_type, carrier_id, ln) values(?,?,?)"
* ;
*
* Object[] params = new Object[] {rto.getType(), rto.getDriver(),
* rto.getLn()}; // define SQL types of the arguments int[] types =
* new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR};
*/
// execute insert query to insert the data
// return number of row / rows processed by the executed query
try {
// int row = template.update(insertSql, params, types);
trayMove trayMove = new trayMove();
trayMove = savetrayInfo(rto);
// trayMoveService.populate(trayMove); // return type ?
// trayMove row = trayMoveRepo.saveAndFlush(trayMove);
// logger.debug(row + " row inserted.");
} catch (Exception _ex) {
logger.debug("Exception executing sql query:( Message: "
+ _ex.getMessage());
logger.debug("Exception executing sql query:( Message: "
+ _ex.getStackTrace());
}
} else {
logger.debug("quote RTO is NULL");
}
return new ThumbsUp();
}
private Stopoff saveStopOff(trayquoteRto rto) {
// TODO Auto-generated method stub
return null;
}
private Location saveLocationInfo(trayquoteRto rto) {
// TODO Auto-generated method stub
return null;
}
public trayMove savetrayInfo(trayquoteRto rto) {
System.out.println("In savetrayInfo method");
//trayMove.setMoveId(100005);
trayMove.setMoveType("IPU");
System.out.println("In savetrayInfo MoveType");
System.out.println("setMoveType");
trayMove.setCarrierId(rto.getDriver());
trayMove.setLn(rto.getLn());
// TODO:rto.getName(); ??
trayMove.setShippersno(rto.getShippersno());
return trayMove;
}
public Location saveLocInfo(trayquoteRto rto) {
// location.set
// location.setAddress1(address1);
return location;
}
}
/*
* create table tray_move ( move_type varchar(16), carrier_id varchar(32), ln
* varchar(32) );
*/
class trayquoteRto {
private String type;
private String driver;
private String ln;
private String shippersno;
private String oramplocation;
private String orampadd1;
private String orampadd2;
private String orampphone;
private String orampstate;
private String orampzip;
private String dramplocation;
private String drampadd1;
private String drampadd2;
private String drampphone;
private String drampstate;
private String drampzip;
private List<Stops> stops = new ArrayList<Stops>();
public String getType() {
return type;
}
public String getDriver() {
return driver;
}
public String getLn() {
return ln;
}
public String getShippersno() {
return shippersno;
}
public String getOramplocation() {
return oramplocation;
}
public String getOrampadd1() {
return orampadd1;
}
public String getOrampadd2() {
return orampadd2;
}
public String getOrampphone() {
return orampphone;
}
public String getOrampstate() {
return orampstate;
}
public String getOrampzip() {
return orampzip;
}
public String getDramplocation() {
return dramplocation;
}
public String getDrampadd1() {
return drampadd1;
}
public String getDrampadd2() {
return drampadd2;
}
public String getDrampphone() {
return drampphone;
}
public String getDrampstate() {
return drampstate;
}
public String getDrampzip() {
return drampzip;
}
public List<Stops> getStops() {
return stops;
}
}
class Stops {
String name;
String add1;
String add2;
String city;
String ext;
String phone;
String st;
String zip;
Integer stop;
Date apptment1;
Date apptment2;
public String getName() {
return name;
}
public String getAdd1() {
return add1;
}
public String getAdd2() {
return add2;
}
public String getCity() {
return city;
}
public String getExt() {
return ext;
}
public String getPhone() {
return phone;
}
public String getSt() {
return st;
}
public String getZip() {
return zip;
}
public Date getApptment1() {
return apptment1;
}
public Date getApptment2() {
return apptment2;
}
public Integer getStop() {
return stop;
}
}
class ThumbsUp {
private String message = "success";
public String getMessage() {
return message;
}
}
#Service
#Repository
public class trayMoveService {
#Autowired
private trayMoveRepository trayMoveRepo;
#Qualifier("trayMove")
public void populate(trayMove dm) {
trayMoveRepo.saveAndFlush(dm);
}
}
#Transactional
public interface trayMoveRepository extends JpaRepository<trayMove, Integer>{
}
The setter method doesnt work. I think m missing some annotations. Can someone direct me to the tutorial please ?
The application is Spring JPA(EclipseLink) annotation based.

Resources