Can't parse JSON because of recursive relationships when using #RelatedToVia - json

I am new to Neo4j and I want to connect a node (Person) with a node (Asset) but also, store the time that this connection has been created. I figured out that I have to use #RelatedtoVia annotation. I have followed the Spring cineasts tutorial ([https://github.com/spring-projects/spring-data-neo4j/tree/master/spring-data-neo4j-examples/cineasts][1] ) Although, everything works fine as far as the tests and the database population are concerned, I get weird results at the REST service. Here is my code:
Node Person
import org.neo4j.helpers.collection.IteratorUtil;
import org.springframework.data.neo4j.annotation.*;
import org.springframework.data.neo4j.template.Neo4jOperations;
import java.util.*;
#NodeEntity
public class Person {
#GraphId
Long id;
#Indexed
private String displayName;
#Indexed(unique = true, failOnDuplicate = true)
private Long personId;
private String firstName;
private String lastName;
private Date birthday;
private String aboutMe;
private String thumbnailURL;
private String email;
private enum gendertypes {male, female, other};
private gendertypes gender;
private String[] languages;
private boolean active;
public static final String CONSUMED = "CONSUMED";
//empty & full constructor
//getters&setters
#RelatedToVia(type = "CONSUMED", elementClass = ConsumedDate.class)
#Fetch
Iterable<ConsumedDate> consumedDates;
public ConsumedDate consumedDate(Neo4jOperations template, Asset asset, Date timestamp) {
final ConsumedDate consumedDate = template.createRelationshipBetween(this, asset, ConsumedDate.class, CONSUMED, false).consumedDate(timestamp);
return template.save(consumedDate);
}
public Collection<ConsumedDate> getConsumedDates() {
return IteratorUtil.asCollection(consumedDates);
}
}
Node Asset
import org.neo4j.helpers.collection.IteratorUtil;
import org.springframework.data.neo4j.annotation.*;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import static org.neo4j.graphdb.Direction.INCOMING;
#NodeEntity
public class Asset {
#GraphId
private Long id;
#Indexed(unique=true, failOnDuplicate = true)
private Long assetId;
private String description;
private String type;
private String[] tags;
public Asset() {}
public Asset(Long assetId, String description, String type, String[] tags) {
this.assetId = assetId;
this.description = description;
this.type = type;
this.tags = tags;
}
public Long getAssetId() {return assetId; }
public void setAssetId(Long assetId) {
this.assetId = assetId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String[] getTags() {
return tags;
}
public void setTags(String[] tags) {
this.tags = tags;
}
#RelatedTo(type = "CONSUMED", direction = INCOMING)
Set<Person> persons;
#RelatedToVia(type="CONSUMED", elementClass=ConsumedDate.class, direction=INCOMING)
#Fetch
Iterable<ConsumedDate> consumedDates;
public Collection<Person> getPersons() {
return persons;
}
public Collection<ConsumedDate> getConsumedDates() {
Iterable<ConsumedDate> allConsumedDates = consumedDates;
return allConsumedDates == null ? Collections.<ConsumedDate>emptyList() : IteratorUtil.asCollection(allConsumedDates);
}
#Override
public String toString() {
return "An asset with ID " + assetId + " description " + description + " type " + type;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Asset asset = (Asset) o;
if (id == null) return super.equals(o);
return id.equals(asset.id);
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : super.hashCode();
}
}
Relationship Entity ConsumedDate
import org.springframework.data.neo4j.annotation.EndNode;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.RelationshipEntity;
import org.springframework.data.neo4j.annotation.StartNode;
import java.util.Date;
#RelationshipEntity(type = "CONSUMED")
public class ConsumedDate {
#GraphId
Long id;
#EndNode
Asset asset;
#StartNode
Person person;
Date timestamp;
public ConsumedDate consumedDate(Date timestamp){
this.timestamp=timestamp;
return this;
}
public Asset getAsset() {
return asset;
}
public Person getPerson() {
return person;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ConsumedDate consumedDate = (ConsumedDate) o;
if (id == null) return super.equals(o);
return id.equals(consumedDate.id);
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : super.hashCode();
}
}
Controller
import gr.ntua.sam.context.neo4j.AssetRepository;
import gr.ntua.sam.context.neo4j.LocationRepository;
import gr.ntua.sam.context.neo4j.PersonRepository;
import gr.ntua.sam.context.resources.*;
import com.wordnik.swagger.annotations.ApiOperation;
import org.neo4j.graphdb.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.support.Neo4jTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.text.ParseException;
import java.util.*;
import java.util.List;
#RestController
#Configuration
#EnableNeo4jRepositories
public class ContextController {
#Autowired
Neo4jTemplate template;
#Autowired
AssetRepository assetRepository;
#Autowired
PersonRepository personRepository;
#ApiOperation(value = "Show the available assets", response = Asset.class)
#RequestMapping(value = "/asset", method = RequestMethod.GET)
public ResponseEntity<List<Asset>> getAssets() throws NotFoundException {
List<Asset> results = assetRepository.all();
return new ResponseEntity<List<Asset>>(results, HttpStatus.OK);
}
#ApiOperation(value = "Create a new asset",response = Asset.class)
#RequestMapping(value = "/asset", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Asset> saveAsset(#RequestBody Asset asset) {
Asset savedAsset = assetRepository.save(asset);
return new ResponseEntity<Asset>(savedAsset, HttpStatus.CREATED);
}
//Persons
#ApiOperation(value = "Get a list of all the available Persons")
#RequestMapping(value = "/person", method = RequestMethod.GET)
public ResponseEntity<List<Person>> getPersons() throws ParseException {
List<Person> results = personRepository.all();
return new ResponseEntity<List<Person>>(results, HttpStatus.OK);
}
#ApiOperation(value = "Creates a new Person node to store information about a user", response = Person.class)
#RequestMapping(value = "/person", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Person> savePerson(#RequestBody Person person) {
Person savedPerson = personRepository.save(person);
return new ResponseEntity<Person>(savedPerson, HttpStatus.CREATED);
}
#ApiOperation(value = "Creates relationship between a Person and an Asset")
#RequestMapping(value = "/person/{personId}/consumes/", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Void> consumes(#PathVariable("personId") Long personId, #RequestBody LinkedAsset linkedAsset) {
Person person = personRepository.findByPersonId(personId);
List<Long> assetIds = linkedAsset.getAssetIDs();
for (Long assetId : assetIds) {
Asset currentAsset = assetRepository.findByAssetId(assetId);
Date date= linkedAsset.getTimestamp();
ConsumedDate consumedDate= person.consumedDate(template,currentAsset,date);
template.save(consumedDate);
}
return new ResponseEntity<Void>(HttpStatus.CREATED);
}
The problem is that when I create a relationship between a Person and an Asset, along with a timestamp (I have created the class LinkedAsset which serves as a JSON input model and has nothing to do with Neo4j) and then try to get through REST the person or the asset, all I get is something definitely not JSON with the person or the asset appearing infinite times. Is there a way to face this problem?
Thank you in advance!

Related

How to query a many to many relationship in spring boot repository

I am trying to have the api return a list of notes, associated by a many to many relationship with labels, given a label id. Spring boot automatically created a bridge table called notes_tables with a notes_id field and a labels_id field. Spring Boot also created a notes table and a labels table. I attempted the following:
#Query(value="select * from notes join notes_labels on note.id=notes_id join labels on labels_id=labels.id where labels_id=:lid", nativeQuery=true)
public List<Note> findNotesForLabel(#Param("lid") int labelId);
I just need to get this to work but I am specifically curious if I can get it to work with jpa method query. Any query will do as long as it works though.
EDIT:
Entities
Note.java
package com.example.maapi.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.List;
import java.util.Objects;
#Entity
#Table(name = "notes")
public class Note {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String note;
private String title;
private String status = "private";
#ManyToOne
#JsonIgnore
private User user;
#ManyToOne
#JsonIgnore
private Folder folder;
#ManyToMany
#JsonIgnore
private List<Label> labels;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Folder getFolder() {
return folder;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public void setFolder(Folder folder) {
this.folder = folder;
}
public List<Label> getLabels() {
return labels;
}
public void setLabels(List<Label> labels) {
this.labels = labels;
}
#Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Note)) {
return false;
}
Note note = (Note) o;
return id == note.id && Objects.equals(note, note.note) &&
Objects.equals(title, note.title) && Objects.equals(status,
note.status) && Objects.equals(user, note.user) &&
Objects.equals(folder, note.folder) && Objects.equals(labels,
note.labels);
}
#Override
public int hashCode() {
return Objects.hash(id, note, title, status, user, folder,
labels);
}
}
Label.java
package com.example.maapi.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.List;
import java.util.Objects;
#Entity
#Table(name = "labels")
public class Label {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String title;
private String status = "private";
#ManyToOne
#JsonIgnore
private User user;
#ManyToOne
#JsonIgnore
private Folder folder;
#ManyToMany(mappedBy = "labels")
#JsonIgnore
private List<Note> notes;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Folder getFolder() {
return folder;
}
public void setFolder(Folder folder) {
this.folder = folder;
}
public List<Note> getNotes() {
return notes;
}
public void setNotes(List<Note> notes) {
this.notes = notes;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Label)) {
return false;
}
Label label = (Label) o;
return id == label.id && Objects.equals(title, label.title) &&
Objects.equals(status, label.status) && Objects.equals(user,
label.user) && Objects.equals(folder, label.folder) &&
Objects.equals(notes, label.notes);
}
#Override
public int hashCode() {
return Objects.hash(id, title, status, user, folder, notes);
}
}
Services:
NoteService.java
package com.example.maapi.services;
import com.example.maapi.models.Folder;
import com.example.maapi.models.Note;
import com.example.maapi.models.User;
import com.example.maapi.repositories.FolderRepo;
import com.example.maapi.repositories.NoteRepo;
import com.example.maapi.repositories.UserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class NoteService {
#Autowired
NoteRepo noteRepo;
#Autowired
UserRepo userRepo;
#Autowired
FolderRepo folderRepo;
public List<Note> findAllNotes(){
return noteRepo.findAllNotes();
}
public Note findNoteById(int noteId){
return noteRepo.findNoteById(noteId);
}
public List<Note> findNotesByUser(int userId){
return noteRepo.findNotesByUser(userId);
}
public Note createNoteForUser(int userId, Note note){
User user = userRepo.findUserById(userId);
note.setUser(user);
return noteRepo.save(note);
}
public List<Note> findNotesByFolder(int folderId){
return noteRepo.findNotesByFolder(folderId);
}
public Note createNoteForFolder(int folderId, Note note){
Folder folder = folderRepo.findFolderById(folderId);
note.setFolder(folder);
note.setUser(folder.getUser());
return noteRepo.save(note);
}
public int updateNote(int noteId, Note updatedNote){
Note note = noteRepo.findNoteById(noteId);
updatedNote.setUser(note.getUser());
updatedNote.setFolder(note.getFolder());
noteRepo.save(updatedNote);
if(updatedNote.equals(note)){
return 1;
} else {
return 0;
}
}
public int deleteNote(int noteId){
noteRepo.deleteById(noteId);
if(noteRepo.findNoteById(noteId) == null) {
return 1;
} else {
return 0;
}
}
// SEARCH IMPLEMENTATION
public List<Note> searchForNote(String note){
return noteRepo.searchForNote(note);
}
}
LabelService.java
So this is the spring-booty way to do this that I was able to figure out. CrudRepository has findById(Integer id) which returns an Optional object.
All you have to do is optional.get() to return the encapsulated object and then you can return the desired field (in my case List notes) with a getter.
// CrudRepo interface provides the findById method which returns an Optional<Label>
// object that may or may not exist. Optional.get() returns the encapsulated object.
public List<Note> findNotesByLabelId(int labelId) {
Optional<Label> label = labelRepo.findById(labelId);
return label.get().getNotes();
}
Try this one!
SELECT * FROM notes n INNER JOIN notes_labels nl ON nl.notes_id = n.note_id WHERE nl.labels_id = ?1
Edit:
#Entity
#Table(name = "notes")
#NamedNativeQuery(name = "Note.getNoteByLabel", resultSetMapping = "getNote",
query = "SELECT n.id,n.note,n.title,n.status FROM notes n INNER JOIN notes_labels nl ON nl.notes_id = n.note_id WHERE nl.labels_id = ?1")
#SqlResultSetMapping(name = "getNote", classes = #ConstructorResult(targetClass = Note.class,
columns = {#ColumnResult(name = "id", type = Integer.class),#ColumnResult(name = "note", type = String.class)
#ColumnResult(name = "title", type = String.class),#ColumnResult(name = "status", type = String.class)}))
public class Note {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String note;
private String title;
private String status = "private";
NoteRepo.java
#Query(nativeQuery = true)
List<Note> getNoteByLabel(int labelId);
Build a proper constructor and try this one.
You have to think on it as if it was simple POO. For example, you can use:
#Query("FROM Note n WHERE (SELECT l FROM Label l WHERE l.id = :lid) MEMBER OF labels")
public List<Note> findNotesByLabel(#Param("lid") int id);
which basically means,
get all notes where given id's label is part of the labels attribute
I don't fully know each implementation yet, surely the documentation would give a better approach, but I just came up with that problem and it did the trick

Evaluate expression json result In debug mode is different with final json result

I have a controller like this:
#ResponseBody
#RequestMapping(value = "/getLayersOfCategory/{categoryId}", method = RequestMethod.GET)
public LayersResult GetLayersOfCategory(#PathVariable("categoryId") Integer categoryId,#RequestHeader("secret") String secret) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm");
DataServicesModel dataServicesModel=new DataServicesModel();
LocalDateTime now = LocalDateTime.now();
CategoriesEntity categoriesEntity=new CategoriesEntity();
categoriesEntity.setId(categoryId);
List<Object[]> layersCategoriesEntityList=layersCategoriesRepository.findAllByCategoryId(categoryId);
List<String> stringList=new ArrayList<>();
for (Object[] row:layersCategoriesEntityList){
stringList.add(row[2].toString());
}
LayersResult layersResult=this.GetPoints(stringList);
**** return layersResult;
}
at **** when I Evaluate "layersResult" expression it shows a json like this:
but when I call the controller by postman
I get something like this:
as you see the iconUrl key has different. I do not know wher the result change at the end of the controller without any line of code tha could change the final result.
thanks in advance for replying.
And this a DataLayerModel:
package org.rajman.lbs.neshan.business.data.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParseException;
import jdk.nashorn.internal.ir.annotations.Ignore;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import javax.persistence.*;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public class DataLayerModel {
private Integer id;
private String title;
private String type;
private String iconUrl="kdjjfhskdjfh";
private String webUrl="http://map.tabr*.ir";
#JsonIgnore
public String getStyle() { return style;
}
public void setStyle(String style) {
this.style = style;
}
private String style="{\"icon\":\"dt.png\"}";
#Value("${url.webUrl:#{null}}")
#JsonIgnore
public String getWebUrl() {
return webUrl;
}
public void setWebUrl(String webUrl) {
this.webUrl = webUrl;
}
public DataLayerModel() {
}
public DataLayerModel(Integer id, String title, String type, String style) {
this.id = id;
this.title = title;
this.type = type.equals("ST_Polygon") || type.equals("polygon") ? "polygon" : "point";
this.style=style;
//this.iconUrl = getIconUrl();
}
public String getIconUrl() {
Object icon;
String url="";
JSONObject jsonObject;
try {
url=this.style;
jsonObject = new JSONObject(this.style);
icon=jsonObject.get("icon");
url=this.getWebUrl()+"/images/"+icon.toString();
}
catch (Exception e){
System.out.println(e);
}
return url;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Assuming iconUrl is a String. i.e. serialization is straight forward.
The only thing, I can guess that would go wrong is getIconUrl() method.
Please try to evaluate, layers.get(0).getIconUrl() at the same debug point.

Spring Data Rest - Exposing ID

I am trying to expose the Id of my domain on the Json response using Spring Data Rest, besides getting it on the self object. I try what I saw on the internet but it is not working. I am using Spring Boot and this is my starting class and my config class for exposing the Id.
package com.desingfreed;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan("com.designfreed")
public class GaliasBackendApplication {
public static void main(String[] args) {
SpringApplication.run(GaliasBackendApplication.class, args);
}
}
package com.desingfreed.config;
import com.desingfreed.domain.Articulo;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter;
import org.springframework.stereotype.Component;
#Component
public class ConfigurationRest extends RepositoryRestConfigurerAdapter {
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.exposeIdsFor(Articulo.class);
}
}
package com.desingfreed.repositories;
import com.desingfreed.domain.Articulo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
#RepositoryRestResource(collectionResourceRel = "articulos", path = "articulos")
public interface ArticuloRepository extends CrudRepository<Articulo, Long> {
}
package com.desingfreed.domain;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name = "STA11")
public class Articulo {
#Id
#GeneratedValue
#Column(name = "ID_STA11")
private Long id;
#Column(name = "COD_ARTICU")
private String codigo;
#Column(name = "DESCRIPCIO")
private String descripcion;
// #OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true, mappedBy = "articulo")
// private List<Precio> precios = new ArrayList<>();
public Articulo() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
// public List<Precio> getPrecios() {
// return precios;
// }
//
// public void setPrecios(List<Precio> precios) {
// this.precios = precios;
// }
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Articulo articulo = (Articulo) o;
if (id != null ? !id.equals(articulo.id) : articulo.id != null) return false;
if (codigo != null ? !codigo.equals(articulo.codigo) : articulo.codigo != null) return false;
return descripcion != null ? descripcion.equals(articulo.descripcion) : articulo.descripcion == null;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (codigo != null ? codigo.hashCode() : 0);
result = 31 * result + (descripcion != null ? descripcion.hashCode() : 0);
return result;
}
#Override
public String toString() {
return "Articulo{" +
"id=" + id +
", codigo='" + codigo + '\'' +
", descripcion='" + descripcion + '\'' +
'}';
}
}
Although doing this I still can get the Id on the Json response, I still get like this:
"_embedded" : {
"articulos" : [ {
"codigo" : "111012082",
"descripcion" : "VIRGEN LEV. FRESCA X 500G",
"_links" : {
"self" : {
"href" : "http://localhost:8080/articulos/1"
},
"articulo" : {
"href" : "http://localhost:8080/articulos/1"
}
}
Thanks very much!
For your information, i've created a simple component to dynamically expose every id.
#Component
public class EntityExposingIdConfiguration extends RepositoryRestConfigurerAdapter {
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
try {
Field exposeIdsFor = RepositoryRestConfiguration.class.getDeclaredField("exposeIdsFor");
exposeIdsFor.setAccessible(true);
ReflectionUtils.setField(exposeIdsFor, config, new ListAlwaysContains());
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
class ListAlwaysContains extends ArrayList {
#Override
public boolean contains(Object o) {
return true;
}
}
}

Database is overwriting. Last entry from json is written in database and all other entry is overwritten. Showing only last Entry of Json File

PlayerService
this is srvice class of my boot app.
package io.anuj.springbootquickstart.topic;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class PlayerService {
#Autowired
private PlayerRespository playerRespository;
// private List<Topic> topics = new ArrayList<> (Arrays.asList(
// new Topic("Spring","Spring Framework","SpringFramework Description"),
// new Topic("Core","Core Framework","CoreFramework Description"),
// new Topic("JavaScript","JavaScript Framework","JavaScript Description")));
public List<Player> getAllPlayer(){
List<Player> player = new ArrayList();
playerRespository.findAll()
.forEach(player::add); //lambda expressions
return player;
}
public Player getPlayer(Long id){
//return topics.stream().filter(t -> t.getId().equals(id).findFirst().get());
return playerRespository.findOne(id);
}
public void addPlayer(Player player) {
playerRespository.save(player);
}
public void updatePlayer(Long id, Player player) {
playerRespository.save(player);
}
public void deletePlayer(Long id) {
//topics.removeIf(t -> t.getId().equals(id));
playerRespository.delete(id);
}
}
PLayerRepository
this is player repository of my app.
package io.anuj.springbootquickstart.topic;
import org.springframework.data.repository.CrudRepository;
public interface PlayerRespository extends CrudRepository <Player, Long>{
//crud repository-logic of any entity class
//getallTopic()
//gettopic(string id)
//update topic(topic t)
//deletetopic(string id)
}
PLayerController
this is player controller
package io.anuj.springbootquickstart.topic;
import java.io.FileReader;
import java.util.List;
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.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
//wherever rest controller is written it will give json as output send back as a HTTP response
public class PlayerController {
#Autowired
private PlayerService playerService;
//get request by default
#RequestMapping("/player")
public List<Player> getallPlayer(){
return playerService.getAllPlayer();
}
//get request
#RequestMapping("/player/{id}")
public Player getPlayer(#PathVariable Long id){
return playerService.getPlayer(id);
}
//
#RequestMapping(method=RequestMethod.GET, value= "/getplayer")
public void addAllPlayer(){
Player player = new Player();
JSONParser parser = new JSONParser();
try {
Object ob = parser.parse(new FileReader("/home/bridgeit/Desktop/P.D-anuj/Json/newPlayerInfo.json"));
JSONObject object = (JSONObject) ob;
JSONArray data = (JSONArray) object.get("Playersinfo");
for (int i = 0; i < data.size(); i++)
{
JSONObject itemObj = (JSONObject) data.get(i);
Object nameObj = itemObj.get("player_name");
String playerName = (String) nameObj;
player.setPlayer_name(playerName);
Object imgObject = itemObj.get("player_img_url");
String playerPic = (String) imgObject;
player.setPlayer_img_url(playerPic);
Object roleObj = itemObj.get("player_role");
String roleName = (String) roleObj;
player.setPlayer_role(roleName);
Object battingStyleObj = itemObj.get("player_batting_style");
String battingStyleName = (String) battingStyleObj;
player.setPlayer_batting_style(battingStyleName);
Object bowlingObj = itemObj.get("player_bowling_style");
String bowlingName = (String) bowlingObj;
player.setPlayer_bowling_style(bowlingName);
Object nationalityObj = itemObj.get("player_nationality");
String nationalityName = (String) nationalityObj;
player.setPlayer_nationality(nationalityName);
Object dobObj = itemObj.get("player_dob");
String dobName = (String) dobObj;
player.setPlayer_dob(dobName);
Object teamIdObj = itemObj.get("team_id");
String teamIdName = (String) teamIdObj;
player.setTeam_id(teamIdName);
playerService.addPlayer(player);
}
} catch (Exception e) {
System.out.println(e);
}
}
/*#RequestMapping(method=RequestMethod.PUT, value= "/player/{id}")
public void updatePlayer(#RequestBody Player player,#PathVariable String id){
playerService.updatePlayer(id,player);
}
#RequestMapping(method=RequestMethod.DELETE, value= "/player/{id}")
public void deletePlayer(#PathVariable String id){
playerService.deletePlayer(id);
}*/
}
this is POJO class
Player.java
package io.anuj.springbootquickstart.topic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
#Entity
/*#Table(name = "Player")*/
public class Player {
/*#Id
#GenericGenerator(name = "gene", strategy = "increment")
#GeneratedValue(generator = "gene")
#Column(name = "id")
private Long id;*/
#Id
#GenericGenerator(name = "gene", strategy = "increment")
#GeneratedValue(generator = "gene")
private long id;
private String team_id;
/*#Column(name = "name")*/
private String player_name;
/*#Column(name = "display_picture")*/
private String player_img_url;
/*#Column(name = "role")*/
private String player_role;
public Player(long id, String team_id, String player_name, String player_img_url, String player_role,
String player_batting_style, String player_bowling_style, String player_nationality, String player_dob) {
super();
this.id = id;
this.team_id = team_id;
this.player_name = player_name;
this.player_img_url = player_img_url;
this.player_role = player_role;
this.player_batting_style = player_batting_style;
this.player_bowling_style = player_bowling_style;
this.player_nationality = player_nationality;
this.player_dob = player_dob;
}
/* #Column(name = "batting_style")*/
private String player_batting_style;
/*#Column(name = "bowling_style")*/
private String player_bowling_style;
/*#Column(name = "nationality")*/
private String player_nationality;
/*#Column(name = "dob")*/
private String player_dob;
/*#Column(name = "teamId")*/
public Player(){
}
public String getTeam_id() {
return team_id;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public void setTeam_id(String team_id) {
this.team_id = team_id;
}
public String getPlayer_name() {
return player_name;
}
public void setPlayer_name(String player_name) {
this.player_name = player_name;
}
public String getPlayer_img_url() {
return player_img_url;
}
public void setPlayer_img_url(String player_img_url) {
this.player_img_url = player_img_url;
}
public String getPlayer_role() {
return player_role;
}
public void setPlayer_role(String player_role) {
this.player_role = player_role;
}
public String getPlayer_batting_style() {
return player_batting_style;
}
public void setPlayer_batting_style(String player_batting_style) {
this.player_batting_style = player_batting_style;
}
public String getPlayer_bowling_style() {
return player_bowling_style;
}
public void setPlayer_bowling_style(String player_bowling_style) {
this.player_bowling_style = player_bowling_style;
}
public String getPlayer_nationality() {
return player_nationality;
}
public void setPlayer_nationality(String player_nationality) {
this.player_nationality = player_nationality;
}
public String getPlayer_dob() {
return player_dob;
}
public void setPlayer_dob(String player_dob) {
this.player_dob = player_dob;
}
/*public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}*/
/*public Player(Long id, String team_id, String player_name, String player_img_url, String player_role,
String player_batting_style, String player_bowling_style, String player_nationality, String player_dob) {
super();
this.id = id;
this.team_id = team_id;
this.player_name = player_name;
this.player_img_url = player_img_url;
this.player_role = player_role;
this.player_batting_style = player_batting_style;
this.player_bowling_style = player_bowling_style;
this.player_nationality = player_nationality;
this.player_dob = player_dob;
}
*/
}
When i execute from json file it shows only last entry of json file. JSON file contains around 150 players but in databse is shows only last entry of the player. i think all the data is getting overwritten. Only last entry is shown of that json file in database. That is last player. Only one player which is last in json is there in database.
It's a little difficult to tell because you have a lot of commented out code that makes things harder to follow, but I think it is because of where you are creating the Player in your controller. Since you're doing this:
Player player = new Player()
outside of the loop, and Java is pass by value of reference, after the first time you addPlayer, you're just updating the same player with new data each time. You could confirm this if you simply debug your code and see if player has an ID after the first save call.
You'd probably want to do this to fix it:
for (int i = 0; i < data.size(); i++) {
Player player = new Player();
// rest of your code here
}

How to increment primary key without check AUTOINCREMENT in MySQL

How to increment primary key without check AUTOINCREMENT in MySQL?
My Example:
Tax.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package newpackage;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.persistence.*;
import javax.transaction.UserTransaction;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author gile
*/
#Entity
#Table(name = "tax", catalog = "invoicedb", schema = "")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Tax.findAll", query = "SELECT t FROM Tax t"),
#NamedQuery(name = "Tax.findByIdtax", query = "SELECT t FROM Tax t WHERE t.idtax = :idtax"),
#NamedQuery(name = "Tax.findByValue", query = "SELECT t FROM Tax t WHERE t.value = :value"),
**#NamedQuery(name = "Tax.findMaxID", query = "SELECT MAX (t.idtax) from Tax t")})** // I write this query to find max value of primary key. how to find max ?
public class Tax implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "idtax")
private Integer idtax;
#Basic(optional = false)
#NotNull
#Column(name = "value")
private BigDecimal value;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "taxid")
private List<Invoicedetails> invoicedetailsList;
public Tax() {
}
public Tax(Integer idtax) {
this.idtax = idtax;
}
public Tax(Integer idtax, BigDecimal value) {
this.idtax = idtax;
this.value = value;
}
public Integer getIdtax() {
return idtax;
}
public void setIdtax(Integer idtax) {
this.idtax = idtax;
}
public BigDecimal getValue() {
return value;
}
public void setValue(BigDecimal value) {
this.value = value;
}
#XmlTransient
public List<Invoicedetails> getInvoicedetailsList() {
return invoicedetailsList;
}
public void setInvoicedetailsList(List<Invoicedetails> invoicedetailsList) {
this.invoicedetailsList = invoicedetailsList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idtax != null ? idtax.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 Tax)) {
return false;
}
Tax other = (Tax) object;
if ((this.idtax == null && other.idtax != null) || (this.idtax != null && !this.idtax.equals(other.idtax))) {
return false;
}
return true;
}
#Override
public String toString() {
return String.format("%.2f %%",value);
}
#Transient
private String taxvalueString;
public String getTaxvalueString() {
return String.format(" %.2f %%",value);
}
public void setTaxvalueString(String taxvalueString) {
this.taxvalueString = taxvalueString;
}
}
You can add a method in Tax Class with PrePersit annotation for creating PK (idtax)
like
#PrePersist
private void generateID() {
// Read existing Tax record, finde new id and set pk here.
}