I have the following problem when i try to do the findCliente method. I have the class Cliente in the package model and when i run the findCliente controller I get this exception here. I don't know where I'm wrong because I don't have much skill with JPA and Spring Suite. Can someone tell me how to fix this exception?
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Unable to locate persister: it.myshop.orm.model.Cliente
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
java.lang.IllegalArgumentException: Unable to locate persister: it.myshop.orm.model.Cliente
org.hibernate.internal.SessionImpl.find(SessionImpl.java:3416)
org.hibernate.internal.SessionImpl.find(SessionImpl.java:3357)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:362)
com.sun.proxy.$Proxy41.find(Unknown Source)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:311)
com.sun.proxy.$Proxy41.find(Unknown Source)
it.myshop.orm.impl.ClienteServiceImpl.getById(ClienteServiceImpl.java:23)
it.myshop.orm.controller.ClienteController.findCliente(ClienteController.java:37)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
org.hibernate.UnknownEntityTypeException: Unable to locate persister: it.myshop.orm.model.Cliente
org.hibernate.metamodel.internal.MetamodelImpl.locateEntityPersister(MetamodelImpl.java:727)
org.hibernate.internal.SessionImpl.locateEntityPersister(SessionImpl.java:3019)
org.hibernate.internal.SessionImpl.access$1800(SessionImpl.java:201)
org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.<init>(SessionImpl.java:2715)
org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.<init>(SessionImpl.java:2698)
org.hibernate.internal.SessionImpl.byId(SessionImpl.java:1180)
org.hibernate.internal.SessionImpl.find(SessionImpl.java:3380)
org.hibernate.internal.SessionImpl.find(SessionImpl.java:3357)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:362)
com.sun.proxy.$Proxy41.find(Unknown Source)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:311)
com.sun.proxy.$Proxy41.find(Unknown Source)
it.myshop.orm.impl.ClienteServiceImpl.getById(ClienteServiceImpl.java:23)
it.myshop.orm.controller.ClienteController.findCliente(ClienteController.java:37)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
AppConfig
package it.myshop.orm.config;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
import it.myshop.orm.dao.ClienteService;
import it.myshop.orm.impl.ClienteServiceImpl;
#EnableWebMvc
#Configuration
#ComponentScan("it.myshop.orm.controller")
public class AppConfig {
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver iwv = new InternalResourceViewResolver();
iwv.setPrefix("/WEB-INF/view/");
iwv.setSuffix(".jsp");
iwv.setViewClass(JstlView.class);
return iwv;
}
//BEAN CONNESSIONE AL DB
#Bean
public DataSource getDbConnection() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/corso-spring-ud?serverTimezone=CET");
ds.setUsername("root");
return ds;
}
#Bean
public LocalContainerEntityManagerFactoryBean getEntityManager() {
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setDatabase(Database.MYSQL);
adapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(getDbConnection());
factory.setJpaVendorAdapter(adapter); //passo adapter
factory.setPackagesToScan(getClass().getPackage().getName());
return factory;
}
#Bean
public ClienteService getClienteServiceImpl() {
return new ClienteServiceImpl();
}
App Initializer
package it.myshop.orm.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import it.myshop.orm.config.AppConfig;
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return new Class<?>[] {AppConfig.class};
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[] {"/"};
}
}
ClienteController
package it.myshop.orm.controller;
import org.springframework.beans.factory.annotation.Autowired;
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 it.myshop.orm.dao.ClienteService;
import it.myshop.orm.impl.ClienteServiceImpl;
import it.myshop.orm.model.Cliente;
#Controller
#RequestMapping("/cliente")
public class ClienteController {
#Autowired
private ClienteService cs;
#ResponseBody
#GetMapping("/add")
public String add() {
// cs.add(null);
System.out.println("Sei nella pagina di aggiunta");
return null;
}
#ResponseBody
#GetMapping("/findCliente")
public String findCliente() {
Cliente c = cs.getById(1);
System.out.println("Sei nella pagina di find del Cliente");
return c.getNome() + " " + c.getCognome();
}
Cliente
package it.myshop.orm.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="cliente")
public class Cliente {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column
private String nome;
#Column
private String cognome;
#Column
private String codiceFiscale;
#Column
private String email;
#Column
private String telefono;
#Column
private String username;
#Column
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public String getCodiceFiscale() {
return codiceFiscale;
}
public void setCodiceFiscale(String codiceFiscale) {
this.codiceFiscale = codiceFiscale;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Interface ClienteService
package it.myshop.orm.dao;
import it.myshop.orm.model.Cliente;
public interface ClienteService {
public Cliente add(Cliente c);
public Cliente getById(int id);
}
ClienteServiceImpl
package it.myshop.orm.impl;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import it.myshop.orm.dao.ClienteService;
import it.myshop.orm.model.Cliente;
public class ClienteServiceImpl implements ClienteService {
#PersistenceContext
public EntityManager em;
#Override
public Cliente add(Cliente c) {
em.persist(c);
return c;
}
#Override
public Cliente getById(int id) {
return em.find(Cliente.class, id);
}
}
In order to solve this problem you have two options. You can choose either of which .
1- you must have all you entity classes declared in you hibernate configuration file.
for this you must add you entity classes specially "Cliente" in hibernate.cfg.xml file
like this :
<mapping class="entity.Client"/>
or
2-another way is adding this entity to session configuration like this :
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml") .addAnnotatedClass(Cliente.class) .buildSessionFactory();
Related
This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 months ago.
This post was edited and submitted for review 7 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Here I'm testing JUnit Mockito test using JUnit 5 ,when I try to test got below exception
Rerun initializationError com.xxx.BookControllerTest
com.xxx.BookControllerTest
org.mockito.exceptions.base.MockitoException:
No tests found in BookControllerTest Is the method annotated with
#Test? Is the method public?
at
org.mockito.internal.runners.RunnerFactory.create(RunnerFactory.java:82)
at
org.mockito.internal.runners.RunnerFactory.createStrict(RunnerFactory.java:40)
at
org.mockito.junit.MockitoJUnitRunner.(MockitoJUnitRunner.java:154)
at
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native
Method) at
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
at
java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at
java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at
java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at
org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at
org.junit.vintage.engine.discovery.DefensiveAllDefaultPossibilitiesBuilder$DefensiveAnnotatedBuilder.buildRunner(DefensiveAllDefaultPossibilitiesBuilder.java:114)
at
org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at
org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:70)
at
org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:37)
at
org.junit.vintage.engine.discovery.DefensiveAllDefaultPossibilitiesBuilder.runnerForClass(DefensiveAllDefaultPossibilitiesBuilder.java:57)
at
org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:70)
at
org.junit.vintage.engine.discovery.ClassSelectorResolver.resolveTestClass(ClassSelectorResolver.java:66)
at
org.junit.vintage.engine.discovery.ClassSelectorResolver.resolve(ClassSelectorResolver.java:57)
at
org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.lambda$resolveUniqueId$3(EngineDiscoveryRequestResolution.java:172)
at
java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
at
java.base/java.util.ArrayList$ArrayListSpliterator.tryAdvance(ArrayList.java:1602)
at
java.base/java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:129)
at
java.base/java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:527)
at
java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:513)
at
java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
at
java.base/java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:150)
at
java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at
java.base/java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:647)
at
org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolve(EngineDiscoveryRequestResolution.java:185)
at
org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolveUniqueId(EngineDiscoveryRequestResolution.java:172)
at
org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolve(EngineDiscoveryRequestResolution.java:123)
at
org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.access$100(EngineDiscoveryRequestResolution.java:57)
at
org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution$DefaultContext.resolve(EngineDiscoveryRequestResolution.java:224)
at
org.junit.vintage.engine.discovery.MethodSelectorResolver.resolveParentAndAddFilter(MethodSelectorResolver.java:56)
at
org.junit.vintage.engine.discovery.MethodSelectorResolver.resolve(MethodSelectorResolver.java:47)
at
org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.lambda$resolveUniqueId$3(EngineDiscoveryRequestResolution.java:172)
at
java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
at
java.base/java.util.ArrayList$ArrayListSpliterator.tryAdvance(ArrayList.java:1602)
at
java.base/java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:129)
at
java.base/java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:527)
at
java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:513)
at
java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
at
java.base/java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:150)
at
java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at
java.base/java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:647)
at
org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolve(EngineDiscoveryRequestResolution.java:185)
at
org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolveUniqueId(EngineDiscoveryRequestResolution.java:172)
at
org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolve(EngineDiscoveryRequestResolution.java:123)
at
org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolveCompletely(EngineDiscoveryRequestResolution.java:91)
at
org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.run(EngineDiscoveryRequestResolution.java:82)
at
org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolver.resolve(EngineDiscoveryRequestResolver.java:113)
at
org.junit.vintage.engine.discovery.VintageDiscoverer.discover(VintageDiscoverer.java:42)
at
org.junit.vintage.engine.VintageTestEngine.discover(VintageTestEngine.java:64)
at
org.junit.platform.launcher.core.EngineDiscoveryOrchestrator.discoverEngineRoot(EngineDiscoveryOrchestrator.java:152)
at
org.junit.platform.launcher.core.EngineDiscoveryOrchestrator.discoverSafely(EngineDiscoveryOrchestrator.java:134)
at
org.junit.platform.launcher.core.EngineDiscoveryOrchestrator.discover(EngineDiscoveryOrchestrator.java:108)
at
org.junit.platform.launcher.core.EngineDiscoveryOrchestrator.discover(EngineDiscoveryOrchestrator.java:80)
at
org.junit.platform.launcher.core.DefaultLauncher.discover(DefaultLauncher.java:110)
at
org.junit.platform.launcher.core.DefaultLauncher.discover(DefaultLauncher.java:78)
at
org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.discover(DefaultLauncherSession.java:81)
at
org.junit.platform.launcher.core.SessionPerRequestLauncher.discover(SessionPerRequestLauncher.java:46)
at
org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.(JUnit5TestReference.java:46)
at
org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.createUniqueIdTest(JUnit5TestLoader.java:113)
at
org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.loadTests(JUnit5TestLoader.java:47)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:513)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: java.lang.reflect.InvocationTargetException at
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native
Method) at
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
at
java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at
java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at
java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at
org.mockito.internal.runners.util.RunnerProvider.newInstance(RunnerProvider.java:29)
at
org.mockito.internal.runners.RunnerFactory.create(RunnerFactory.java:75)
... 66 more Caused by: org.junit.runners.model.InvalidTestClassError:
Invalid test class 'com.xxx.BookControllerTest':
No runnable methods at org.junit.runners.ParentRunner.validate(ParentRunner.java:525) at
org.junit.runners.ParentRunner.(ParentRunner.java:92) at
org.junit.runners.BlockJUnit4ClassRunner.(BlockJUnit4ClassRunner.java:74)
at
org.mockito.internal.runners.DefaultInternalRunner$1.(DefaultInternalRunner.java:31)
at
org.mockito.internal.runners.DefaultInternalRunner.(DefaultInternalRunner.java:30)
... 73 more
Entity Class
#Entity
#Table(name = "book_Record")
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long bookId;
#NonNull
private String name;
#NonNull
private String summary;
private int rating;
public Book(Long bookId, #NonNull String name, #NonNull String summary, int rating) {
super();
this.bookId = bookId;
this.name = name;
this.summary = summary;
this.rating = rating;
}
public Book() {
super();
}
public Long getBookId() {
return bookId;
}
public void setBookId(Long bookId) {
this.bookId = bookId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
}
Repository class
public interface BookRepository extends JpaRepository<Book , Long>{
}
Controller Class
package com.controller;
import java.util.List;
import java.util.Optional;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.crossstore.ChangeSetPersister.NotFoundException;
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.entity.Book;
import com.repository.BookRepository;
#RestController
#RequestMapping("/book")
public class BookController {
#Autowired
BookRepository bookRepository;
#GetMapping
public List<Book>getAllProductRecords()
{
return bookRepository.findAll();
}
#GetMapping(value="/productId")
public Book getBookById(#PathVariable(value="bookId") Long bookId)
{
return bookRepository.findById(bookId).get();
}
#PostMapping
public Book createBookRecord(#RequestBody #Valid Book bookRecord)
{
return bookRepository.save(bookRecord);
}
#PutMapping
public Book updateBookRecord(#RequestBody #Valid Book bookRecord) throws NotFoundException
{
if(bookRecord==null || bookRecord.getBookId()==null)
{
throw new NotFoundException();
}
Optional<Book> optionalBook = bookRepository.findById(bookRecord.getBookId());
if(!optionalBook.isPresent())
{
throw new NotFoundException();//"Product With ID:"+productRecord.getProductId()+ "does not exist"
}
Book existingProductRecord = optionalBook.get();
existingProductRecord.setName(bookRecord.getName());
existingProductRecord.setSummary(bookRecord.getSummary());
existingProductRecord.setRating(bookRecord.getRating());
return bookRepository.save(existingProductRecord);
}
}
Test Class
package com.xxx;
import static org.hamcrest.CoreMatchers.is;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
//import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.changepond.controller.BookController;
import com.changepond.entity.Book;
import com.changepond.repository.BookRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
#RunWith(MockitoJUnitRunner.class)
public class BookControllerTest {
private MockMvc mockmvc;
ObjectMapper objectMapper = new ObjectMapper();
ObjectWriter objectWriter = objectMapper.writer();
#Mock
private BookRepository bookRepository;
#InjectMocks
private BookController bookController;
Book Record_1 = new Book(1L,"english","tense",4);
Book Record_2 = new Book(2L,"english1","tense1",3);
Book Record_3 = new Book(3L,"english2","tense2",2);
#Before
public void setUp()
{
MockitoAnnotations.initMocks(this);
this.mockmvc=MockMvcBuilders.standaloneSetup(bookController).build();
}
#Test
public void getAllRecords() throws Exception
{
List<Book> records = new ArrayList<>(Arrays.asList(Record_1,Record_2,Record_3));
Mockito.when(bookRepository.findAll()).thenReturn(records);
mockmvc.perform(MockMvcRequestBuilders
.get("/book")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$[2].name",is("english2")));
//.andExpect(MockMvcResultMatchers.jsonPath("$", hasSize(3)))
}
}
I am using spring boot with h2 database when using a sequence and using #SequenceGenerator doesn't seem to be generating the value for the primary key. I want to generate the value of Id by default and then update the values into the database.
Here are the details of my class.
CardHolder.java
package com.spring.book.rental.dao.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name = "card_holder")
public class CardHolder {
#Id
#Column
#GeneratedValue(generator="SEQ_CARD_HOLDER_ID",strategy=GenerationType.IDENTITY)
#SequenceGenerator(name="SEQ_CARD_HOLDER_ID",
sequenceName="SEQ_PG_CARD_HOLDER_ID",initialValue = 1)
public int id;
#Column(name = "last_name")
public String lastName;
#Column(name = "first_name")
public String firstName;
#Column(name = "card_number")
public String cardNumber;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
}
BookController.java
package com.spring.book.rental.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.spring.book.rental.DTO.BookDTO;
import com.spring.book.rental.DTO.RentBookRequest;
import com.spring.book.rental.service.BookService;
#RestController
public class BookController {
#Autowired
BookService bookService;
#PostMapping(path="book-rental/rentABook", consumes = "application/json")
public String rentABook(#RequestBody RentBookRequest bookRequest) {
try {
bookService.rentBook(bookRequest);
return "You rented a Book Id : "+bookRequest.getBookId();
} catch (Exception e) {
return e.getMessage();
}
}
}
BookServiceImpl.java
package com.spring.book.rental.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.spring.book.rental.DTO.BookDTO;
import com.spring.book.rental.DTO.RentBookRequest;
import com.spring.book.rental.dao.BookDAO;
import com.spring.book.rental.dao.CardHolderDAO;
import com.spring.book.rental.dao.RentalDAO;
import com.spring.book.rental.dao.model.Book;
import com.spring.book.rental.dao.model.CardHolder;
import com.spring.book.rental.dao.model.Rental;
import com.spring.book.rental.service.BookService;
#Service("bookService")
#Component
public class BookServiceImpl implements BookService {
#Autowired
BookDAO bookDao;
#Autowired
CardHolderDAO cardHolderDAO;
#Autowired
RentalDAO rentalDAO;
#Override
public void rentBook(RentBookRequest bookRequest) throws Exception {
CardHolder cardHolder = new CardHolder();
cardHolder.setFirstName(bookRequest.getFirstName());
cardHolder.setLastName(bookRequest.getLastName());
cardHolder.setCardNumber(bookRequest.getCardNumber());
cardHolderDAO.addCardHolder(cardHolder);
/* Rental rental = new Rental();
rental.setBook_id(bookRequest.getBookId());
rental.setCardHolder_id(cardHolder.getId());
rentalDAO.addRental(rental); */
}
}
CardHolderDAOImpl.java
package com.spring.book.rental.dao.impl;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.spring.book.rental.dao.CardHolderDAO;
import com.spring.book.rental.dao.model.CardHolder;
import com.spring.book.rental.dao.repository.CardHolderRepository;
#Repository
public class CardHolderDAOImpl implements CardHolderDAO {
#Autowired
CardHolderRepository cardHolderRepository;
#Override
public void addCardHolder(CardHolder cardHolder) {
cardHolderRepository.save(cardHolder);
}
}
CardHolderRepository.java
package com.spring.book.rental.dao.repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import com.spring.book.rental.dao.model.CardHolder;
public interface CardHolderRepository extends CrudRepository<CardHolder, Integer> {
public Optional<CardHolder> findById(Integer id);
}
RentBookRequest.java
package com.spring.book.rental.DTO;
public class RentBookRequest {
private int bookId;
private int cardHolderId;
private String firstName;
private String lastName;
private String cardNumber;
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public int getCardHolderId() {
return cardHolderId;
}
public void setCardHolderId(int cardHolderId) {
this.cardHolderId = cardHolderId;
}
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 getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
}
Here is the main class
SpringTaskBookRentalApplication.java
package com.spring.book.rental;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import sun.misc.Contended;
#ComponentScan(basePackages = "com")
#EnableAutoConfiguration
#SpringBootApplication
public class SpringTaskBookRentalApplication {
public static void main(String[] args) {
SpringApplication.run(SpringTaskBookRentalApplication.class, args);
}
}
I have added this in the application.properties file
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:bookrentaldb
spring.datasource.username=admin
spring.datasource.password=admin
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.datasource.continue-on-error=false
spring.datasource.initialize=true
spring.datasource.separator=;
spring.datasource.sql-script-encoding=UTF-8
Here is the schema.sql file
create table BOOK(
id int not null primary key,
title varchar(50) not null,
IS_BOOK_AVAILABLE boolean not null,
author varchar(50) not null,
primary key(id)
);
create table card_holder (
id int not null primary key AUTO_INCREMENT,
first_name varchar(20),
last_name varchar(20),
card_number varchar(20),
primary key(id)
);
create table Rental(
rental_id int not null primary key AUTO_INCREMENT,
cardHolder_id int not null,
book_id int not null
);
CREATE SEQUENCE SEQ_PG_CARD_HOLDER_ID MINVALUE 1 MAXVALUE 9999 INCREMENT BY 1 START WITH 1 NOCYCLE ;
CREATE SEQUENCE SEQ_PG_Rental_ID MINVALUE 1 MAXVALUE 999999 INCREMENT BY 1 START WITH 100 NOCYCLE ;
Here is the data.sql
insert into BOOK (id,title,IS_BOOK_AVAILABLE,author) values (101,'A Thousand Splendid Suns','true','Khalid Hosseini');
insert into BOOK (id,title,IS_BOOK_AVAILABLE,author) values (102,'Head First Design Patterns','true','Elisabeth Freeman and Kathy Sierra');
insert into BOOK (id,title,IS_BOOK_AVAILABLE,author) values (103,'Head First Java','true','Book by Bert Bates and Kathy Sierra');
commit;
I have tried several other things with #GeneratedValue
#Id
#Column
#GeneratedValue(strategy=GenerationType.AUTO)
public int id;
This is the stackTrace of error I am getting
java.lang.IllegalArgumentException: After saving the identifier must not be null!
at org.springframework.util.Assert.notNull(Assert.java:198)
at org.springframework.data.jdbc.core.JdbcAggregateTemplate.store(JdbcAggregateTemplate.java:343)
at org.springframework.data.jdbc.core.JdbcAggregateTemplate.save(JdbcAggregateTemplate.java:149)
at org.springframework.data.jdbc.repository.support.SimpleJdbcRepository.save(SimpleJdbcRepository.java:55)
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.data.repository.core.support.ImplementationInvocationMetadata.invoke(ImplementationInvocationMetadata.java:72)
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:382)
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:205)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:549)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:155)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:130)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy81.save(Unknown Source)
at com.spring.book.rental.dao.impl.CardHolderDAOImpl.addCardHolder(CardHolderDAOImpl.java:38)
at com.spring.book.rental.dao.impl.CardHolderDAOImpl$$FastClassBySpringCGLIB$$8e01a85d.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)
at com.spring.book.rental.dao.impl.CardHolderDAOImpl$$EnhancerBySpringCGLIB$$5a6f1054.addCardHolder(<generated>)
at com.spring.book.rental.service.impl.BookServiceImpl.rentBook(BookServiceImpl.java:68)
at com.spring.book.rental.controller.BookController.rentABook(BookController.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.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
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.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
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:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
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:373)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
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)
You are adding lot of dependencies which you don't need. And when you add a dependency that you don't need, spring boot tries to guess the type of your application and configures accordingly.
I also recommend reading Spring data JPA vs Spring Data JDBC as both are mixed.
1.
public CardHolder addCardHolder(CardHolder cardHolder) {
return cardHolderRepository.save(cardHolder);
}
#Override
public void rentBook(RentBookRequest bookRequest) throws Exception {
CardHolder cardHolder = new CardHolder();
cardHolder.setFirstName(bookRequest.getFirstName());
cardHolder.setLastName(bookRequest.getLastName());
cardHolder.setCardNumber(bookRequest.getCardNumber());
CardHolder saved = cardHolderDAO.addCardHolder(cardHolder);
Rental rental = new Rental();
rental.setBook_id(bookRequest.getBookId());
rental.setCardHolder_id(saved.getId());
rentalDAO.addRental(rental);
}
Your pom should contain only the following. You are currently adding many different dependencies
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
package com.spring.book.rental.dao.model;
import javax.persistence.*;
#Entity
#Table(name = "BOOK")
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public int id;
#Column
public String title;
#Column(name = "IS_BOOK_AVAILABLE")
public boolean isBookAvailable;
#Column
public String author;
...
package com.spring.book.rental.dao.model;
import javax.persistence.*;
#Entity
#Table(name = "card_holder")
public class CardHolder {
#Id
#GeneratedValue(generator="SEQ_CARD_HOLDER_ID",strategy=GenerationType.IDENTITY)
#SequenceGenerator(name="SEQ_CARD_HOLDER_ID", sequenceName="SEQ_PG_CARD_HOLDER_ID",initialValue = 1)
#Column
public int id;
#Column(name = "last_name")
public String lastName;
#Column(name = "first_name")
public String firstName;
#Column(name = "card_number")
public String cardNumber;
....
package com.spring.book.rental.dao.model;
import javax.persistence.*;
import org.springframework.boot.autoconfigure.domain.EntityScan;
#Entity
#Table(name = "Rental")
public class Rental {
#Id
#Column(name = "rental_id")
#GeneratedValue(strategy = GenerationType.AUTO)
public int rentalId;
#Column(name = "cardHolder_id")
public int cardHolder_id;
#Column(name = "book_id")
public int book_id;
....
package com.spring.book.rental.dao.repository;
import com.spring.book.rental.dao.model.Book;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
import java.util.Optional;
public interface BookRepository extends CrudRepository<Book,Integer>{
public List<Book> findAllByIsBookAvailableTrue();
public List<Book> findAll();
public Optional<Book> findById(Integer id);
}
...
Delete schema.sql as it has mistakes and JPA can auto create it.
application properties
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
I have a Spring Boot 2.1 app with a simple rest controller, service tier, and data tier. I am attempting to disable spring.jpa.open-in-view as I want to manage the loading of my collections, etc. My problem seems to be when I disable open-in-view, I can't get anything back in my controller including simple properties including Strings.
Sample Project, simplified version of the code below:
https://github.com/csyperski/springbootopeninview
Here is my error:
2019-02-05 09:06:19.591 -ERROR 11355 --- [nio-8081-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : 175 : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.hibernate.LazyInitializationException: could not initialize proxy [com.cwssoft.pscafepos.model.Item#268] - no Session] with root cause
-
org.hibernate.LazyInitializationException: could not initialize proxy [com.cwssoft.pscafepos.model.Item#268] - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:169) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:309) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor.intercept(ByteBuddyInterceptor.java:45) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.proxy.ProxyConfiguration$InterceptorDispatcher.intercept(ProxyConfiguration.java:95) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at com.cwssoft.pscafepos.model.Item$HibernateProxy$h2GPuZuU.getBuilding(Unknown Source) ~[main/:na]
at com.cwssoft.pscafepos.controllers.ItemController.lambda$getSingle$3(ItemController.java:52) ~[main/:na]
at java.util.Optional.filter(Optional.java:178) ~[na:1.8.0_201]
at com.cwssoft.pscafepos.controllers.ItemController.getSingle(ItemController.java:52) ~[main/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_201]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_201]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_201]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_201]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.13.jar:9.0.13]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
Here is my Model without getters/setters:
import com.cwssoft.pscafepos.model.converters.BooleanToStringConverter;
import javax.persistence.*;
import java.util.Date;
#Entity
#Table(name="items", indexes = {
#Index(name="key_items_name", columnList="item_name"),
#Index(name="key_items_building", columnList="item_building"),
#Index(name="key_items_visible", columnList="item_visible"),
#Index(name="key_items_free", columnList="item_allowfree"),
#Index(name="key_items_reduced", columnList="item_allowreduced"),
#Index(name="key_items_typea", columnList="item_istypea"),
})
public class Item implements DomainObject {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "item_id", updatable = false, nullable = false)
private Long id;
#Column(name="item_name", length = 100, nullable = false, unique = false)
private String name;
#Column(name="item_description", columnDefinition = "TEXT")
private String description;
#Column(name="item_price")
private double price;
#Column(name="item_building", length = 100, nullable = false, unique = false)
private String building;
#Column(name="item_category", columnDefinition = "TEXT")
private String category;
#Column(name="item_visible", length = 1, nullable = false, unique = false)
#Convert(converter= BooleanToStringConverter.class)
private boolean visible;
#Column(name="item_allowfree", length = 1, nullable = false, unique = false)
#Convert(converter=BooleanToStringConverter.class)
private boolean allowFree;
#Column(name="item_allowreduced",length = 1, nullable = false, unique = false)
#Convert(converter=BooleanToStringConverter.class)
private boolean allowReduced;
#Column(name="item_istypea",length = 1, nullable = false, unique = false)
#Convert(converter=BooleanToStringConverter.class)
private boolean typeA;
#Column(name="item_reducedprice")
private double reducedPrice;
#Column(name="item_addby", length = 100, nullable = false, unique = false)
private String addedBy;
#Column(name="item_adddate")
#Temporal(TemporalType.TIMESTAMP)
private Date createDate;
#Column(name="item_fr_bl")
private int freeReducedBreakfastLunch;
}
Here is my Service Tier:
package com.cwssoft.pscafepos.services;
import com.cwssoft.pscafepos.model.Item;
import com.cwssoft.pscafepos.repositories.ItemRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
#Service
public class DefaultItemService extends BaseService<Item, ItemRepository> implements ItemService {
public DefaultItemService(ItemRepository itemRepository) {
super(itemRepository);
}
#Override
#Transactional
public Optional<Item> findByName(String name) {
if (name != null) {
return Optional.ofNullable(repository.findByName(name.trim()));
}
return Optional.empty();
}
#Override
#Transactional
public List<Item> findAll(String building) {
if (building != null) {
return repository.findByBuildingOrderByVisibleDescNameAsc(building.trim());
}
return Collections.emptyList();
}
}
and the service super class:
package com.cwssoft.pscafepos.services;
import com.cwssoft.pscafepos.model.DomainObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
#Slf4j
public abstract class BaseService<T extends DomainObject,U extends JpaRepository<T,Long>> implements CrudService<T,U> {
protected final U repository;
public BaseService(U repository) {
this.repository = repository;
}
public U getRepository() {
return repository;
}
#Transactional
public List<T> findAll() {
return repository.findAll();
}
#Transactional
public List<T> findAll(Sort sort) {
return repository.findAll(sort);
}
#Transactional
public List<T> findAllById(Iterable<Long> ids) {
return repository.findAllById(ids);
}
#Transactional
public Optional<T> save(T item) {
return Optional.ofNullable(repository.saveAndFlush(item));
}
#Transactional
public Optional<T> get(long id) {
return Optional.ofNullable(prepare(repository.getOne(id)));
}
#Transactional
public T prepare( T item ) {
return item;
}
#Transactional
public void delete(long id) {
get(id).ifPresent( repository::delete );
}
}
And the controller:
package com.cwssoft.pscafepos.controllers;
import com.cwssoft.pscafepos.model.AdminUser;
import com.cwssoft.pscafepos.model.Item;
import com.cwssoft.pscafepos.services.AdminUserService;
import com.cwssoft.pscafepos.services.ItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
#RestController
#RequestMapping("/items")
#Slf4j
public class ItemController extends BaseController {
private final ItemService service;
public ItemController(ItemService itemService, AdminUserService adminUserService) {
super(adminUserService);
this.service = itemService;
}
#GetMapping("/all")
#Secured("CAFE_MANAGER")
public List<Item> all(Principal principal) {
return getLocation(principal)
.map( service::findAll )
.orElse( Collections.emptyList() );
}
#GetMapping("/single/{itemId}")
#Secured("CAFE_MANAGER")
public Item getSingle(Principal principal, #PathVariable("itemId") long id) {
final Optional<String> location = getLocation(principal);
location
.flatMap( l -> service.get(id) )
.ifPresent( item -> {
log.info("Item.toString {}", item);
});
return location
.flatMap( l -> service.get(id) )
.filter( item -> item.getBuilding() != null && item.getBuilding().equalsIgnoreCase(location.orElse(null)) )
.orElse( null );
}
}
So what am I missing, why can't I pull back basic properties, there are no collections in the Item class and it about as simple as they come. I see that I'm getting a HibernateProxy wrapped object back and when I attempt to call getBuilding is when it appears to be failing, even though building is just a simple string. This is all before Jaskson is attempting to serialize the object to put it over the wire. Thanks!
i am trying to insert some record into my database table using spring hibernate,but the following error occur after running the project.please help me to solve the problem..thanks
Entity class Admin.java
package com.finalproject.entity;
// Generated Apr 20, 2017 4:49:19 PM by Hibernate Tools 4.3.1
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Admin generated by hbm2java
*/
#Entity
#Table(name="admin"
,catalog="advertisement_system"
)
public class Admin implements java.io.Serializable {
private Integer adminId;
private String adminName;
private String adminEmail;
private String adminPass;
private byte[] adminPhoto;
public Admin() {
}
public Admin(String adminName, String adminEmail, String adminPass) {
this.adminName = adminName;
this.adminEmail = adminEmail;
this.adminPass = adminPass;
}
public Admin(String adminName, String adminEmail, String adminPass, byte[] adminPhoto) {
this.adminName = adminName;
this.adminEmail = adminEmail;
this.adminPass = adminPass;
this.adminPhoto = adminPhoto;
}
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="admin_id", unique=true, nullable=false)
public Integer getAdminId() {
return this.adminId;
}
public void setAdminId(Integer adminId) {
this.adminId = adminId;
}
#Column(name="admin_name", nullable=false, length=45)
public String getAdminName() {
return this.adminName;
}
public void setAdminName(String adminName) {
this.adminName = adminName;
}
#Column(name="admin_email", nullable=false, length=45)
public String getAdminEmail() {
return this.adminEmail;
}
public void setAdminEmail(String adminEmail) {
this.adminEmail = adminEmail;
}
#Column(name="admin_pass", nullable=false, length=45)
public String getAdminPass() {
return this.adminPass;
}
public void setAdminPass(String adminPass) {
this.adminPass = adminPass;
}
#Column(name="admin_photo")
public byte[] getAdminPhoto() {
return this.adminPhoto;
}
public void setAdminPhoto(byte[] adminPhoto) {
this.adminPhoto = adminPhoto;
}
}
AdminServiceImpl.java class
package com.finalproject.service.impl;
import com.finalproject.dao.AdminDao;
import com.finalproject.entity.Admin;
import com.finalproject.service.AdminService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
#Service("adminService")
#Transactional(propagation = Propagation.SUPPORTS,rollbackFor = Exception.class)
public class AdminServiceImpl implements AdminService {
#Autowired
AdminDao adminDao;
#Override
public void create(Admin admin) {
adminDao.create(admin);
}
#Override
public void update(Admin admin) {
adminDao.update(admin);
}
#Override
public void delete(Long adminId) {
adminDao.delete(adminId);
}
#Override
public Admin edit(Long adminId) {
return adminDao.edit(adminId);
}
#Override
public List<Admin> getAll() {
return adminDao.getAll();
}
#Override
public Admin find(Long adminId) {
return adminDao.find(adminId);
}
}
Dao implemented class AdminDaoImpl.java
package com.finalproject.dao.impl;
import com.finalproject.dao.AdminDao;
import com.finalproject.entity.Admin;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository("adminDao")
public class AdminDaoImpl implements AdminDao {
#Autowired
SessionFactory sessionFactory;
protected Session currentSession() {
return sessionFactory.getCurrentSession();
}
#Override
public void create(Admin admin) {
currentSession().save(admin);
}
#Override
public void update(Admin admin) {
currentSession().update(admin);
}
#Override
public void delete(Long adminId) {
currentSession().delete(adminId);
}
#Override
public Admin edit(Long adminId) {
return find(adminId);
}
#Override
public Admin find(Long adminId) {
return (Admin) currentSession().get(Admin.class, adminId);
}
#Override
public List<Admin> getAll() {
return currentSession().createCriteria(Admin.class).list();
}
}
controller class AdminController.java
package com.finalproject.controller;
import com.finalproject.entity.Admin;
import com.finalproject.service.AdminService;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping(value = "/admin")
public class AdminController {
#Autowired
AdminService adminService;
#RequestMapping(value = "/register", method = RequestMethod.GET)
public String register(Map<String, Object> map) {
map.put("adminReg", new Admin());
return "/admin/add";
}
#RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(Admin admin, Map<String, Object> map) {
adminService.create(admin);
return "redirect:/admin/details/" + admin.getAdminId();
}
#RequestMapping(value = "/details/{adminId}",method = RequestMethod.GET)
public String details(#PathVariable("adminId") Long adminId, Map<String, Object> map) {
Admin admin = adminService.find(adminId);
map.put("adminName", admin.getAdminName());
map.put("adminEmail", admin.getAdminEmail());
map.put("adminPass", admin.getAdminPass());
return "admin/details";
}
}
Error message
type Exception report
message Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:948)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
root cause
org.hibernate.HibernateException: No Session found for current thread
org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:978)
com.finalproject.dao.impl.AdminDaoImpl.currentSession(AdminDaoImpl.java:19)
com.finalproject.dao.impl.AdminDaoImpl.create(AdminDaoImpl.java:24)
com.finalproject.service.impl.AdminServiceImpl.create(AdminServiceImpl.java:22)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
com.sun.proxy.$Proxy125.create(Unknown Source)
com.finalproject.controller.AdminController.create(AdminController.java:29)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Error Message
AdminDaoImpl.java
Can't find error ((
Spring MVC + Hibernate, JavaConfig
WebAppConfig:
package com.sprhib.init;
import java.util.Properties;
import javax.annotation.Resource;
import javax.sql.DataSource;
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.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
#Configuration
#ComponentScan("com.sprhib")
#EnableWebMvc
#EnableTransactionManagement
#PropertySource("classpath:application.properties")
public class WebAppConfig {
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setHibernateProperties(hibProperties());
return sessionFactoryBean;
}
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
return properties;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
User
package com.sprhib.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;
#Entity
#Table(name="user")
public class User {
#Id
#GeneratedValue
private Integer id;
private String name;
private Integer age;
private Boolean isAdmin;
private Timestamp createdDate;
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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Boolean getAdmin() {
return isAdmin;
}
public void setAdmin(Boolean admin) {
isAdmin = admin;
}
public Timestamp getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Timestamp createdDate) {
this.createdDate = createdDate;
}
}
package com.sprhib.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.sprhib.model.User;
#Repository
public class UserDAOImpl implements UserDAO {
#Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
public void addUser(User user) {
getCurrentSession().save(user);
}
public void updateUser(User user) {
User userUpdate = getUser(user.getId());
userUpdate.setName(user.getName());
userUpdate.setAge(user.getAge());
userUpdate.setAdmin(user.getAdmin());
userUpdate.setCreatedDate(user.getCreatedDate());
getCurrentSession().update(userUpdate);
}
public User getUser(int id) {
return (User)getCurrentSession().get(User.class,id);
}
public void deleteUser(int id) {
User user = getUser(id);
if (user!=null)
getCurrentSession().delete(user);
}
public List<User> getUsers() {
System.out.println("zzz");
return getCurrentSession().createQuery("FROM User").list();
}
}
UserDAOImpl:
package com.sprhib.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.sprhib.model.User;
#Repository
public class UserDAOImpl implements UserDAO {
#Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
public void addUser(User user) {
getCurrentSession().save(user);
}
public void updateUser(User user) {
User userUpdate = getUser(user.getId());
userUpdate.setName(user.getName());
userUpdate.setAge(user.getAge());
userUpdate.setAdmin(user.getAdmin());
userUpdate.setCreatedDate(user.getCreatedDate());
getCurrentSession().update(userUpdate);
}
public User getUser(int id) {
return (User)getCurrentSession().get(User.class,id);
}
public void deleteUser(int id) {
User user = getUser(id);
if (user!=null)
getCurrentSession().delete(user);
}
public List<User> getUsers() {
return getCurrentSession().createQuery("FROM User").list();
}
}
UserController:
package com.sprhib.controller;
import java.util.List;
import com.sprhib.model.User;
import com.sprhib.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.servlet.ModelAndView;
#Controller
#RequestMapping(value="/user")
public class UserController {
#Autowired
private UserService userService;
#RequestMapping(value="/add", method=RequestMethod.GET)
public ModelAndView addUserPage()
{
ModelAndView modelAndView = new ModelAndView("add-user-form");
modelAndView.addObject("user",new User());
return modelAndView;
}
#RequestMapping(value="/add", method=RequestMethod.POST)
public ModelAndView addingUser(#ModelAttribute User user) {
ModelAndView modelAndView = new ModelAndView("home");
userService.addUser(user);
String message = "User was successfully added.";
modelAndView.addObject("message", message);
return modelAndView;
}
#RequestMapping(value="/list")
public ModelAndView listOfUsers() {
ModelAndView modelAndView = new ModelAndView("list-of-users");
List<User> users = userService.getUsers();
modelAndView.addObject("users", users);
return modelAndView;
}
#RequestMapping(value="/edit/{id}", method=RequestMethod.GET)
public ModelAndView editUserPage(#PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView("edit-user-form");
User user = userService.getUser(id);
modelAndView.addObject("user",user);
return modelAndView;
}
#RequestMapping(value="/edit/{id}", method=RequestMethod.POST)
public ModelAndView edditingUser(#ModelAttribute User user, #PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView("home");
userService.updateUser(user);
String message = "User was successfully updated.";
modelAndView.addObject("message", message);
return modelAndView;
}
#RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
public ModelAndView deleteUser(#PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView("home");
userService.deleteUser(id);
String message = "User was successfully deleted.";
modelAndView.addObject("message", message);
return modelAndView;
}
}
application.properties:
#DB properties:
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/test
db.username=root
db.password=root
#Hibernate Configuration:
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=true
entitymanager.packages.to.scan=com.sprhib.model
When i try to get users in a browser:
HTTP Status 500 - Request processing failed; nested exception is
org.springframework.transaction.CannotCreateTransactionException:
Could not open Hibernate Session for transaction; nested exception is
java.lang.NoClassDefFoundError:
org/hibernate/engine/transaction/spi/TransactionContext
type Exception report
message Request processing failed; nested exception is
org.springframework.transaction.CannotCreateTransactionException:
Could not open Hibernate Session for transaction; nested exception is
java.lang.NoClassDefFoundError:
org/hibernate/engine/transaction/spi/TransactionContext
description The server encountered an internal error that prevented it
from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is
org.springframework.transaction.CannotCreateTransactionException:
Could not open Hibernate Session for transaction; nested exception is
java.lang.NoClassDefFoundError:
org/hibernate/engine/transaction/spi/TransactionContext
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:977)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:856)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:841)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
org.springframework.transaction.CannotCreateTransactionException:
Could not open Hibernate Session for transaction; nested exception is
java.lang.NoClassDefFoundError:
org/hibernate/engine/transaction/spi/TransactionContext
org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:544)
org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:463)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
com.sun.proxy.$Proxy34.getUsers(Unknown Source)
com.sprhib.controller.UserController.listOfUsers(UserController.java:44)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:497)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:775)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:965)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:856)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:841)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NoClassDefFoundError:
org/hibernate/engine/transaction/spi/TransactionContext
org.springframework.orm.hibernate4.HibernateTransactionManager.isSameConnectionForEntireSession(HibernateTransactionManager.java:711)
org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:445)
org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:463)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
com.sun.proxy.$Proxy34.getUsers(Unknown Source)
com.sprhib.controller.UserController.listOfUsers(UserController.java:44)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:497)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:775)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:965)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:856)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:841)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.ClassNotFoundException:
org.hibernate.engine.transaction.spi.TransactionContext
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1308)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1142)
org.springframework.orm.hibernate4.HibernateTransactionManager.isSameConnectionForEntireSession(HibernateTransactionManager.java:711)
org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:445)
org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:463)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
com.sun.proxy.$Proxy34.getUsers(Unknown Source)
com.sprhib.controller.UserController.listOfUsers(UserController.java:44)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:497)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:775)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:965)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:856)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:841)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
I'am traning to this example...
You use org.springframework.orm.hibernate4.HibernateTransactionManager for Hibernate 4. This class using TransactionContext from Hibernate 4.
Looks like you use Hibernate 5. Just change
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
to this
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
You need to use corresponding Spring libraries of course. For an example 4.2.4.RELEASE.