i was trying to develop a web app using springmvc when i keep getting a NullPointerException
Utilisateur.java :
import java.util.HashSet;
import java.util.Set;
import org.springframework.stereotype.Component;
/**
*
* #author admin
*/
//#Component
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* Utilisateur generated by hbm2java
*/
#Entity
#Table(name = "utilisateur")
public class Utilisateur implements java.io.Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer idUser;
private String nom;
private String prenom;
private String profession;
private String photo;
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="idUser")
private Set<Post> posts;
public Utilisateur() {
}
public Utilisateur(String nom, String prenom, String profession, String photo, Set posts) {
this.nom = nom;
this.prenom = prenom;
this.profession = profession;
this.photo = photo;
this.posts = posts;
}
public Integer getIdUser() {
return this.idUser;
}
public void setIdUser(Integer idUser) {
this.idUser = idUser;
}
public String getNom() {
return this.nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return this.prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getProfession() {
return this.profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
public String getPhoto() {
return this.photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public Set getPosts() {
return this.posts;
}
public void setPosts(Set posts) {
this.posts = posts;
}
}
my userController.java:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
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.portlet.ModelAndView;
#Controller
public class UserController {
#RequestMapping(value="/listUtilisateur/",method=RequestMethod.GET)
public ModelAndView showUsers(){
ModelAndView model=new ModelAndView();
model.addObject("msg","hello");
System.out.println("nisrine khan");
return model;
}
#RequestMapping(value="/CreateUser",method=RequestMethod.GET)
public ModelAndView FormUser(){
ModelAndView model=new ModelAndView("CreateUser");
model.addObject("msg","msg");
System.out.println("nisrine khan");
return model;
}
#RequestMapping(value="/editUser",method=RequestMethod.GET)
public ModelAndView EditUser(){
ModelAndView model=new ModelAndView("CreateUser1");
model.addObject("msg","msg");
System.out.println("nisrine khan");
return model;
}
}
my formusercontroller.java:
FormUserController.java:
import com.ensat.service.UtilisateurServiceImp;
import com.ensat.model.Utilisateur;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class FormUserController {
private UtilisateurServiceImp userService;
#Autowired(required = true)
public FormUserController(UtilisateurServiceImp USI) {
this.userService = USI;
}
private Map<Integer, Utilisateur> UtilisateurMap = new HashMap<>();
#RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String submit(
#ModelAttribute("Utilisateur") Utilisateur utilisateur,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error";
}
model.addAttribute("nom", utilisateur.getNom());
model.addAttribute("id", utilisateur.getIdUser());
model.addAttribute("prenom", utilisateur.getPrenom());
model.addAttribute("profession", utilisateur.getProfession());
model.addAttribute("photo", utilisateur.getPhoto());
model.addAttribute("msg", "Welcome to Island!");
model.addAttribute("utilisateur", utilisateur);
UtilisateurMap.put(utilisateur.getIdUser(), utilisateur);
if (utilisateur.getIdUser() == 0) {
//new person, add it
this.userService.addService(utilisateur);
} else {
//existing person, call update
this.userService.updateService(utilisateur);
}
return "listUser";
}
#RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
public String editUtilisateur(
#ModelAttribute("Utilisateur") Utilisateur utilisateur,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error";
}
model.addAttribute("nom", utilisateur.getNom());
model.addAttribute("id", utilisateur.getIdUser());
model.addAttribute("prenom", utilisateur.getPrenom());
model.addAttribute("profession", utilisateur.getProfession());
model.addAttribute("photo", utilisateur.getPhoto());
UtilisateurMap.put(utilisateur.getIdUser(), utilisateur);
this.userService.updateService(utilisateur);
return "listUser";
}
#RequestMapping("/remove/{id}")
public String removeUtilisateur(#PathVariable("idUser") int id) {
this.userService.removeService(id);
return "listUser";
}
}
my utilisateurDAO.java:
import com.ensat.model.Utilisateur;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
#Repository
public class UtilisateurDao implements IntDao<Utilisateur> {
private static final Logger logger = LoggerFactory.getLogger(UtilisateurDao.class);
#Autowired
#Qualifier("sessionFactory")
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}
#Override
public boolean saveUser(Utilisateur p) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(p);
logger.info("Utilisateur enregistré avec succés , Utilisateur Details=" + p);
return true;
}
#Override
public boolean UpdateUser(Utilisateur p) {
Session session = this.sessionFactory.getCurrentSession();
session.update(p);
logger.info("Utilisateur mis à jour avec succés , Utilisateur Details=" + p);
return true;
}
#Override
public void deleteUser(Integer userId) {
Session session = this.sessionFactory.getCurrentSession();
Utilisateur p = (Utilisateur) session.load(Utilisateur.class, userId);
if (null != p) {
session.delete(p);
}
logger.info("Utilisateur supprimée avec succés , Utilisateur details=" + p);
}
#SuppressWarnings("unchecked")
#Override
public List<Utilisateur> getAllelements() {
Session session = this.sessionFactory.getCurrentSession();
List<Utilisateur> UtilisateursList = session.createQuery("from Utilisateur").list();
for (Utilisateur p : UtilisateursList) {
logger.info("Utilisateur List::" + p);
}
return UtilisateursList;
}
#Override
public Utilisateur listUserById(Integer userId) {
Session session = this.sessionFactory.getCurrentSession();
Utilisateur p = (Utilisateur) session.load(Utilisateur.class, userId);
logger.info("Utilisateur loaded successfully, Utilisateur details=" + p);
return p;
}
}
and the error is :
org.apache.catalina.core.ApplicationContext.log Error during mapping
java.lang.NullPointerException at
org.apache.catalina.mapper.Mapper.internalMapWrapper(Mapper.java:842)
at org.apache.catalina.mapper.Mapper.map(Mapper.java:712) at
org.apache.catalina.core.ApplicationContext.getRequestDispatcher(ApplicationContext.java:499)
at
org.apache.catalina.core.ApplicationContextFacade.getRequestDispatcher(ApplicationContextFacade.java:221)
at
org.apache.catalina.connector.Request.getRequestDispatcher(Request.java:1338)
at
org.apache.catalina.connector.RequestFacade.getRequestDispatcher(RequestFacade.java:613)
at
javax.servlet.ServletRequestWrapper.getRequestDispatcher(ServletRequestWrapper.java:291)
at
org.springframework.web.servlet.view.InternalResourceView.getRequestDispatcher(InternalResourceView.java:281)
at
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:189)
at
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:267)
at
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1221)
at
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1005)
at
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:952)
at
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) at
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Related
**
2021-11-26 20:30:57.375 WARN 11700 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookRestController': Unsatisfied dependency expressed through field 'bookService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookServiceImpl': Unsatisfied dependency expressed through field 'bookService'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'bookServiceImpl': Requested bean is currently in creation: Is there an unresolvable circular reference?
2021-11-26 20:30:57.376 INFO 11700 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-11-26 20:30:57.382 INFO 11700 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2021-11-26 20:30:57.393 INFO 11700 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2021-11-26 20:30:57.396 INFO 11700 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2021-11-26 20:30:57.410 INFO 11700 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-11-26 20:30:57.437 ERROR 11700 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter:
**
APPLICATION FAILED TO START
Description:
The dependencies of some of the beans in the application context form a cycle:
bookRestController (field private BookAuthorManyToManyRelationship.service.BookService BookAuthorManyToManyRelationship.Rest.BookRestController.bookService)
┌─────┐
| bookServiceImpl (field private BookAuthorManyToManyRelationship.service.BookService BookAuthorManyToManyRelationship.serviceImpl.BookServiceImpl.bookService)
└─────┘
Action:
Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.*
BasicProjectApplication.java
```package BookAuthorManyToManyRelationship;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class BasicProjectApplication {
public static void main(String[] args) {
SpringApplication.run(BasicProjectApplication.class, args);
}
}```
**AuthorDAO.java**
```package BookAuthorManyToManyRelationship.dao;
import java.util.List;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
public interface AuthorDAO {
public Author findById(int id);
public List<Book> findListOfBookWrittenByAuthor();
public void deleteById(int id);
public void save(Author author);
}```
**BookDAO.java**
```package BookAuthorManyToManyRelationship.dao;
import java.util.List;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
public interface BookDAO {
public Book findById(int id);
public List<Author> findListOfAuthorWhoHasWrittenThisBook();
public void deleteById(int id);
public void save(Book book);
}```
**AuthorDAOImpl.java**
```package BookAuthorManyToManyRelationship.daoImpl;
import java.util.List;
import javax.persistence.EntityManager;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import BookAuthorManyToManyRelationship.dao.AuthorDAO;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
#Repository
public class AuthorDAOImpl implements AuthorDAO {
#Autowired
private EntityManager entityManager;
#Override
public Author findById(int id) {
Session session = entityManager.unwrap(Session.class);
Author author = session.get(Author.class, id);
return author;
}
#Override
public List<Book> findListOfBookWrittenByAuthor() {
Session session = entityManager.unwrap(Session.class);
Query<Book> theQuery = session.createQuery("from Book",Book.class);
List<Book> book = theQuery.getResultList();
return book;
}
#Override
public void deleteById(int id) {
Session session = entityManager.unwrap(Session.class);
Query theQuery = session.createQuery("delete from Author where author_id=:theid");
theQuery.setParameter("theid", id);
theQuery.executeUpdate();
}
#Override
public void save(Author author) {
Session session = entityManager.unwrap(Session.class);
session.saveOrUpdate(author);
}
}```
**BookDAOImpl.java**
```package BookAuthorManyToManyRelationship.daoImpl;
import java.util.List;
import javax.persistence.EntityManager;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import BookAuthorManyToManyRelationship.dao.BookDAO;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
#Repository
public class BookDAOImpl implements BookDAO {
#Autowired
private EntityManager entityManager;
#Override
public Book findById(int id) {
Session session = entityManager.unwrap(Session.class);
Book b = session.get(Book.class, id);
return b;
}
#Override
public List<Author> findListOfAuthorWhoHasWrittenThisBook() {
Session session = entityManager.unwrap(Session.class);
Query<Author> q = session.createQuery("from Author",Author.class);
List<Author> author = q.getResultList();
return author;
}
#Override
public void deleteById(int id) {
Session session = entityManager.unwrap(Session.class);
Query q = session.createQuery("delete from Book where book_id:=theid");
q.setParameter("theid", id);
q.executeUpdate();
}
#Override
public void save(Book book) {
Session session = entityManager.unwrap(Session.class);
session.saveOrUpdate(book);
}
}```
**Address.java**
```package BookAuthorManyToManyRelationship.entity;
import javax.persistence.Embeddable;
#Embeddable
public class Address {
String street;
String city;
String country;
public Address(String street, String city, String country) {
super();
this.street = street;
this.city = city;
this.country = country;
}
public Address() {
super();
// TODO Auto-generated constructor stub
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}```
**Author.java**
```package BookAuthorManyToManyRelationship.entity;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="author")
public class Author {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
int id;
String authorName;
Address address;
#ManyToMany(cascade = CascadeType.ALL)
List<Book> book;
public Author() {
super();
// TODO Auto-generated constructor stub
}
public Author(int id, String authorName,Address address,List<Book> book) {
super();
this.id = id;
this.authorName = authorName;
this.address = address;
this.book = book;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<Book> getBook() {
return book;
}
public void setBook(List<Book> book) {
this.book = book;
}
}```
**Book.java**
```package BookAuthorManyToManyRelationship.entity;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="book")
public class Book {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
int id;
String book_name;
String subject;
#ManyToMany(cascade = CascadeType.ALL)
List<Author> author;
public Book() {
super();
// TODO Auto-generated constructor stub
}
public Book(int id, String book_name, String subject, List<Author> author) {
super();
this.id = id;
this.book_name = book_name;
this.subject = subject;
this.author = author;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBook_name() {
return book_name;
}
public void setBook_name(String book_name) {
this.book_name = book_name;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public List<Author> getAuthor() {
return author;
}
public void setAuthor(List<Author> author) {
this.author = author;
}
}```
**AuthorRestController**
```package BookAuthorManyToManyRelationship.Rest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
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 BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
import BookAuthorManyToManyRelationship.service.AuthorService;
#RestController
#RequestMapping("/welcome")
public class AuthorRestController {
#Autowired
private AuthorService authorService;
#GetMapping("/author/{id}")
public Author getAuthorById(#PathVariable int id )
{
return authorService.findById(id);
}
#GetMapping("/book")
public List<Book> getBook()
{
return authorService.findListOfBookWrittenByAuthor();
}
#PostMapping("/saveAuthor")
public void setAuthor(#RequestBody Author author)
{
authorService.save(author);
}
}```
**BookRestController.java**
```package BookAuthorManyToManyRelationship.Rest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
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 BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
import BookAuthorManyToManyRelationship.service.BookService;
#RestController
#RequestMapping("/abc")
public class BookRestController {
#Autowired
private BookService bookService;
#GetMapping("/book/{id}")
public Book getBookById(#PathVariable int id )
{
return bookService.findById(id);
}
#GetMapping("/author")
public List<Author> getAuthor()
{
return bookService.findListOfAuthorWhoHasWrittenThisBook();
}
#PostMapping("/saveBook")
public void setBook(#RequestBody Book book)
{
bookService.save(book);
}
}```
**AuthorService.java**
```package BookAuthorManyToManyRelationship.service;
import java.util.List;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
public interface AuthorService {
public Author findById(int id);
public List<Book> findListOfBookWrittenByAuthor();
public void deleteById(int id);
public void save(Author author);
}```
**BookService.java**
```package BookAuthorManyToManyRelationship.service;
import java.util.List;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
public interface BookService {
public Book findById(int id);
public List<Author> findListOfAuthorWhoHasWrittenThisBook();
public void deleteById(int id);
public void save(Book book);
}```
**AuthorServiceImpl.java**
```package BookAuthorManyToManyRelationship.serviceImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import BookAuthorManyToManyRelationship.dao.AuthorDAO;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
import BookAuthorManyToManyRelationship.service.AuthorService;
#Service
public class AuthorServiceImpl implements AuthorService {
#Autowired
private AuthorDAO authorDAO;
#Override
#Transactional
public Author findById(int id) {
return authorDAO.findById(id);
}
#Override
#Transactional
public List<Book> findListOfBookWrittenByAuthor() {
return authorDAO.findListOfBookWrittenByAuthor();
}
#Override
#Transactional
public void deleteById(int id) {
authorDAO.deleteById(id);
}
#Override
#Transactional
public void save(Author author) {
authorDAO.save(author);
}
}```
**BookServiceImpl.java**
```package BookAuthorManyToManyRelationship.serviceImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import BookAuthorManyToManyRelationship.entity.Author;
import BookAuthorManyToManyRelationship.entity.Book;
import BookAuthorManyToManyRelationship.service.BookService;
#Service
public class BookServiceImpl implements BookService {
#Autowired
private BookService bookService;
#Override
#Transactional
public Book findById(int id) {
return bookService.findById(id);
}
#Override
#Transactional
public List<Author> findListOfAuthorWhoHasWrittenThisBook() {
return bookService.findListOfAuthorWhoHasWrittenThisBook();
}
#Override
#Transactional
public void deleteById(int id) {
bookService.deleteById(id);
}
#Override
#Transactional
public void save(Book book) {
bookService.save(book);
}
}
```
here is cause of your problem
#Service
public class BookServiceImpl implements BookService {
#Autowired
private BookService bookService
I am not able to understand why do you have reference of BookService inside it's own implementation, my best guess you wanted to add BookDAO here.
I am new to spring-data, I have this error java.lang.String cannot be cast to com.example.accessingdatamysql.User and do not know how to fix it! I add the various relevant parts of my code.
The method should output the oldest entry (via timestamp) by name.
Main.Controller
package com.example.accessingdatamysql;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
#RequestMapping(path="/demo")
public class MainController {
#Autowired
private UserRepository userRepository;
#Transactional
#PostMapping(path="/add")
public #ResponseBody String addNewUser (#RequestParam String name,
#RequestParam String email,#RequestParam String surname)
{
User n = new User();
n.setName(name);
n.setSurname(surname);
n.setEmail(email);
userRepository.create(n);
return "Saved";
}
#GetMapping(path="first")
User one(#RequestParam String name) {
return userRepository.findFirstByName(name);
}
}
User.java
package com.example.accessingdatamysql;
import java.sql.Timestamp;
import java.time.Instant;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
public String name;
private String email;
private String surname;
#Column(name="stmp", columnDefinition = "TIMESTAMP (6)")
Timestamp timestamp = Timestamp.from(Instant.now());
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
public Timestamp getTimestamp() {
return timestamp;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
RepoImpl.java
package com.example.accessingdatamysql;
import java.util.List;
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;
#Component
public class UserRepositoryImpl implements UserRepository {
private final EntityManager em;
public UserRepositoryImpl(EntityManager entityManager) {
this.em = entityManager;
}
#Override
public User findFirstByName(String name) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<User> criteria = builder.createQuery(User.class);
Root<User> root = criteria.from(User.class);
criteria.select(root.get("name"));
criteria.orderBy(builder.asc(root.get("timestamp")));
TypedQuery<User> query = em.createQuery(criteria).setMaxResults(1);
return query.getSingleResult();
}
#Override
// per la creazione//
public void create(User entity) {
em.persist(entity);
}
}
ERROR
[Request processing failed; nested exception is java.lang.ClassCastException: java.lang.String cannot be cast to com.example.accessingdatamysql.User] with root cause
java.lang.ClassCastException: java.lang.String cannot be cast to com.example.accessingdatamysql.User
at com.example.accessingdatamysql.UserRepositoryImpl.findFirstByName(UserRepositoryImpl.java:35) ~[classes!/:0.0.1-SNAPSHOT]
If you meant to find User by name, you should have set the filter parameter not in criteria.select but in criteria.where:
public User findFirstByName(String name) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<User> criteria = builder.createQuery(User.class);
Root<User> root = criteria.from(User.class); // root is User
criteria.select(root).where(builder.equal(root.get("name"), name));
criteria.orderBy(builder.asc(root.get("timestamp")));
TypedQuery<User> query = em.createQuery(criteria).setMaxResults(1);
return query.getSingleResult();
}
While criteria.select(root.get("name")); implies that only column "name" is selected and returned, that is the name of the first user should be returned.
If such information is needed, it may be retrieved in the following way:
public String findFirstUserName() {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<String> criteria = builder.createQuery(String.class);
Root<User> root = criteria.from(User.class); // root is User
criteria.select(root.get("name")); // getting name
criteria.orderBy(builder.asc(root.get("timestamp"))); // of the first/earliest user
TypedQuery<String> query = em.createQuery(criteria).setMaxResults(1);
return query.getSingleResult();
}
Do just like the error says -
CriteriaQuery<String> criteria = builder.createQuery(String.class);
instead of
CriteriaQuery<User> criteria = builder.createQuery(User.class);
Read more here Reference
I went to develop an application to manage students in a university, I am looking for how to find students in relation to a date entered for that I have developed the following code lines:
1- Model student.java
package com.avatar.model;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
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.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.JoinColumn;
#Entity
#Table(name = "Students")
public class Student{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String nom;
private String prenom;
private String numTel;
private String mail;
#Temporal(TemporalType.DATE)
private Date dateCurrent;
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
#JoinTable(name = "student_techno",
joinColumns = { #JoinColumn(name = "student_id") },
inverseJoinColumns = { #JoinColumn(name = "techno_id") })
private Set<Techno> techno = new HashSet<>();
public Student() {
}
#SuppressWarnings("unchecked")
public Student(String nom, String prenom,String numTel, String mail, Date dateCurrent,
) {
super();
this.nom = nom;
this.prenom = prenom;
this.numTel = numTel;
this.mail = mail;
this.dateCurrent = dateCurrent;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getNumTel() {
return numTel;
}
public void setNumTel(String numTel) {
this.numTel = numTel;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getdateCurrent() {
return dateCurrent;
}
public void setdateCurrent(Date dateCurrent) {
this.dateCurrent = dateCurrent;
}
#Override
public String toString() {
return "Student[nom=" + nom + ", prenom=" + prenom + ", numTel=" + numTel + ", mail="
+ mail + ", dateCurrent=" + dateCurrent+ "]";
}
}
2- Controller
package com.avatar.web;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.CrossOrigin;
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.avatar.dao.StudentDao;
import com.avatar.model.Student;
#CrossOrigin(origins = "http://localhost:4200")
#RestController
#RequestMapping("/avatar")
public class StudentController {
#Autowired
StudentDao studentdao;
#GetMapping(value = "/all-students")
public List<Student> listeDesStudent() {
List<Student> students= studentdao.findAll();
if (students.isEmpty())
throw new ProductNotFoundException("No student is registered in the database");
return students;
}
#GetMapping(value = "/all-students/dateCurrent/{dateCurrent}")
public List<Student> viewStudent(#PathVariable("dateCurrent") #DateTimeFormat(pattern = "yyyy-MM-dd") Date dateCurrent) {
Calendar c = Calendar.getInstance();
c.setTime(dateCurrent);
c.add(Calendar.DATE, 1);
dateCurrent = c.getTime();
return studentdao.findByDate(dateCurrent);
}
#GetMapping(value = "/all-students /techno/{nomTechno}")
List<Student > viewStudent(#PathVariable("nomTechno") String nomTechno) {
return studentdao.findDistinctByTechnoNomTechno(nomTechno);
}
#PostMapping(value = "/add-student")
public Student addStudent(#RequestBody Student student) {
Student studentAdded= studentdao.save(Student);
return studentAdded;
}
}
3- DAO
package com.avatar.dao;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.avatar.model.Student;
#Repository
public interface StudentDao extends JpaRepository<Student, String> {
List<Student> findByDate(Date dateCurrent);
List<> findDistinctByTechnoNomTechno(String nomTechno);
}
4- applications.properties
server.port= 8080
# MySQL Properties
spring.jpa.show-sql = true
spring.datasource.url= jdbc:mysql://localhost:3306/avatar?serverTimezone=UTC&useLegacyDatetimeCode=false
spring.datasource.username=*****
spring.datasource.password=*****
# Hibernate Properties
spring.jpa.hibernate.ddl-auto=update
in my console i have:
Failed to create query for method public abstract java.util.List com.avatar.dao.StudentDao.findByDate(java.util.Date)! No property date found for type Student!
Please update DAO as per for below mentioned changes
If the field name is dateCurrent then findByDateCurrent.
package com.avatar.dao;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.avatar.model.Student;
#Repository
public interface StudentDao extends JpaRepository<Student, String> {
List<Student> findByDateCurrent(Date dateCurrent);
List<> findDistinctByTechnoNomTechno(String nomTechno);
}
You are missing field name, in Entity class it is not the date by dateCurrent, thus your JPA should be findByDateCurrent
I have created an Entity class and when I run the application I get the above error. I have matched the code with that of the instructor and still I get the exception. Have been looking for the solution but could not resolve it. Hence, thought to post here.
The stack trace for the same:
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/spring-crm-rest] threw exception [Request processing failed; nested exception is org.hibernate.MappingException: Unknown entity: com.travelplanner.rest.entity.User] with root cause
org.hibernate.MappingException: Unknown entity: com.travelplanner.rest.entity.User
at org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:620)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1635)
at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:225)
at org.hibernate.event.internal.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:499)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:83)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:660)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:652)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:647)
at com.travelplanner.rest.dao.UserDAOImpl.saveUser(UserDAOImpl.java:45)
at com.travelplanner.rest.service.UserServiceImpl.saveUser(UserServiceImpl.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy125.saveUser(Unknown Source)
at com.travelplanner.rest.controller.UserRestController.addUser(UserRestController.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:770)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
below is the config.java
package com.travelplanner.rest.config;
import java.beans.PropertyVetoException;
import java.util.Properties;
import java.util.logging.Logger;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.mchange.v2.c3p0.ComboPooledDataSource;
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan("com.travelplanner.rest")
#PropertySource({ "classpath:persistence-mysql.properties" })
public class DemoAppConfig implements WebMvcConfigurer {
#Autowired
private Environment env;
private Logger logger = Logger.getLogger(getClass().getName());
#Bean
public DataSource myDataSource() {
// create connection pool
ComboPooledDataSource myDataSource = new ComboPooledDataSource();
// set the jdbc driver
try {
myDataSource.setDriverClass("com.mysql.jdbc.Driver");
}
catch (PropertyVetoException exc) {
throw new RuntimeException(exc);
}
// for sanity's sake, let's log url and user ... just to make sure we are reading the data
logger.info("jdbc.url=" + env.getProperty("jdbc.url"));
logger.info("jdbc.user=" + env.getProperty("jdbc.user"));
// set database connection props
myDataSource.setJdbcUrl(env.getProperty("jdbc.url"));
myDataSource.setUser(env.getProperty("jdbc.user"));
myDataSource.setPassword(env.getProperty("jdbc.password"));
// set connection pool props
myDataSource.setInitialPoolSize(getIntProperty("connection.pool.initialPoolSize"));
myDataSource.setMinPoolSize(getIntProperty("connection.pool.minPoolSize"));
myDataSource.setMaxPoolSize(getIntProperty("connection.pool.maxPoolSize"));
myDataSource.setMaxIdleTime(getIntProperty("connection.pool.maxIdleTime"));
return myDataSource;
}
private Properties getHibernateProperties() {
// set hibernate properties
Properties props = new Properties();
props.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
props.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
return props;
}
// need a helper method
// read environment property and convert to int
private int getIntProperty(String propName) {
String propVal = env.getProperty(propName);
// now convert to int
int intPropVal = Integer.parseInt(propVal);
return intPropVal;
}
#Bean
public LocalSessionFactoryBean sessionFactory(){
// create session factorys
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
// set the properties
sessionFactory.setDataSource(myDataSource());
sessionFactory.setPackagesToScan(env.getProperty("hibernate.packagesToScan"));
sessionFactory.setHibernateProperties(getHibernateProperties());
return sessionFactory;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
// setup transaction manager based on session factory
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);
return txManager;
}
}
Below is the User entity class:
package com.travelplanner.rest.entity;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="users")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name="email")
private String email;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="user_travel_plans")
private UserTravelPlans userTravelPlans;
public User() {
}
public User(int id, String firstName, String lastName, String email) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public UserTravelPlans getUserTravelPlans() {
return userTravelPlans;
}
public void setUserTravelPlans(UserTravelPlans userTravelPlans) {
this.userTravelPlans = userTravelPlans;
}
#Override
public String toString() {
return "User [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}
UserTarvelPlan.java:
package com.travelplanner.rest.entity;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="user_travel_plans")
public class UserTravelPlans {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="place")
private String place;
#Column(name="hotel")
private String hotel;
#Column(name="transport")
private String transport;
#OneToOne(mappedBy="userTravelPlans", cascade= {CascadeType.DETACH, CascadeType.MERGE,
CascadeType.PERSIST, CascadeType.REFRESH})
private User user;
public UserTravelPlans() {}
public UserTravelPlans(int id, String place, String hotel, String transport) {
this.id = id;
this.place = place;
this.hotel = hotel;
this.transport = transport;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getHotel() {
return hotel;
}
public void setHotel(String hotel) {
this.hotel = hotel;
}
public String getTransport() {
return transport;
}
public void setTransport(String transport) {
this.transport = transport;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Override
public String toString() {
return "UserTravelPlans [id=" + id + ", place=" + place + ", hotel=" + hotel + ", transport=" + transport + "]";
}
}
I am developing a project in Spring Boot Billing. I have successfully build and run this project but there is some issue.
When i am trying insert data via POST method but Browser shows POST method not supported.
Here is my controller
BillingController.java
package com.billing.controller;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.billing.model.Restaurant_billing;
import com.billing.model.Restaurant_billingDao;
import com.billing.model.billing;
import com.billing.model.billingDao;
import com.billing.model.itemDao;
import com.billing.model.tax_billing;
import com.billing.model.tax_billingDao;
#Controller
#RestController
#RequestMapping("/restaurant")
public class BillingController {
#Autowired
private itemDao itemDao;
#Autowired
private billingDao billingDao;
#Autowired
private Restaurant_billingDao restaurant_billingDao;
#Autowired
private tax_billingDao tax_billingDao;
SessionFactory sessionFactory;
Session sesion=null;
org.hibernate.Transaction tx=null;
#RequestMapping(value="/create", method = RequestMethod.POST, consumes =
MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public String R_billing(#RequestBody final Restaurant_billing r_billing[] ,HttpServletResponse response,HttpServletRequest request)
throws ServletException {
try{
billing billingObject = new billing();
billingDao.save(billingObject);
int billing_id = billingObject.getId();
tax_billing tax_billing= new tax_billing();
tax_billing.setBilling_id(billing_id);
tax_billing.setTax_amount("140");
tax_billingDao.save(tax_billing);
for(Restaurant_billing prof:r_billing){
prof.setBilling_id(billing_id);
restaurant_billingDao.save(prof);
}
}
catch(Exception ex){
return "Error creating the user: " + ex.toString();
}
return ("User profession added successfully");
}
}
Here is my model class
Restaurant_billing.java
package com.billing.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name ="billing_restaurant")
public class Restaurant_billing {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name="billing_id")
private int billing_id;
#Column(name="itemid")
private String itmeid;
#Column(name="quantity")
private String quantity;
#Column(name="billing_type")
private String billing_type;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getBilling_id() {
return billing_id;
}
public void setBilling_id(int billing_id) {
this.billing_id = billing_id;
}
public String getItmeid() {
return itmeid;
}
public void setItmeid(String itmeid) {
this.itmeid = itmeid;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getBilling_type() {
return billing_type;
}
public void setBilling_type(String billing_type) {
this.billing_type = billing_type;
}
}
No need to use #Controller use only #RestController and also assign sesion and tx values.
After that you just try the following code,
#RequestMapping(value = "/create", method = RequestMethod.POST)
public #RequestBody Restaurant_billing R_billing(final HttpServletResponse response){
try{
billing billingObject = new billing();
//Here set the billingObject values
billingDao.save(billingObject);
int billing_id = billingObject.getId();
tax_billing tax_billing= new tax_billing();
tax_billing.setBilling_id(billing_id);
tax_billing.setTax_amount("140");
tax_billingDao.save(tax_billing);
for(Restaurant_billing prof:r_billing){
prof.setBilling_id(billing_id);
restaurant_billingDao.save(prof);
}
}
catch(Exception ex){
return "Error creating the user: " + ex.toString();
}
return ("User profession added successfully");
}
//here return obj
}