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

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

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

Repository returns empty list in Spring boot

I am trying to write a simple REST to pull records from a table that was shared with me. Since the table doesn't have a default ID column, I embedded a pk column to the entity object. Please find the code below for your review.
The issue I'm facing is that the repository.findByMediaType, where mediaType is one of the entity properties, returns empty list. I made sure the query param is not null and there are records in the table for the param passed. I tried findAll as well but didn't work. I can't seem to find what's wrong with the code. I am new to spring boot and would like to know the different ways I can debug this.
Service implementation class
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hyb.enterprisedashboard.api.entity.Tenders;
import com.hyb.enterprisedashboard.api.repository.DashboardRepository;
#Service
public class DashboardServiceImpl implements DashboardService{
Logger logger = LoggerFactory.getLogger(DashboardServiceImpl.class);
#Autowired
DashboardRepository dashboardRepository;
#Override
public List<Tenders> getTenderByMediaType(String mediaType) {
List<Tenders> tenderList = dashboardRepository.findAll();
//findByMediaType(mediaType);
tenderList.stream().forEach(tender -> {
logger.info("Order {} paid via {}",tender.getId().getOrderNumber(), tender.getMediaType());
});
return tenderList;
}
}
Entity class
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name = "TENDERS")
public class Tenders {
/** The id. */
#EmbeddedId
private TendersPK id;
/** The dateTime. */
#Column(name="DATE_TIME")
private Date dateTime;
/** The tenderMedia. */
#Column(name="TENDERED_MEDIA")
private String tenderMedia;
/** The mediaType. */
#Column(name="MEDIA_TYPE")
private String mediaType;
/** The tenderAmount. */
#Column(name="TENDERED_AMOUNT")
private BigDecimal tenderAmount;
/**
* #return the id
*/
public TendersPK getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(TendersPK id) {
this.id = id;
}
/**
* #return the dateTime
*/
public Date getDateTime() {
return dateTime;
}
/**
* #param dateTime the dateTime to set
*/
public void setDateTime(Date dateTime) {
this.dateTime = dateTime;
}
/**
* #return the tenderMedia
*/
public String getTenderMedia() {
return tenderMedia;
}
/**
* #param tenderMedia the tenderMedia to set
*/
public void setTenderMedia(String tenderMedia) {
this.tenderMedia = tenderMedia;
}
/**
* #return the mediaType
*/
public String getMediaType() {
return mediaType;
}
/**
* #param mediaType the mediaType to set
*/
public void setMediaType(String mediaType) {
this.mediaType = mediaType;
}
/**
* #return the tenderAmount
*/
public BigDecimal getTenderAmount() {
return tenderAmount;
}
/**
* #param tenderAmount the tenderAmount to set
*/
public void setTenderAmount(BigDecimal tenderAmount) {
this.tenderAmount = tenderAmount;
}
#Override
public String toString() {
return "Tenders [id=" + id + ", dateTime=" + dateTime + ", tenderMedia=" + tenderMedia + ", mediaType="
+ mediaType + ", tenderAmount=" + tenderAmount + "]";
}
}
PK Embedded class
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable
public class TendersPK implements Serializable{
/** The Constant serialVersionUID.*/
private static final long serialVersionUID = 1L;
/**
*
*/
public TendersPK() {
}
/**
* #param storeNumber
* #param orderNumber
*/
public TendersPK(long storeNumber, long orderNumber) {
super();
this.storeNumber = storeNumber;
this.orderNumber = orderNumber;
}
#Column(name = "STORE_NUMBER")
private long storeNumber;
#Column(name = "ORDER_NUMBER")
private long orderNumber;
/**
* #return the storeNumber
*/
public long getStoreNumber() {
return storeNumber;
}
/**
* #param storeNumber the storeNumber to set
*/
public void setStoreNumber(long storeNumber) {
this.storeNumber = storeNumber;
}
/**
* #return the orderNumber
*/
public long getOrderNumber() {
return orderNumber;
}
/**
* #param orderNumber the orderNumber to set
*/
public void setOrderNumber(long orderNumber) {
this.orderNumber = orderNumber;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (orderNumber ^ (orderNumber >>> 32));
result = prime * result + (int) (storeNumber ^ (storeNumber >>> 32));
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof TendersPK))
return false;
TendersPK other = (TendersPK) obj;
if (orderNumber != other.orderNumber)
return false;
if (storeNumber != other.storeNumber)
return false;
return true;
}
#Override
public String toString() {
return "TendersPK [storeNumber=" + storeNumber + ", orderNumber=" + orderNumber + "]";
}
}
Repository class
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.hyb.enterprisedashboard.api.entity.Tenders;
import com.hyb.enterprisedashboard.api.entity.TendersPK;
#Repository
public interface DashboardRepository extends JpaRepository<Tenders, TendersPK>{
#Query("select t from Tenders t where t.mediaType = ?1")
List<Tenders> findByMediaType(String mediaType);
}
And I see the below query passed in the console
Hibernate: select tenders0_.order_number as order_number1_0_, tenders0_.store_number as store_number2_0_, tenders0_.date_time as date_time3_0_, tenders0_.media_type as media_type4_0_, tenders0_.tendered_amount as tendered_amount5_0_, tenders0_.tendered_media as tendered_media6_0_ from tenders tenders0_
Could anyone please help to find the cause?
This was happening to me and it turns out my spring.datasource.* properties were not being set. I had them in the wrong file and the were not being read.
I would think that my repository query would error out if I had not provided datasource url, username, and password - instead I would simply just get an empty list returned.
I ended up figuring out that I was not pulling my datasource credentials by adding this in my RestController:
#Value("${spring.datasource.username}")
String username;
Then I just printed username to the system.out.println. When starting the application I would get an error that spring.datasource.username was undefined. Hence I knew I was not loading datasource information that I thought I was.

Get _links with spring RepositoryRestController

I have defined custom controllers for my repositories. For example, one looks like this
#RequestMapping(method = RequestMethod.GET, value = "/myEntities")
public ResponseEntity<?> get() {
...TO SOME STUFF
MyEntity myEntity= myEntityRepository.findById(1);
return ResponseEntity.ok(new Resource<>(myEntity));
}
This returns a JSON format data which includes a _links section, where I can get the href to the entity.
Now if I want to return an array of entities which are all resources, I get stuck.
What I have tried so far:
1.
#RequestMapping(method = RequestMethod.GET, value = "/myEntities")
public ResponseEntity<?> get() {
...TO SOME STUFF
List<MyEntity> myEntityList= myEntityRepository.findAll(1);
return ResponseEntity.ok(new Resources<>(myEntityList));
}
2.
#RequestMapping(method = RequestMethod.GET, value = "/myEntities")
public ResponseEntity<?> get() {
...TO SOME STUFF
List<MyEntity> myEntityList= myEntityRepository.findAll();
List<Resource<MyEntity>> resources = new ArrayList<>();
myEntityList.forEach(me -> {
resources.add(new Resource<>(me));
})
return ResponseEntity.ok(resources);
}
Option 1. and 2. don't add _links to the result and I don't understand why. I have googled it a lot and you can add links manually but this seems to be a much clearer way. Can anybody understand, what I'm doing wrong?
There are answers at "adding association links to spring data rest custom exposed method" and "Enable HAL serialization in Spring Boot for custom controller method" for similar questions. I tried something a little different from those answers, for solving a similar situation, and it worked fine. I wish you get your problem solved.
It follows how I did solve my specific situation:
#PostMapping(value = "/myEntities/searchWithParams"
, consumes = MediaType.APPLICATION_JSON_VALUE
, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> searchWithParams(#RequestBody SearchParamsDtoClass params, PersistentEntityResourceAssembler assembler)
{
List<MyEntity> entities = myEntityService.searchWithParams(params);
List<PersistentEntityResource> resourcesList = new ArrayList<PersistentEntityResource>();
for (MyEntity entity: entities) {
PersistentEntityResource resource = assembler.toResource(entity);
resourcesList.add(resource);
}
Resources<PersistentEntityResource> resources = new Resources(resourcesList);
return ResponseEntity.ok(resources);
}
The Resources constructor accepts a collection of embedded content, which is not the same as a collection of links. You have to add the links manually.
Resources resources = new Resources();
resources.add(myEntityRepository
.findAll()
.stream()
.map(entry -> convertToLink(entry)
.collect(Collectors.toList()));
return ResponseEntity.ok(resources);
Here is an example that includes embedded content and pagination in a HAL compliant format.
import static java.util.Objects.*;
import static java.util.Optional.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.springframework.hateoas.MediaTypes.*;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*;
import static org.springframework.http.HttpStatus.*;
import static org.springframework.http.MediaType.*;
import static org.springframework.web.bind.annotation.RequestMethod.*;
import java.util.ArrayList;
import javax.inject.Inject;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.elasticsearch.index.query.QueryBuilder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.hateoas.Link;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.codahale.metrics.annotation.Timed;
#RestController
#RequestMapping("/catalog/users")
public class UserResource {
private final #NotNull UserLocator locator;
private final #NotNull ElasticsearchOperations elasticsearchTemplate;
#Inject
public UserResource(
final #NotNull UserLocator locator,
final #NotNull ElasticsearchOperations elasticsearchTemplate
) {
this.locator = requireNonNull(locator, "locator cannot be null");
this.elasticsearchTemplate = requireNonNull(elasticsearchTemplate, "elasticsearchTemplate cannot be null");
}
/**
* GET /users : get all the users.
*
* #return the ResponseEntity with status 200 (OK) and the list of users in body
*/
#Timed
#RequestMapping(method = GET, produces = { HAL_JSON_VALUE, APPLICATION_JSON_VALUE })
public ResponseEntity<Representations<User>> allUsers(
#RequestParam(name = "page", required = false, defaultValue = "0") #Min(0) int page,
#RequestParam(name = "size", required = false, defaultValue = "25") #Min(1) int size,
#RequestParam(name = "like", required = false) String like
) {
final PageRequest pageRequest = new PageRequest(page, size, Sort.Direction.ASC, "surname.raw", "givenName.raw");
final Page<User> entries = elasticsearchTemplate.queryForPage(
new NativeSearchQueryBuilder()
.withQuery(startingWith(like))
.withPageable(pageRequest)
.build(),
User.class
);
final ArrayList<Link> links = new ArrayList<>();
links.add(linkTo(UserResource.class).withSelfRel());
if (!entries.isFirst()) {
links.add(linkTo(methodOn(UserResource.class).allUsers(0, size, like)).withRel("first"));
}
if (!entries.isLast()) {
links.add(linkTo(methodOn(UserResource.class).allUsers(entries.getTotalPages() - 1, size, like)).withRel("last"));
}
if (entries.hasNext()) {
links.add(linkTo(methodOn(UserResource.class).allUsers(entries.nextPageable().getPageNumber(), size, like)).withRel("next"));
}
if (entries.hasPrevious()) {
links.add(linkTo(methodOn(UserResource.class).allUsers(entries.previousPageable().getPageNumber(), size, like)).withRel("prev"));
}
final Representations<User> resourceList = new Representations<>(entries, Representations.extractMetadata(entries), links);
return ResponseEntity.ok(resourceList);
}
private QueryBuilder startingWith(String like) {
return isNull(like) ? null : matchPhrasePrefixQuery("_all", like);
}
/**
* GET /users/:identifier : get the "identifier" user.
*
* #param identifier the identifier of the role to retrieve
* #return the ResponseEntity with status 200 (OK) and with body the role, or with status 404 (Not Found) or with 410 (Gone)
*/
#Timed
#RequestMapping(value = "/{identifier}", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<UserRepresentation> aUser(
#PathVariable("identifier") #NotNull String identifier
) {
return ofNullable(this.locator.findOne(identifier))
.map(user -> toRepresentation(user))
.map(ResponseEntity::ok)
.orElse(notFound())
;
}
private #NotNull UserRepresentation toRepresentation(final #NotNull User role) {
final String id = role.getIdentifier();
final Link self = linkTo(methodOn(UserResource.class).aUser(id)).withSelfRel().expand(id);
final Link collection = linkTo(UserResource.class).withRel("collection");
return new UserRepresentation(role, self, collection);
}
protected final #NotNull <U> ResponseEntity<U> notFound() {
return new ResponseEntity<>(NOT_FOUND);
}
}
import java.util.Optional;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.core.Relation;
#Relation(value = "item", collectionRelation = "items")
public class UserRepresentation extends Representation<User> {
public UserRepresentation(User content, Iterable<Optional<Link>> links) {
super(content, links);
}
public UserRepresentation(User content, Link... links) {
super(content, links);
}
#SafeVarargs
public UserRepresentation(User content, Optional<Link>... links) {
super(content, links);
}
public UserRepresentation(User content) {
super(content);
}
}
import static java.util.Arrays.*;
import static java.util.Collections.*;
import static java.util.Objects.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.ResourceSupport;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Representation<T> extends Resource<T> {
private final Map<String, ResourceSupport> embedded = new HashMap<>();
public Representation(final #NotNull T content) {
super(content, emptyList());
}
public Representation(final #NotNull T content, final #NotNull Link... links) {
super(content, links);
}
#SafeVarargs
public Representation(final #NotNull T content, final #NotNull Optional<Link>... links) {
this(content, (Iterable<Optional<Link>>) asList(links));
}
public Representation(final #NotNull T content, final #NotNull Iterable<Optional<Link>> links) {
super(content, emptyList());
asStream(links).forEach(this::add);
}
public void add(final #NotNull Optional<Link> link) {
if (null != link && link.isPresent()) super.add(link.get());
}
#JsonProperty("_embedded")
#JsonInclude(Include.NON_EMPTY)
public final #NotNull Map<String, ResourceSupport> getEmbedded() {
return this.embedded;
}
/**
* #param rel must not be {#literal null} or empty.
* #param resource the resource to embed
*/
public final void embed(final #NotNull #Size(min=1) String rel, final ResourceSupport resource) {
requireNonNull(rel, "rel cannot be null");
if (rel.trim().isEmpty()) {
throw new IllegalArgumentException("rel cannot be empty");
}
if (null != resource) {
this.embedded.put(rel, resource);
}
}
}
import javax.validation.constraints.NotNull;
import org.springframework.data.domain.Page;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Resources;
import org.springframework.hateoas.PagedResources.PageMetadata;
import org.springframework.hateoas.core.Relation;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
#Relation(collectionRelation = "items")
public class Representations<T> extends Resources<T> {
#JsonUnwrapped
#JsonInclude(JsonInclude.Include.NON_NULL)
private final PageMetadata metadata;
public Representations(Iterable<T> content) {
super(content);
this.metadata = null;
}
public Representations(Iterable<T> content, PageMetadata metadata) {
super(content);
this.metadata = metadata;
}
public Representations(Iterable<T> content, Iterable<Link> links) {
super(content, links);
this.metadata = null;
}
public Representations(Iterable<T> content, PageMetadata metadata, Iterable<Link> links) {
super(content, links);
this.metadata = metadata;
}
public Representations(Iterable<T> content, Link... links) {
super(content, links);
this.metadata = null;
}
public Representations(Iterable<T> content, PageMetadata metadata, Link... links) {
super(content, links);
this.metadata = metadata;
}
/**
* Returns the pagination metadata.
*
* #return the metadata
*/
#JsonProperty("page")
public PageMetadata getMetadata() {
return metadata;
}
public static <U> PageMetadata extractMetadata(final #NotNull Page<U> page) {
return new PageMetadata(page.getSize(), page.getNumber(), page.getTotalElements(), page.getTotalPages());
}
}

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

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

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.

Resources