The springboot application exposes the graphql API on the endpoint "localhost:8091/rest/books". When I test it with Postman passing the query in the body as graphQL type it gives error "Invalid Syntax", whereas when I pass the same query as raw text, it yields correct results. I'm using HSQL. The structure of my application is:
The files with their code respectively are:
Book.java
package com.techprimers.graphql.springbootgrapqlexample.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
//#AllArgsConstructor
//#NoArgsConstructor
#Setter
#Getter
#Table
#Entity
public class Book {
#Id
private String isn;
public Book() {
super();
}
public Book(String isn, String title, String publisher, String[] authors, String publishedDate) {
super();
this.isn = isn;
this.title = title;
this.publisher = publisher;
this.authors = authors;
this.publishedDate = publishedDate;
}
public String getIsn() {
return isn;
}
public void setIsn(String isn) {
this.isn = isn;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String[] getAuthors() {
return authors;
}
public void setAuthors(String[] authors) {
this.authors = authors;
}
public String getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(String publishedDate) {
this.publishedDate = publishedDate;
}
private String title;
private String publisher;
private String[] authors;
private String publishedDate;
}
BookRepository.java
package com.techprimers.graphql.springbootgrapqlexample.repository;
import com.techprimers.graphql.springbootgrapqlexample.model.Book;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository extends JpaRepository<Book, String> {
}
BookResource.java
package com.techprimers.graphql.springbootgrapqlexample.resource;
import com.techprimers.graphql.springbootgrapqlexample.service.GraphQLService;
import graphql.ExecutionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#CrossOrigin(origins = "http://localhost:3000")
#RequestMapping("/rest/books")
#RestController
public class BookResource {
#Autowired
GraphQLService graphQLService;
#PostMapping
public ResponseEntity<Object> getAllBooks(#RequestBody String query) {
ExecutionResult execute = graphQLService.getGraphQL().execute(query);
return new ResponseEntity<>(execute, HttpStatus.OK);
}
}
AllBooksDataFetcher.java
package com.techprimers.graphql.springbootgrapqlexample.service.datafetcher;
import com.techprimers.graphql.springbootgrapqlexample.model.Book;
import com.techprimers.graphql.springbootgrapqlexample.repository.BookRepository;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
#Component
public class AllBooksDataFetcher implements DataFetcher<List<Book>>{
#Autowired
BookRepository bookRepository;
#Override
public List<Book> get(DataFetchingEnvironment dataFetchingEnvironment) {
return bookRepository.findAll();
}
}
BookDataFetcher.java
package com.techprimers.graphql.springbootgrapqlexample.service.datafetcher;
import com.techprimers.graphql.springbootgrapqlexample.model.Book;
import com.techprimers.graphql.springbootgrapqlexample.repository.BookRepository;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class BookDataFetcher implements DataFetcher<Book>{
#Autowired
BookRepository bookRepository;
#Override
public Book get(DataFetchingEnvironment dataFetchingEnvironment) {
String isn = dataFetchingEnvironment.getArgument("id");
return bookRepository.findById(isn).get();
}
}
And in the resources folder is
Books.graphql (contains schema)
schema {
query: Query
}
type Query {
allBooks: [Book]
book(id: String): Book
}
type Book {
isn: String
title: String
publisher: String
authors: [String]
publishedDate: String
}
Related
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'categoryService': Unsatisfied dependency expressed through field 'categoryRepository': Error creating bean with name 'categoryRepository' defined in com.example.demo.repository.CategoryRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class com.example.demo.model.Category
package com.example.demo.model;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
#Table(name="categories")
public class Category {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "name")
private #NotNull String categoryName;
#Column(name = "description")
private String description;
#Column(name = "image")
private String imageUrl;
public Category() {
}
public Category(#NotNull String categoryName) {
this.categoryName = categoryName;
}
public Category(#NotNull String categoryName, String description) {
this.categoryName = categoryName;
this.description = description;
}
public Category(#NotNull String categoryName, String description, String imageUrl) {
this.categoryName = categoryName;
this.description = description;
this.imageUrl = imageUrl;
}
public String getCategoryName() {
return this.categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "User {category id=" + id + ", category name='" + categoryName + "', description='" + description + "'}";
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
package com.example.demo.controllers;
import java.util.ArrayList;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.service.CategoryService;
import com.example.demo.common.ApiResponse;
import com.example.demo.model.Category;
#RestController
#RequestMapping("category")
public class CategoryController {
#Autowired
private CategoryService categoryService;
#PostMapping("")
public ResponseEntity<ApiResponse> storeCategory(#Valid #RequestBody Category category) {
categoryService.saveCategory(category);
ArrayList<String> message = new ArrayList<String>();
message.add("Category is added successfully");
return new ResponseEntity<ApiResponse>(new ApiResponse(true, message), HttpStatus.OK);
}
}
package com.example.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.example.demo.model.Category;
import com.example.demo.repository.CategoryRepository;
#Service
public class CategoryService {
#Autowired
private CategoryRepository categoryRepository;
public void saveCategory(Category category) {
// categoryRepository.saveAndFlush(category);
}
}
package com.example.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.model.Category;
#Repository("categoryRepository")
public interface CategoryRepository extends JpaRepository<Category, Integer> {
Category findByCategoryName(String categoryName);
}
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#EnableJpaRepositories
#ComponentScan(basePackages = { "com.example.demo.model.*" })
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
how to solve this error?
I ran the program but it showed this error.
Try adding this tag #EnableJpaRepositories in your MainApplication class and #ComponentScan(basePackages = {
"your entities package.*"
}
I am trying to create a CRUD application using Spring-boot and Mongo DB.
I am getting error the in the update and delete operations
During Delete, there is a timestamp error showing and on update a new object is getting created instead of updating the existing object. I have attached the controller and service layer codes.
Can anyone please find a solution for this.
Controller Layer
package com.springrest.springrest.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.springrest.springrest.entities.Course;
import com.springrest.springrest.services.CourseService;
#CrossOrigin
#RestController
#RequestMapping("/api")
public class MyController {
#Autowired
private CourseService courseService;
#GetMapping("/courses")
public ResponseEntity<?> getCourses(){
return ResponseEntity.ok(this.courseService.GetCourses());
}
#PostMapping("/courses")
public ResponseEntity<?> addCourse(#RequestBody Course course)
{
Course save=this.courseService.addCourse(course);
return ResponseEntity.ok(save);
}
#GetMapping("/courses/{courseId}")
public ResponseEntity<?> getCourse(#PathVariable String courseId ){
Optional<Course> save=this.courseService.getCourse(Integer.parseInt(courseId));
return ResponseEntity.ok(save);
}
#PutMapping("/courses/{courseId}")
public ResponseEntity<?> updateCourse(#PathVariable String courseId,
#RequestBody Course course)
{
Optional<Course> save=Optional.ofNullable(this.courseService.updateCourse(Integer.parseInt
(courseId),course));
return ResponseEntity.ok(save);
}
#DeleteMapping("/courses/{courseId}")
public void deleteCourse(#PathVariable String courseId)
{
this.courseService.deleteCourse(Integer.parseInt(courseId));
//return ResponseEntity.ok(this.courseService.deleteCourse(Integer.parseInt(courseId)));
}
}
Service Layer
package com.springrest.springrest.services;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.springrest.springrest.entities.Course;
import com.springrest.springrest.repository.CourseRepository;
#Service
public class CourseServiceimpl implements CourseService
{
#Autowired
private CourseRepository userlist;
public List<Course> GetCourses() {
return this.userlist.findAll();
}
public Course addCourse(Course course) {
return this.userlist.save(course);
}
public Optional<Course> getCourse(int courseId)
{
Optional<Course> c=this.userlist.findById(courseId);
return c;
}
#Override
public Course updateCourse(int courseId, Course course)
{
Course c=this.userlist.findById(courseId).get();
c.setId(course.getId());
c.setTitle(course.getTitle());
c.setDescription(course.getDescription());
return this.userlist.save(c);
}
#Override
public void deleteCourse(int courseId)
{
//Course c= this.userlist.findById(courseId).get();
this.userlist.deleteById(courseId);
}
}
Entity Layer
package com.springrest.springrest.entities;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
#Document(collection="Course")
public class Course {
#Field( name="id")
private int id;
#Field(name="title")
private String title;
#Field(name="description")
private String description;
public Course(int id, String title, String description) {
super();
this.id = id;
this.title = title;
this.description = description;
}
public Course() {
super();
}
#Override
public String toString() {
return "Course [id=" + id + ", title=" + title + ", description=" + description + "]";
}
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 String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
This is the error I am getting on a Delete Request
{
"timestamp": "2022-11-09T18:45:58.630+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/api/courses/147"
}
Are you getting an error in get and save operations? Because although you inject CourseService in controller, you did not override get and save operations methods in CourseServiceimpl class.
I finished creating a simple Spring-boot project in which I can enter users and through the Get command it returns me the name (from a list of identical names) with the oldest entry date. Unfortunately, every time I ask for Get it returns this ERROR:
D:\>curl -G localhost:8080/demo/first?=Biagio
{"timestamp":"2020-10-04T22:46:35.996+00:00","status":404,"error":"Not Found","message":"","path":"/demo/first"}
And to each of my POST / Add requests like this ERROR:
D:\>curl localhost:8080/demo/add -d name=Giovanni -d email=giovanni#gmail.com -d surname=Jackie
{"timestamp":"2020-10-04T22:40:51.928+00:00","status":404,"error":"Not Found","message":"","path":"/demo/add"}
Below I enter the interested parties of my project to try to get something out of it, because I have been stuck for days now
AccessingDataMysqlApplication.java
package com.example.accessingdatamysql;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class AccessingDataMysqlApplication {
public static void main(String[] args) {
SpringApplication.run(AccessingDataMysqlApplication.class, args);
}
}
MainController.java
package com.example.accessingdatamysql.rest;
import javax.persistence.NoResultException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.service.UserService;
#RestController
#RequestMapping("/demo")
public class MainController {
#Autowired
private UserService userService;
#Transactional
//#RequestMapping(value = "/add/", method = RequestMethod.POST)
#PostMapping(path="/demo/add")
public String addNewUser(#PathVariable("name") String name, #PathVariable("email") String email,
#PathVariable("surname") String surname) {
UserDto n = new UserDto();
n.setName(name);
n.setSurname(surname);
n.setEmail(email);
userService.create(n);
return "User Saved in DB";
}
#SuppressWarnings({ "rawtypes", "unchecked" })
//#RequestMapping(value = "/fetchUser/{name}", method = RequestMethod.GET)
#GetMapping("/demo/first")
public ResponseEntity<UserDto> fetchUser(#PathVariable("name") String name) {
System.out.println(name);
try {
UserDto namefound = userService.findFirstByName(name);
System.out.println("Name found");
ResponseEntity<UserDto> user = new ResponseEntity<UserDto>(namefound, HttpStatus.OK);
return user;
} catch(NoResultException ne) {
System.out.println("User not found");
return new ResponseEntity("User not found with name : " + name, HttpStatus.NOT_FOUND);
}
}
}
UserService.java
package com.example.accessingdatamysql.service;
import org.springframework.stereotype.Service;
import com.example.accessingdatamysql.model.UserDto;
#Service
public interface UserService {
UserDto findFirstByName(String name);
void create(UserDto user);
}
UserServiceImpl.java
package com.example.accessingdatamysql.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.model.UserEntity;
import com.example.accessingdatamysql.repo.UserRepository;
import com.example.accessingdatamysql.util.UserMapper;
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserRepository userRepository;
#Autowired
UserMapper mapper;
#Override
public UserDto findFirstByName(String name) {
UserEntity entity = userRepository.findFirstByName(name);
return mapper.toDtoMapper(entity);
}
#Override
public void create(UserDto user) {
UserEntity entity = mapper.toEntityMapper(user);
userRepository.create(entity);
}
}
UserMapper.java
package com.example.accessingdatamysql.util;
import org.mapstruct.Mapper;
import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.model.UserEntity;
#Mapper(componentModel = "spring")
public interface UserMapper {
public UserEntity toEntityMapper (UserDto user);
public UserDto toDtoMapper (UserEntity userEntity);
}
UserRepository.java
package com.example.accessingdatamysql.repo;
import org.springframework.stereotype.Repository;
import com.example.accessingdatamysql.model.UserEntity;
#Repository
public interface UserRepository {
UserEntity findFirstByName(String name);
void create(UserEntity entity);
}
UserRepositoryImpl.java
package com.example.accessingdatamysql.service;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Component;
import com.example.accessingdatamysql.model.UserEntity;
import com.example.accessingdatamysql.repo.UserRepository;
#Component
public class UserRepositoryImpl implements UserRepository {
private final EntityManager em;
public UserRepositoryImpl(EntityManager entityManager) {
this.em = entityManager;
}
#Override
public UserEntity findFirstByName(String name) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<UserEntity> criteria = builder.createQuery(UserEntity.class);
Root<UserEntity> root = criteria.from(UserEntity.class);
criteria.select(root).where(builder.equal(root.get("name"), name));
criteria.orderBy(builder.asc(root.get("timestamp")));
TypedQuery<UserEntity> query = em.createQuery(criteria).setMaxResults(1);
return query.getSingleResult();
}
#Override
// per la creazione//
public void create(UserEntity entity) {
em.persist(entity);
}
}
UserDto.java
package com.example.accessingdatamysql.model;
import java.io.Serializable;
import java.sql.Timestamp;
public class UserDto implements Serializable {
/**
*
*/
private static final long serialVersionUID = -7621330660870602403L;
/**
*
*/
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
private Timestamp timestamp;
private String email;
private String surname;
}
If you need I can also insert User.java and the pom, but the pom has no problems as the dependencies are all correct.
You have an additional demo in your path descriptions for GET and POST methods, you should remove it:
#GetMapping("/demo/first")
#PostMapping(path = "/demo/first")
It should be :
#GetMapping("/first")
#PostMapping(path = "/first")
This because you have already defined demo in the RequestMapping annotation in the class level.
The Java Rest Api prints on http://localhost:8080/books
[{},{},{}]
instead of the booklist object. I use a main method a book_controller and a book model. Firstly I add a couple of books in the list in the method getbooks() and then I return them as a list.
Why does this happen?
application.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
#SpringBootApplication (exclude = SecurityAutoConfiguration.class)
public class Lab6NosApplication {
public static void main(String[] args) {
SpringApplication.run(Lab6NosApplication.class, args);
}
}
Book_controller.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import ch.qos.logback.classic.Logger;
import net.minidev.json.JSONArray;
#Controller
public class Book_controller implements ErrorController, Serializable {
#GetMapping("books")
public #ResponseBody List<book> getbooks() {
List<book> bookList = new ArrayList<book>();
bookList.add(new book(1,"lokesh","gupta"));
bookList.add(new book(2,"lokesh","gupta"));
bookList.add(new book(3,"lokesh","gupta"));
java.lang.System.out.print(bookList);
return bookList;
}
#RequestMapping("/error")
#ResponseBody
public String handleError(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");
return String.format("<html><body><h2>Error Page</h2><div>Status code: <b>%s</b></div>"
+ "<div>Exception Message: <b>%s</b></div><body></html>",
statusCode, exception==null? "N/A": exception.getMessage());
}
#Override
public String getErrorPath() {
return "/error";
}
}
Book.java
public class Book {
public Book(Integer id, String title, String author) {
super();
this.id = id;
this.title = title;
this.author = author;
}
private Integer id;
private String title;
private String author;
//getters and setters
#Override
public String toString() {
return "Employee [id=" + id + ", title=" + title
+ ", author=" + author + "]";
}
}
Thank you!
You see it empty because your Book class doesn't have public getters or properties, so the serializer won't be able to access it's values.
Add getters to your Book class:
public Integer getId(){
return this.id;
}
public String getTitle(){
return this.title;
}
public String getAuthor(){
return this.author;
}
You can also improve your code, with better naming such as BookController instead of Book_controller. Have a look at java naming conventions.
Finally, take a look at a #RestController. If you use #RestController, you don't need to have #ResponseBody
im using UUID in my application as Primary Key i have problem whene find data by id give me exception error.
this is Note Class
package com.example.demo.model;
import java.util.Date;
import java.util.UUID;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
#AutoConfigurationPackage
#Entity
public class Note {
#Id
#GeneratedValue( strategy = GenerationType.AUTO,generator = "pg-uuid")
#GenericGenerator(name = "pg-uuid",strategy = "uuid2")
private UUID id;
private String title;
private String text;
#ManyToOne(fetch = FetchType.LAZY,cascade = CascadeType.MERGE)
private Notebook notebook;
private Date lastModifiedOn;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Notebook getNotebook() {
return notebook;
}
public void setNotebook(Notebook notebook) {
this.notebook = notebook;
}
public Date getLastModifiedOn() {
return lastModifiedOn;
}
public void setLastModifiedOn(Date lastModifiedOn) {
this.lastModifiedOn = lastModifiedOn;
}
this is NoteController
package com.example.demo.controller;
import java.text.ParseException;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.MyMapper;
import com.example.demo.Repository.NoteBookRepository;
import com.example.demo.Repository.NoteRepository;
import com.example.demo.model.Note;
import com.example.demo.model.Notebook;
import com.example.demo.view.NoteViewModle;
#RestController
#RequestMapping("/api/note")
#CrossOrigin
public class NoteController {
#Autowired
NoteRepository noteRepository;
#Autowired
NoteBookRepository notebookRepository;
#Autowired
MyMapper maper;
#GetMapping("/all")
public List<NoteViewModle> getAllNote(){
List<Note> list = this.noteRepository.findAll();
List<NoteViewModle> noteViewModles = (List<NoteViewModle>) list.stream().map(note ->maper.convertToNodeViewModel(note)).collect(Collectors.toList());
return noteViewModles;
}
#GetMapping("/byId/{id}")
public NoteViewModle getNotreById(#PathVariable("id") UUID id) {
System.out.println(id);
Note note = this.noteRepository.findById(id).orElse(null);
if(note == null)
{
System.out.println("In If");
throw new EntityNotFoundException();
}
NoteViewModle modle = maper.convertToNodeViewModel(note);
return modle;
}
#GetMapping("/byNoteBook/{notebookId}")
public List<Note> getNotesByNoteBook(#PathVariable("notebookId") String id)
{
return this.noteRepository.findAllByNotebook(this.notebookRepository.findById(UUID.fromString(id)).orElse(new Notebook()));
}
#PostMapping("/add")
public Note save(#RequestBody NoteViewModle modle)
{
Note note = maper.convertToNodeEntity(modle);
return this.noteRepository.save(note);
}
#DeleteMapping("/deltebyId/{id}")
public void deleteNoteById(#PathVariable("id") String id) {
this.noteRepository.deleteById(UUID.fromString(id));
}
}
this is MyMapper to mape the json data
package com.example.demo;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.example.demo.Repository.NoteBookRepository;
import com.example.demo.model.Note;
import com.example.demo.model.Notebook;
import com.example.demo.view.NoteViewModle;
import com.example.demo.view.NotebookViewModel;
#Component
public class MyMapper {
#Autowired
NoteBookRepository bookRepository;
public NoteViewModle convertToNodeViewModel(Note entity) {
NoteViewModle modle = new NoteViewModle();
modle.setId(entity.getId().toString());
modle.setTitle(entity.getTitle());
modle.setText(entity.getText());
modle.setNoteBookId(entity.getNotebook().getId().toString());
modle.setData(entity.getLastModifiedOn().toString());
return modle;
}
public Note convertToNodeEntity(NoteViewModle viewModle) {
Note note = new Note();
note.setTitle(viewModle.getTitle());
note.setText(viewModle.getText());
//note.setLastModifiedOn(new SimpleDateFormat("dd/MM/yyyy").parse(viewModle.getData()));
//Notebook notebook = bookRepository.findById(UUID.fromString(viewModle.getId())).orElse(new Notebook());
return note;
}
public NotebookViewModel convertToNotebookViewModel(Notebook entity)
{
NotebookViewModel viewModel = new NotebookViewModel();
viewModel.setId(entity.getId().toString());
viewModel.setName(entity.getName());
viewModel.setNumOfNote(entity.getNotes().size());
return viewModel;
}
public Notebook convertToNotebookEntity(NotebookViewModel model) {
Notebook notebook = new Notebook();
notebook.setId(UUID.fromString(model.getId()));
notebook.setName(model.getName());
return notebook;
}
}
this is repositry class
package com.example.demo.Repository;
import java.util.List;
import java.util.UUID;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.model.Note;
import com.example.demo.model.Notebook;
#Repository
public interface NoteRepository extends JpaRepository<Note, UUID> {
List<Note> findAllByNotebook(Notebook notebook);
}
this is error is appears org.springframework.dao.EmptyResultDataAccessException: No class com.example.demo.model.Notebook entity with id 7e83b195-eb81-4752-a6fa-a5206c9eb1c6 exists!