Error using Spel expressions in Spring JPA native query( converting string to Hexa) - spring-boot

I created a repository with the following method.
#Modifying(clearAutomatically = true)
#Query(
value = "UPDATE address SET address_line_1 = :#{#address.getAddressLine1()} , address_line_2 = :#{#address.getAddressLine2()} ," +
" address_line_3 = :#{#address.getAddressLine3()} , city = :#{#address.getCity()} , address_type = :#{#address.getAddressType().toString()} ," +
" postal_code = :#{#address.getPostalCode()} , state = :#{#address.getState().toString()} , country= :#{#address.getCountry().toString()} , residence_type = :#{#address.getResidenceType().toString()} ," +
" discriminator = :#{#address.getAddressType().toString()},created_by = :#{#address.getCreatedBy()} , created_date = :#{#address.getCreatedDateTime()} WHERE address_id = :#{#address.getId()}",
nativeQuery = true)
void updateAddress(#Param("address") Address address);
During the updates the addressLine2/ addressLine3 is converted to and stored in the database in hexa format.
For example, if addressLine2 is passed into the method as 1OFFICE OF HOBBITS, it is converted to and stored as \x314f6666696365206f6620486f6262697473
This only occurs on a few updates (not all). I cannot discern a distinguishable pattern among the values that are updated as expected and those that are converted to hexa format.
HELP!!
Additional Info:
I even tried without the Spel Expression and I see the same error:
Here are some more details:
Repository Interface:
import com.company.domain.Address;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface AddressRepository extends JpaRepository<Address, Long> {
#Modifying(clearAutomatically = true)
#Query(
value = "UPDATE address SET address_line_1 = :address_line_1 , address_line_2 = :address_line_2 ," +
" address_line_3 = :address_line_3 WHERE address_id = :address_id ",
nativeQuery = true)
void updateAddress(#Param("address_line_1") String address_line_1,#Param("address_line_2") String address_line_2,#Param("address_line_3") String address_line_3,#Param("address_id") Long address_id);
}
Service Class:
import com.company.hibernate.AddressRepository;
import com.company.domain.Address;
import com.company.domain.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Class by AddressServiceImpl
*/
#Service
public class AddressServiceImpl implements AddressService {
#Autowired
private AddressRepository addressRepository;
#Override
public void updateAddress(Address address) {
System.out.println(address);
System.out.println(address.getId());
System.out.println(address.getAddressLine2());
addressRepository.updateAddress(address.getAddressLine1() , address.getAddressLine2() ,
address.getAddressLine3(),address.getId());
}
}
When I call the service method
addressService.updateAddress(address);
I see the following sysouts:
{"addressId":2000112115,"addressLine1":"2001 Hussle
Road2","addressLine2":"Office of Hobbits","addressLine3":null }
2000112115
Office of Hobbits
But In the database I see : the following for address_line_2
\x4f6666696365206f6620486f6262697473
Updated 2 - Added address class:
package com.company.domain;
import com.company.common.Identifiable;
import com.company.enums.AddressType;
import com.company.ResidenceType;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.EqualsExclude;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.HashCodeExclude;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.io.Serializable;
import java.time.LocalDateTime;
public class Address implements Identifiable<Long>, Serializable {
private static final long serialVersionUID = 599052439022921076L;
protected static final String INVALID_ADDRESS = "InvalidAddress";
private Long addressId;
private String addressLine1;
private String addressLine2;
private String addressLine3;
#Override
public Long getId() {
return addressId;
}
public void setId(Long id) {
this.addressId = id;
}
public Customer getCustomer() {
return customer;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getAddressLine3() {
return addressLine3;
}
public void setAddressLine3(String addressLine3) {
this.addressLine3 = addressLine3;
}
#Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj, false);
}
#Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this, false);
}
#Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}
}

Related

JPA - Converter class is not being invoked as expected

I cannot figure out why my converter class is not being called. I have the following Entity class:
import org.springframework.validation.annotation.Validated;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.List;
#Entity
#Validated
#Table(name = "c_mark", schema="common")
public class CMark {
#Id
#Column(name = "c_mark_id")
private String id;
#Column(name = "cl_fk")
private String cFk;
#Column(name = "s_con")
#Convert(converter = StringListConverterCommaDelim.class)
private List<String> sCon;
#Override
public String toString() {
return "ClassificationMarking{" +
"id='" + id + '\'' +
", cFk='" + cFk + '\'' +
", s_con='" + s_con + '\'' +
'}';
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCFk() {
return cFk;
}
public void setCFk(String cFk) {
this.cFk = cFk;
}
public List<String> getSCon() {
return sCon;
}
public void setSCon(List<String> sCon) {
this.sCon = sCon;
}
}
Here is the converter class:
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.Arrays;
import java.util.List;
import static java.util.Collections.emptyList;
#Converter
public class StringListConverterCommaDelim implements AttributeConverter<List<String>, String>
{
private static final String SPLIT_CHAR = ",";
#Override
public String convertToDatabaseColumn(List<String> stringList) {
return stringList != null ? String.join(SPLIT_CHAR, stringList) : "";
}
#Override
public List<String> convertToEntityAttribute(String string) {
return string != null ? Arrays.asList(string.split(SPLIT_CHAR)) : emptyList();
}
}
Here is the repo interface that defines the insert method:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
public interface CMarkRepository extends JpaRepository <ClassificationMarking, String> {
#Transactional
#Modifying
#Query(value = "INSERT INTO c_mark(c_fk, s_con) " +
"values(:c_fk, :s_con)", nativeQuery = true)
int insertCMark(#Param("c_fk") String c_fk, #Param("s_con") String s_con);
}
, and finally the method that invokes the insert:
public int postCMark(CMark cMark) {
CMark cm = null;
int status = 0;
try {
status = cMarkingRepository.insertCMark(cMark.getCFk(), cMark.getSCon());
} catch ( Exception e) {
e.printStackTrace();
}
return status;
}
My expectation is that the conversion takes place from the insertCMark() call? I am not sure. In any event, the converter is never called. I would be grateful for any ideas. Thanks!
You're not inserting the whole Entity. So I guess from Spring perspective you just give normal String parameters and Spring probably doesn't know the parameter should somehow be converted.
Despite that shouldn't you even get a compile error because you try to call insertCMark(String, String) as insertCMark(String, List<String>)?
Right now I would say that there is no need for some fancy Spring magic.
You can just tweak the getSCon() method to return a String and convert it in there. Or when you need it for something else to create a second method getSConString():
public String getSCon() {
return this.sCon != null ? String.join(SPLIT_CHAR, this.sCon) : "";
}
Another way is to use your current Converter by hand when calling insertCMark:
public int postCMark(CMark cMark) {
CMark cm = null;
int status = 0;
AttributeConverter<List<String>, String> converter = new StringListConverterCommaDelim();
String sCon = converter.convertToDatabaseColumn(cMark.getSCon());
try {
status = cMarkingRepository.insertCMark(cMark.getCFk(), sCon);
} catch ( Exception e) {
e.printStackTrace();
}
return status;
}

in case of violation in saveAll() in spring boot hibernate

I am currently working on a Spring Boot Hibernate.
I need to save a list of objects in mySql database,
I read about the difference between saving using saveAll() and foreach save() and I can conclude that saveAll() is much faster. However, in case of exception say UK violation for example, the whole process rollback, and no object will be saved.
To be more simple: I want to save a list of object in one transaction, and in case of any constraint violation, ignore it and save the rest.
this is my entity:
package com.entity;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
#Transactional
public class Page {
#Id
#GeneratedValue(generator = "page_sequence-generator")
#GenericGenerator(
name = "page_sequence-generator",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
#Parameter(name = "sequence_name", value = "page_sequence"),
#Parameter(name = "initial_value", value = "1"),
#Parameter(name = "increment_size", value = "1")
}
)
private long id;
#Column(nullable = false, unique = true)
private String url;
private boolean isPageConsumed;
public Page() {
}
public Page(String url, boolean isPageConsumed) {
this.url = url;
this.isPageConsumed = isPageConsumed;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public boolean isPageConsumed() {
return isPageConsumed;
}
public void setPageConsumed(boolean pageConsumed) {
isPageConsumed = pageConsumed;
}
#Override
public String toString() {
return "Page{" +
"id=" + id +
", url='" + url + '\'' +
", isPageConsumed=" + isPageConsumed +
'}';
}
}
And this is my repository:
#Repository
public interface PageRepository extends CrudRepository<Page, String> {
#Query(value = "SELECT p FROM Page p where p.isPageConsumed = '0'")
public Page findFirstPage();
}
Thank you :)
You could use Spring's #Transactional(noRolbackFor={SomeException.class}) on the controller method that invokes saveAll().

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);
}
}
}

Relationship issue on neo4j.ogm using spring boot application

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.

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