org.hibernate.MappingException: Unknown entity: com.travelplanner.rest.entity.User - java

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 + "]";
}
}

Related

org.hibernate.MappingException: Unknown entity when trying to create a new record

I want to implement simple CRUD operations in MySQL using Hibernate and Spring MVC. I have made a few web apps in Spring MVC but Hibernate is quite new to me. I tried to create a record in one of the tables in my database and followed this tutorial: https://examples.javacodegeeks.com/enterprise-java/hibernate/hibernate-crud-operations-tutorial/ But when I run the application, it gives org.hibernate.MappingException
I have tried both keeping and removing the mapping class line from the file hibernate-cfg.xml. I also checked for missing #Entity annotations.
Exception Stack:
org.hibernate.MappingException: Unknown entity: com.eversoft.traverse.model.User
at org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:704)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1731)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:118)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:191)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:176)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:712)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:704)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:699)
at com.eversoft.traverse.daoimpl.UserDaoImpl.createUser(UserDaoImpl.java:43)
at com.eversoft.traverse.serviceimpl.UserServiceImpl.createUser(UserServiceImpl.java:22)
at com.eversoft.traverse.controller.UserController.addUserDummy(UserController.java:31)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
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:791)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:835)
User.java
package com.eversoft.traverse.model;
import java.io.Serializable;
import java.util.Date;
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="users")
public class User implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="firstName")
private String firstName;
#Column(name="middleName")
private String middleName;
#Column(name="lastName")
private String lastName;
#Column(name="nationality")
private String nationality;
#Column(name="dateOfBirth")
public Date dateOfBirth;
#Column(name="visaId")
private int visaId;
public User() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public int getVisaId() {
return visaId;
}
public void setVisaId(int visaId) {
this.visaId = visaId;
}
}
UserController.java
package com.eversoft.traverse.controller;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.eversoft.traverse.model.User;
import com.eversoft.traverse.service.UserService;
#Controller
public class UserController {
#Autowired
UserService userService;
#RequestMapping(value="/adddummyvalue", method = RequestMethod.GET)
public String addUserDummy(Model model) {
User dummyUser = new User();
dummyUser.setDateOfBirth(new Date());
dummyUser.setFirstName("Bikalpa");
dummyUser.setLastName("Dhakal");
dummyUser.setMiddleName("Raj");
dummyUser.setNationality("Nepalese");
dummyUser.setVisaId(22);
userService.createUser(dummyUser);
return "home";
}
}
UserDaoImpl.java
package com.eversoft.traverse.daoimpl;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.springframework.stereotype.Repository;
import com.eversoft.traverse.dao.UserDao;
import com.eversoft.traverse.model.User;
#Repository
public class UserDaoImpl implements UserDao {
static Session sessionObj;
static SessionFactory sessionFactoryObj;
//public final static Logger logger = Logger.getLogger(DbOperations.class);
// This Method Is Used To Create The Hibernate's SessionFactory Object
private static SessionFactory buildSessionFactory() {
// Creating Configuration Instance & Passing Hibernate Configuration File
Configuration configObj = new Configuration();
configObj.configure("hibernate.cfg.xml");
// Since Hibernate Version 4.x, ServiceRegistry Is Being Used
ServiceRegistry serviceRegistryObj = new StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build();
// Creating Hibernate SessionFactory Instance
sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);
return sessionFactoryObj;
}
#Override
public void createUser(User user) {
try {
// Getting Session Object From SessionFactory
sessionObj = buildSessionFactory().openSession();
// Getting Transaction Object From Session Object
sessionObj.beginTransaction();
sessionObj.save(user);
// Committing The Transactions To The Database
sessionObj.getTransaction().commit();
} catch(Exception sqlException) {
if(null != sessionObj.getTransaction()) {
sessionObj.getTransaction().rollback();
}
sqlException.printStackTrace();
} finally {
if(sessionObj != null) {
sessionObj.close();
}
}
}
}
UserServiceImpl.java
package com.eversoft.traverse.serviceimpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.eversoft.traverse.dao.UserDao;
import com.eversoft.traverse.model.User;
import com.eversoft.traverse.service.UserService;
#Service
public class UserServiceImpl implements UserService{
#Autowired
UserDao userDao;
public UserServiceImpl() {
}
#Override
public void createUser(User user) {
userDao.createUser(user);
}
}
hibernate-cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- SQL Dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Database Connection Settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sys</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">helloworld</property>
<property name="show_sql">true</property>
<!-- Specifying Session Context -->
<property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>
<!-- <mapping class="com.eversoft.traverse.model.User" /> -->
<!-- Mapping With Model Class Containing Annotations -->
<!-- <mapping class="com.jcg.hibernate.crud.operations.Student" /> -->
</session-factory>
</hibernate-configuration>
I expected a new record to be inserted to table when I hit http://localhost:8080/traverse/adddummyvalue but I get MappingException instead.
You need to change your code as example you referred is for Hibernate 4.3 and you are using Hibernate 5.x. Refer here for explanation.
Change your code as per hibernate 5.x docs
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder() .configure("hibernate.cfg.xml").build();
Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder().build();
return metadata.getSessionFactoryBuilder().build();

Error during mapping java.lang.NullPointerException

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)

Hibernate not creating table in H2

Hibernate is not creating table in H2 database. I am using a maven webapp project. But hibernate seems to not create automatic tables. PLease help. This is my User class -
package com.sakib.model;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name = "userlogin")
public class User {
private String fname;
private String lname;
private String email;
private int mobile;
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getMobile() {
return mobile;
}
public void setMobile(int mobile) {
this.mobile = mobile;
}
}
This is my DBConfiguration file. I am not using xml based file for hibernate config -
package com.sakib.configuration;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.sakib.model.User;
public class DBConfiguration {
#Bean
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:tcp://localhost/~/userlogin");
dataSource.setUsername("sa");
dataSource.setPassword("sa");
return dataSource;
}
#Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBuilder lsf=
new LocalSessionFactoryBuilder(getDataSource());
Properties hibernateProperties=new Properties();
hibernateProperties.setProperty(
"hibernate.dialect", "org.hibernate.dialect.H2Dialect");
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "create");
hibernateProperties.setProperty("hibernate.show_sql", "true");
lsf.addProperties(hibernateProperties);
Class classes[]=new Class[]{User.class};
return lsf.addAnnotatedClasses(classes).buildSessionFactory();
}
#Bean
public HibernateTransactionManager hibTransManagement(){
return new HibernateTransactionManager(sessionFactory());
}
}
This is App.java. Its basically to run backend implementation with main method -
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.sakib.configuration.DBConfiguration;
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
ApplicationContext context=
new AnnotationConfigApplicationContext(DBConfiguration.class);
}
}
Any help would be of great use.

Error creating bean with name 'loginRepository': Invocation of init method failed; nested exception [duplicate]

This question already has answers here:
Autowiring fails: Not an managed Type
(13 answers)
Closed 4 years ago.
Here is my code:
springboot class
package com.angularjs.app.controller;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.web.bind.annotation.RestController;
//#RestController
//#EnableAutoConfiguration
#SpringBootApplication
public class Application extends SpringBootServletInitializer{
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Application.class);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Controller
package com.angularjs.app.controller;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.angularjs.app.message.Response;
import com.angularjs.app.model.LoginVO;
import com.angularjs.app.repo.LoginRepository;
//#Configuration
//#ComponentScan
//#EnableAutoConfiguration
#RestController
#EnableJpaRepositories("com.angularjs.app.repo")
public class LoginController {
//#Autowired
LoginRepository loginRepository;
#RequestMapping("/findbyusername")
public Response findByLastName(#RequestParam("username") String username) {
LoginVO userDetails = loginRepository.findByUsername(username);
return new Response("Done", userDetails);
}
#RequestMapping("/")
ModelAndView home(ModelAndView modelAndView) {
modelAndView.setViewName("home");
return modelAndView;
}
#RequestMapping(value = "/postuserdetails", method = RequestMethod.POST)
public void postCustomer(#RequestBody LoginVO loginVo) {
loginRepository.save(new LoginVO(loginVo.getUsername(), loginVo.getPassword(), loginVo.getEmail(),"Y"));
}
}
response class
package com.angularjs.app.message;
public class Response {
private String status;
private Object data;
public Response() {
}
public Response(String status, Object data) {
this.status = status;
this.data = data;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
model class
package com.angularjs.app.model;
import java.io.Serializable;
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 = "user_details")
public class LoginVO implements Serializable{
private static final long serialVersionUID = -3009157732242241606L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column (name="user_id")
private long userId;
#Column (name="user_name")
private String username;
#Column (name="valid_user")
private String validUser;
#Column (name="password")
private String password;
#Column (name="email")
private String email;
public LoginVO(String username, String password, String email, String validuser) {
this.username = username;
this.password = password;
this.email = email;
this.validUser = validuser;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getValidUser() {
return validUser;
}
public void setValidUser(String validUser) {
this.validUser = validUser;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return String.format("Customer[userId=%d, username='%s', email='%s']", userId, username, email);
}
}
repo class
package com.angularjs.app.repo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Service;
import com.angularjs.app.model.LoginVO;
#Service
public interface LoginRepository extends CrudRepository<LoginVO, Long> {
LoginVO findByUsername(String userName);
}
Exception
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-08-25 16:23:47.591 ERROR 2702 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.angularjs.app.model.LoginVO
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1699) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:573) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:740) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:762) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:398) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:330) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1258) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at com.angularjs.app.controller.Application.main(Application.java:21) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_91]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_91]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_91]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_91]
at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:496) [spring-boot-maven-plugin-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_91]
Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.angularjs.app.model.LoginVO
at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:473) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:72) ~[spring-data-jpa-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:66) ~[spring-data-jpa-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:169) ~[spring-data-jpa-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:107) ~[spring-data-jpa-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:90) ~[spring-data-jpa-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:298) ~[spring-data-commons-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$3(RepositoryFactoryBeanSupport.java:286) ~[spring-data-commons-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.util.Lazy.getNullable(Lazy.java:141) ~[spring-data-commons-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.util.Lazy.get(Lazy.java:63) ~[spring-data-commons-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:289) ~[spring-data-commons-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:102) ~[spring-data-jpa-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1758) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1695) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
... 22 common frames omitted
By adding #EntityScan(basePackageClasses=LoginVO.class) on Application class, my issue got resolved.

jpa named and criteria query fail when running on webserver (wildfly) in spring mvc 4 webapplication with java configuration

I have the following simple spring mvc 4 application with JPA 2.0 using java config
package com.somecompany.class;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#Configuration
#EnableWebMvc
#Import({JPAConfig.class, BeanConfig.class})
#ComponentScan("com.*")
public class AppConfig {
public InternalResourceViewResolver setupInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
The AppConfig.java class contains the application configuration logic
package com.somecompany.class;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
import org.springframework.instrument.classloading.LoadTimeWeaver;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages="com.somecompany.model.*")
public class JPAConfig {
#Bean
public JpaTransactionManager jpaTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager(getEntityManagerFactoryBean().getObject());
return transactionManager;
}
#Bean
public LocalContainerEntityManagerFactoryBean getEntityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean containerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
containerEntityManagerFactoryBean.setDataSource(getDataSource());
containerEntityManagerFactoryBean.setPersistenceUnitName("pmd-web");
LoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
containerEntityManagerFactoryBean.setLoadTimeWeaver(loadTimeWeaver);
return containerEntityManagerFactoryBean;
}
#Bean
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/somedatabase");
dataSource.setUsername("someuser");
dataSource.setPassword("somepassword");
return dataSource;
}
}
The JPAConfig.java contains the JPA configuration details
package com.somecompany.class;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebAppInitializer implements WebApplicationInitializer{
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext();
webApplicationContext.register(AppConfig.class);
webApplicationContext.setServletContext(servletContext);
webApplicationContext.refresh();
Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(webApplicationContext));
dynamic.addMapping("/");
dynamic.setLoadOnStartup(1);
}
}
WebAppInitializer.java contains the logic for initializing the web app
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="pmd-web">
<description>project metrics dashboard</description>
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
</properties>
</persistence-unit>
</persistence>
persistence.xml is as above.
package com.somecompany.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RestController;
import com.somecompany.VO.LoginVO;
import com.somecompany.loginService.LoginService;
#RestController
public class LoginController {
#Autowired
LoginService loginService;
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity<LoginVO> authenticateUser(#RequestBody LoginVO loginVO) {
loginVO = loginService.authenticateUser(loginVO);
if (loginVO.getStatus()) {
return new ResponseEntity<LoginVO>(loginVO, HttpStatus.OK);
} else {
return new ResponseEntity<LoginVO>(loginVO, HttpStatus.FORBIDDEN);
}
}
}
The Restful controller class is as above
package com.somecompany.loginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import somecompany.VO.LoginVO;
import somecompany.mapper.LoginMapper;
import somecompany.model.PmdUser;
import com.somecompany.LoginDAO;
#Service
public class LoginService {
#Autowired
LoginDAO loginDAO;
#Autowired
LoginMapper loginMapper;
#Transactional
public LoginVO authenticateUser(LoginVO loginVO) {
PmdUser pmdUser = loginMapper.getpmdUserFromLoginVO(loginVO);
LoginVO loginVOFromDB = loginDAO.authenticateUser(pmdUser);
if (loginVO.getUserName().equalsIgnoreCase(loginVOFromDB.getUserName())) {
loginVO.setStatus(true);
}
return loginVO;
}
}
The service class is as above
package com.somecompany.loginDAO;
import java.util.List;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.somecompany.VO.LoginVO;
import com.somecompany.baseDAO.BaseDao;
import com.somecompany.mapper.LoginMapper;
import com.somecompany.model.PmdUser;
#Repository
public class LoginDAO extends BaseDao {
#Autowired
LoginMapper loginMapper;
public LoginVO authenticateUser(PmdUser pmdUser) {
PmdUser user = null;
LoginVO loginVO = null;
List<PmdUser> pmdUsers = findByNamedQuery("findByUsername", pmdUser.getUserName());
if (pmdUsers.size() > 0) {
user = pmdUsers.get(0);
loginVO = loginMapper.getLoginVOFromPmdUser(user);
}
return loginVO;
}
}
The loginDAO.java class is as above
package com.somecompany.baseDAO;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Repository;
#Repository
public abstract class BaseDao<E, K> {
/** The entity manager. */
#PersistenceContext(unitName = "pmd-web")
protected EntityManager entityManager;
/**
* Gets the entity manager.
*
* #return the entity manager
*/
public EntityManager getEntityManager() {
return entityManager;
}
/** The entity class. */
protected Class<E> entityClass;
/**
* Instantiates a new base DAO.
*/
#SuppressWarnings("unchecked")
public BaseDao() {
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[0];
}
public List<E> findByNamedQuery(final String name, Object... params) {
javax.persistence.Query query = getEntityManager().createNamedQuery(name);
for (int i = 0; i < params.length; i++) {
query.setParameter(i + 1, params[i]);
}
final List<E> result = (List<E>) query.getResultList();
return result;
}
}
On deploying the application war and execution the REST service i get the exception
Caused by: java.lang.IllegalArgumentException: No query defined for that name [findByUsername]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.buildQueryFromName(AbstractEntityManagerImpl.java:788) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createNamedQuery(AbstractEntityManagerImpl.java:767) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.8.0_65]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) [rt.jar:1.8.0_65]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.8.0_65]
at java.lang.reflect.Method.invoke(Method.java:497) [rt.jar:1.8.0_65]
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:294) [spring-orm-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at com.sun.proxy.$Proxy92.createNamedQuery(Unknown Source)
at com.somecompany.baseDAO.BaseDao.findByNamedQuery(BaseDao.java:184) [classes:]
at com.somecompany.loginDAO.LoginDAO.authenticateUser(LoginDAO.java:26) [classes:]
at com.somecompany.loginDAO.LoginDAO$$FastClassBySpringCGLIB$$1909bedd.invoke(<generated>) [classes:]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) [spring-core-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:651) [spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at com.somecompany.loginDAO.LoginDAO$$EnhancerBySpringCGLIB$$45d26c87.authenticateUser(<generated>) [classes:]
at com.somecompany.loginService.LoginService.authenticateUser(LoginService.java:25) [classes:]
at com.somecompany.loginService.LoginService$$FastClassBySpringCGLIB$$3de2163d.invoke(<generated>) [classes:]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) [spring-core-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720) [spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) [spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) [spring-tx-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281) [spring-tx-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) [spring-tx-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) [spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655) [spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at com.somecompany.loginService.LoginService$$EnhancerBySpringCGLIB$$912637e7.authenticateUser(<generated>) [classes:]
at com.somecompany.loginController.LoginController.authenticateUser(LoginController.java:22) [classes:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.8.0_65]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) [rt.jar:1.8.0_65]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.8.0_65]
at java.lang.reflect.Method.invoke(Method.java:497) [rt.jar:1.8.0_65]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) [spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) [spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
... 30 more
But i have the named query on the entity as below
package com.somecompany.model;
import static javax.persistence.GenerationType.IDENTITY;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
import org.springframework.stereotype.Component;
#Entity
#Table(name = "pmd_user", catalog = "pmd", uniqueConstraints = {
#UniqueConstraint(columnNames = { "CUSTOMER_ID", "USER_NAME" }),
#UniqueConstraint(columnNames = "EMAIL_ADDRESS") })
#Component
#NamedQuery(name="findByUsername", query="SELECT u FROM PmdUser u WHERE u.userName = ?1")
public class PmdUser implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Long userId;
private PmdCustomer pmdCustomer;
private String userName;
private String emailAddress;
private Long phone;
private String firstName;
private String lastName;
private String password;
private Boolean passwordChangeRequired;
private Date lastPasswordChange;
private Long challengeQuestionId;
private String challengeAnswer;
private Boolean deactivated;
private Boolean deleted;
private Boolean isPreview;
private Boolean receiveEmail;
private Boolean isGuest;
private Boolean newsletter;
private String emailFormat;
private Date dateOfLastLogon;
private Long visits;
private String note;
private Long createdIp;
private Long updatedIp;
private Date dateCreated;
private Date dateUpdated;
private Long createdBy;
private Long updatedBy;
private List<PmdUserRole> pmdUserRoles = new ArrayList<PmdUserRole>(0);
public PmdUser() {
}
public PmdUser(String userName, String emailAddress) {
this.userName = userName;
this.emailAddress = emailAddress;
}
public PmdUser(PmdCustomer pmdCustomer, String userName, String emailAddress, Long phone, String firstName,
String lastName, String password, Boolean passwordChangeRequired, Date lastPasswordChange,
Long challengeQuestionId, String challengeAnswer, Boolean deactivated, Boolean deleted, Boolean isPreview,
Boolean receiveEmail, Boolean isGuest, Boolean newsletter, String emailFormat, Date dateOfLastLogon,
Long visits, String note, Long createdIp, Long updatedIp, Date dateCreated, Date dateUpdated,
Long createdBy, Long updatedBy, List<PmdUserRole> pmdUserRoles) {
this.pmdCustomer = pmdCustomer;
this.userName = userName;
this.emailAddress = emailAddress;
this.phone = phone;
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.passwordChangeRequired = passwordChangeRequired;
this.lastPasswordChange = lastPasswordChange;
this.challengeQuestionId = challengeQuestionId;
this.challengeAnswer = challengeAnswer;
this.deactivated = deactivated;
this.deleted = deleted;
this.isPreview = isPreview;
this.receiveEmail = receiveEmail;
this.isGuest = isGuest;
this.newsletter = newsletter;
this.emailFormat = emailFormat;
this.dateOfLastLogon = dateOfLastLogon;
this.visits = visits;
this.note = note;
this.createdIp = createdIp;
this.updatedIp = updatedIp;
this.dateCreated = dateCreated;
this.dateUpdated = dateUpdated;
this.createdBy = createdBy;
this.updatedBy = updatedBy;
this.pmdUserRoles = pmdUserRoles;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "USER_ID", unique = true, nullable = false)
public Long getUserId() {
return this.userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "CUSTOMER_ID")
public PmdCustomer getPmdCustomer() {
return this.pmdCustomer;
}
public void setPmdCustomer(PmdCustomer pmdCustomer) {
this.pmdCustomer = pmdCustomer;
}
#Column(name = "USER_NAME", nullable = false, length = 32)
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Column(name = "EMAIL_ADDRESS", unique = true, nullable = false, length = 128)
public String getEmailAddress() {
return this.emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
#Column(name = "PHONE")
public Long getPhone() {
return this.phone;
}
public void setPhone(Long phone) {
this.phone = phone;
}
#Column(name = "FIRST_NAME", length = 32)
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "LAST_NAME", length = 32)
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "PASSWORD", length = 128)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name = "PASSWORD_CHANGE_REQUIRED")
public Boolean getPasswordChangeRequired() {
return this.passwordChangeRequired;
}
public void setPasswordChangeRequired(Boolean passwordChangeRequired) {
this.passwordChangeRequired = passwordChangeRequired;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "LAST_PASSWORD_CHANGE", length = 19)
public Date getLastPasswordChange() {
return this.lastPasswordChange;
}
public void setLastPasswordChange(Date lastPasswordChange) {
this.lastPasswordChange = lastPasswordChange;
}
#Column(name = "CHALLENGE_QUESTION_ID")
public Long getChallengeQuestionId() {
return this.challengeQuestionId;
}
public void setChallengeQuestionId(Long challengeQuestionId) {
this.challengeQuestionId = challengeQuestionId;
}
#Column(name = "CHALLENGE_ANSWER", length = 128)
public String getChallengeAnswer() {
return this.challengeAnswer;
}
public void setChallengeAnswer(String challengeAnswer) {
this.challengeAnswer = challengeAnswer;
}
#Column(name = "DEACTIVATED")
public Boolean getDeactivated() {
return this.deactivated;
}
public void setDeactivated(Boolean deactivated) {
this.deactivated = deactivated;
}
#Column(name = "DELETED")
public Boolean getDeleted() {
return this.deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
#Column(name = "IS_PREVIEW")
public Boolean getIsPreview() {
return this.isPreview;
}
public void setIsPreview(Boolean isPreview) {
this.isPreview = isPreview;
}
#Column(name = "RECEIVE_EMAIL")
public Boolean getReceiveEmail() {
return this.receiveEmail;
}
public void setReceiveEmail(Boolean receiveEmail) {
this.receiveEmail = receiveEmail;
}
#Column(name = "IS_GUEST")
public Boolean getIsGuest() {
return this.isGuest;
}
public void setIsGuest(Boolean isGuest) {
this.isGuest = isGuest;
}
#Column(name = "NEWSLETTER")
public Boolean getNewsletter() {
return this.newsletter;
}
public void setNewsletter(Boolean newsletter) {
this.newsletter = newsletter;
}
#Column(name = "EMAIL_FORMAT", length = 4)
public String getEmailFormat() {
return this.emailFormat;
}
public void setEmailFormat(String emailFormat) {
this.emailFormat = emailFormat;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "DATE_OF_LAST_LOGON", length = 19)
public Date getDateOfLastLogon() {
return this.dateOfLastLogon;
}
public void setDateOfLastLogon(Date dateOfLastLogon) {
this.dateOfLastLogon = dateOfLastLogon;
}
#Column(name = "VISITS")
public Long getVisits() {
return this.visits;
}
public void setVisits(Long visits) {
this.visits = visits;
}
#Column(name = "NOTE", length = 65535)
public String getNote() {
return this.note;
}
public void setNote(String note) {
this.note = note;
}
#Column(name = "CREATED_IP")
public Long getCreatedIp() {
return this.createdIp;
}
public void setCreatedIp(Long createdIp) {
this.createdIp = createdIp;
}
#Column(name = "UPDATED_IP")
public Long getUpdatedIp() {
return this.updatedIp;
}
public void setUpdatedIp(Long updatedIp) {
this.updatedIp = updatedIp;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "DATE_CREATED", length = 19)
public Date getDateCreated() {
return this.dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "DATE_UPDATED", length = 19)
public Date getDateUpdated() {
return this.dateUpdated;
}
public void setDateUpdated(Date dateUpdated) {
this.dateUpdated = dateUpdated;
}
#Column(name = "CREATED_BY")
public Long getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(Long createdBy) {
this.createdBy = createdBy;
}
#Column(name = "UPDATED_BY")
public Long getUpdatedBy() {
return this.updatedBy;
}
public void setUpdatedBy(Long updatedBy) {
this.updatedBy = updatedBy;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pmdUser")
public List<PmdUserRole> getPmdUserRoles() {
return this.pmdUserRoles;
}
public void setPmdUserRoles(List<PmdUserRole> pmdUserRoles) {
this.pmdUserRoles = pmdUserRoles;
}
#Override
public String toString() {
return "PmdUser [userId=" + userId + ", userName=" + userName + ", emailAddress=" + emailAddress
+ ", firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
I suspect this is due to an integration issue with spring and JPA as the same query works fine in a unit test.
Has anybody faced this issue before ? or Is my JPA configuration not complete ?
Refer to your persistence xml location :
containerEntityManagerFactoryBean.setPersistenceXmlLocation("classpath:...");
Refer to your entities either from persistence xml OR
containerEntityManagerFactoryBean.setPackagesToScan("com.somecomany.model");
And you are configuring repositories from the wrong location, change :
#EnableJpaRepositories(basePackages="com.somecompany.model.*")
to :
#EnableJpaRepositories(basePackages="com.somecompany")
The issue was with the class deceleration in the Persistence.xml file previously the deceleration was as below
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="pmd-web">
<description>project metrics dashboard</description>
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
</properties>
</persistence-unit>
and had to change it to have the class declarations
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="pmd-web">
<class>com.somecompany.model.PmdCustomer</class>
<class>com.somecompany.model.CustomerModule</class>
<class>com.somecompany.model.Modules</class>
<class>com.somecompany.model.Project</class>
<class>com.somecompany.model.ProjectRelease</class>
<class>com.somecompany.model.ProjectSprint</class>
<class>com.somecompany.model.Role</class>
<class>com.somecompany.model.User</class>
<class>com.somecompany.model.UserRole</class>
</persistence-unit>

Categories

Resources