Issue
I’m trying to upgrade some components of an old legacy war application and have run into trouble when upgrading to Hibernate 5.6. Hibernate is now no longer able to map my User entity and I'm not sure why.
Any help would be highly appreciated. Let me know if you need additional info.
EDIT: Added HibernateUtil
Error:
com.myapp.hibernate.exception.MyAppHibernateException: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped [FROM User WHERE username = :username]
at com.myapp.hibernate.HibernateManager.getUser(HibernateManager.java:97)
at com.myapp.servlets.LoginServlet.doPost(LoginServlet.java:46)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at com.myapp.filter.SessionFilter.doFilter(SessionFilter.java:61)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at com.myapp.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:36)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at com.myapp.filter.PropertiesLoadErrorFilter.doFilter(PropertiesLoadErrorFilter.java:48)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at com.myapp.filter.RequestFilter.doFilter(RequestFilter.java:29)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:890)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1789)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:750)
Failing code:
public User getUser(String username) throws MyAppHibernateException {
try {
Query query = getSession().createQuery("FROM User WHERE username = :username");
query.setParameter("username", username);
List<User> users = query.list();
User user = null;
if (users.size() > 0)
user = users.get(0);
return user;
} catch (Exception e) {
logger.error(e.getMessage());
throw new MyAppHibernateException(e.getMessage());
}
}
hibernate.cfg.xml (located in WEB-INF/classes)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.transaction.coordinator_class">jdbc</property>
<property name="dialect">org.hibernate.dialect.PostgreSQL10Dialect</property>
<property name="show_sql">true</property>
<property name="current_session_context_class">thread</property>
<!-- Connection pool -->
<property name="c3p0.min_size">5</property>
<property name="c3p0.max_size">15</property>
<property name="c3p0.timeout">300</property>
<property name="c3p0.max_statements">50</property>
<property name="c3p0.idle_test_period">3000</property>
<!-- Mapping resource configuration files -->
<mapping class="com.myapp.hibernate.models.User" />
</session-factory>
</hibernate-configuration>
HibernateUtil
package com.myapp.hibernate;
import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import com.myapp.properties.MyProperties;
public class HibernateUtil {
private static ServiceRegistry serviceRegistry;
private static final SessionFactory sessionFactory;
private static Logger logger = Logger.getLogger(HibernateUtil.class.getName());
static {
try {
logger.info("Statically initializing Hibernate Session Factory");
Configuration configuration = new Configuration()
.setProperty("hibernate.connection.url", MyProperties.getHibernateUrl())
.setProperty("hibernate.connection.username", MyProperties.getHibernateUser())
.setProperty("hibernate.connection.password", MyProperties.getHibernatePwd());
if (MyProperties.getHibernateHbm2ddl_auto() != null) {
configuration.setProperty("hibernate.hbm2ddl.auto", MyProperties.getHibernateHbm2ddl_auto());
}
configuration.configure("hibernate.cfg.xml");
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
logger.info("Failed to create sessionFactory object. " + ex.getMessage());
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
User entity
package com.myapp.hibernate.models;
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.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "user_")
public class User {
@Id
@SequenceGenerator(name = "user_seq", sequenceName = "user_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
@Column(name = "id", unique = true)
private int identifier;
@Column(name = "username", unique = true)
private String username;
@Column(name = "password")
private String password;
@Column(name = "firstName", nullable = false)
private String firstName;
@Column(name = "lastName", nullable = false)
private String lastName;
public User() {
super();
}
public User(String username, String password, String firstName, String lastName) {
super();
this.username = username;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
}
}
SQL
CREATE TABLE "public"."user_" (
"id" int4 NOT NULL,
"firstname" varchar(255) COLLATE "pg_catalog"."default" NOT NULL,
"lastname" varchar(255) COLLATE "pg_catalog"."default" NOT NULL,
"password" varchar(255) COLLATE "pg_catalog"."default",
"username" varchar(255) COLLATE "pg_catalog"."default",
);
Solution
The problem is due to below configuration(seems most Hibernate tutorial configuration is like this)
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
It is not working in Hibernate 5, the reason may be due to Service Registry API update.
The fix is to simply write it
sessionFactory = configuration.configure("hibernate.cfg.xml").buildSessionFactory();
by referring to 3.8. XML configuration file
Answered By - samabcde
Answer Checked By - Gilberto Lyons (JavaFixing Admin)