Hibernate unable to map entity - QuerySyntaxException - java

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",
);

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

Related

Spring MVC with multiple database connections

Hello I am building my first Spring MVC and Thymeleaf web app and I do not know how to connect to two different Oracle databases. I managed to connect to just one.
Here is the code:
Repository code:
package com.example.demo;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
/**
*
* #author 40723
*/
#Repository
public class TelefonMailRepositoryImpl implements TelefonMailRepository {
private final DataSource dataSourceMail;
private final DataSource inregIvg;
public TelefonMailRepositoryImpl(DataSource dataSourceMail, #Qualifier("inregIvg") DataSource inregIvg) {
this.dataSourceMail = dataSourceMail;
this.inregIvg = inregIvg;
}
public Map<String, Object> findByNumber(String telefon) {
Map<String, Object> toateTel;
String query = "select cnp, nume, prenume from utilizatori where telefon=?";
JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSourceMail);
jdbcTemplate.queryForMap(query,telefon);
Map<String, Object> info1 = jdbcTemplate.queryForMap(query,telefon);
// return info1;
String query2 = "select cif, den_client from b101_conturi where telefon=?";
JdbcTemplate jdbcTemplate2 = new JdbcTemplate(this.inregIvg);
Map<String, Object> info2 = jdbcTemplate.queryForMap(query2,telefon);
if(info2.isEmpty()) {
return info1;
} else {
return info2;
}
}
public Map<String, Object> findByEmail(String email) {
String query = "select cnp, nume, prenume from utilizatori where upper(email)=upper(?)";
JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSourceMail);
Map<String, Object> info1 = jdbcTemplate.queryForMap(query, email);
String query2 = "select cif, den_client from b101_conturi where upper(email)=upper(?)";
JdbcTemplate jdbcTemplate2 = new JdbcTemplate(this.inregIvg);
Map<String, Object> info2 = jdbcTemplate2.queryForMap(query2,email);
if(info2.isEmpty()) {
return info1;
} else {
return info1;
}
}
public DataSource getDataSourceMail() {
return dataSourceMail;
}
}
This is the DbConfig file:
package com.example.demo;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
/**
*
* #author 40723
*/
#Configuration
public class DbConfig {
#Bean
#Primary
#ConfigurationProperties("app.datasource.dsmail")
public DataSourceProperties dsmailDataSourceProperties() {
return new DataSourceProperties();
}
#Bean(name="DSMail")
#Primary
#ConfigurationProperties("app.datasource.dsmail.configuration")
public HikariDataSource dataSourceMail() {
return dsmailDataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();
}
#Bean
#ConfigurationProperties("app.datasource.inregivg")
public DataSourceProperties inregIvgDataSourceProperties() {
return new DataSourceProperties();
}
#Bean(name = "inregIvg")
#ConfigurationProperties("app.datasource.inregivg.configuration")
public HikariDataSource dataSourceInregIvg() {
return inregIvgDataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();
}
}
And here are the application properties:
app.datasource.dsmail.username=xxx
app.datasource.dsmail.password=xxx
app.datasource.dsmail.url=dburl:123
app.datasource.dsmail.driver-class-name=oracle.jdbc.OracleDriver
app.datasource.dsmail.configuration.pool-name=DSMailPool
app.datasource.dsmail.configuration.auto-commit=false
app.datasource.inregivg.username=yyy
app.datasource.inregivg.password=yyy
app.datasource.inregivg.url=dburl2:321
app.datasource.inregivg.driver-class-name=oracle.jdbc.OracleDriver
app.datasource.inregivg.configuration.pool-name=DSInregivgPool
app.datasource.inregivg.configuration.auto-commit=false
I have changed the user, pass, and url of application props because of security reasons.
Can you tell me what I am doing wrong ?
The error that I get is:
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Mar 21 12:00:20 EET 2022
There was an unexpected error (type=Internal Server Error, status=500).
PreparedStatementCallback; bad SQL grammar [select cif, den_client from b101_conturi where telefon=?]; nested exception is java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [select cif, den_client from b101_conturi where telefon=?]; nested exception is java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:239)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:70)
at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1541)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:667)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:713)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:744)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:757)
at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:879)
at org.springframework.jdbc.core.JdbcTemplate.queryForMap(JdbcTemplate.java:916)
at com.example.demo.TelefonMailRepositoryImpl.findByNumber(TelefonMailRepositoryImpl.java:56)
at com.example.demo.TelefonMailRepositoryImpl$$FastClassBySpringCGLIB$$ecef6002.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:783)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:753)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:753)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:698)
at com.example.demo.TelefonMailRepositoryImpl$$EnhancerBySpringCGLIB$$637cc014.findByNumber(<generated>)
at com.example.demo.TelefonMailService.getRaspuns(TelefonMailService.java:25)
at com.example.demo.TelefonMailController.postDbRequest(TelefonMailController.java:36)
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:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
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:681)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
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 org.springframework.web.servlet.resource.ResourceUrlEncodingFilter.doFilter(ResourceUrlEncodingFilter.java:67)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
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:540)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:359)
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:889)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1735)
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:748)
Caused by: java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist
at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:630)
at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:564)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1151)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:771)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:299)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:498)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:152)
at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:937)
at oracle.jdbc.driver.OracleStatement.prepareDefineBufferAndExecute(OracleStatement.java:1172)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1101)
at oracle.jdbc.driver.OracleStatement.executeSQLSelect(OracleStatement.java:1426)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1309)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3746)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3855)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1098)
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52)
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java)
at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:722)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:651)
... 71 more
Caused by: Error : 942, Position : 28, Sql = select cif, den_client from b101_conturi where telefon=:1 , OriginalSql = select cif, den_client from b101_conturi where telefon=?, Error Msg = ORA-00942: table or view does not exist
at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:637)
... 89 more
Just as a reminder with one connection it works it retrieves the desired info but with two datasources it does not work. I made the select that spits the error in Toad and it works so the tabvle exists. Thanks in advance. Have a nice day !
The connection is successful but it can't be find a table in db. I think you need to separate package of models by each db and the configuration class should be know the package name for each db. For example for JPA:
#Configuration
#EnableJpaRepositories(
basePackages = "com.project.modelpackage"
)
public class ClassName { ... }

How to connect to SQL Server 2017 using Hibernate and Windows Authentication?

Full MCVE is at the bottom of this post.
I am trying to run a very basic Hibernate example as I work through a tutorial. However, I am receiving the following error: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]:
Exception in thread "main" java.lang.ExceptionInInitializerError
at hibernateTutorial.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:50)
at hibernateTutorial.util.HibernateUtil.getSessionFactory(HibernateUtil.java:30)
at hibernateTutorial.main.HibernateMain.main(HibernateMain.java:21)
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:176)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:127)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:86)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:479)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:85)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:709)
at hibernateTutorial.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:47)
... 2 more
Caused by: org.vibur.dbcp.ViburDBCPException: java.lang.NullPointerException
at org.vibur.dbcp.ViburDBCPDataSource.start(ViburDBCPDataSource.java:233)
at org.hibernate.vibur.internal.ViburDBCPConnectionProvider.configure(ViburDBCPConnectionProvider.java:57)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:107)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:246)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
... 15 more
Caused by: java.lang.NullPointerException
at java.util.Hashtable.put(Hashtable.java:460)
at java.util.Properties.setProperty(Properties.java:166)
at org.vibur.dbcp.pool.Connector$Builder$Driver.<init>(Connector.java:66)
at org.vibur.dbcp.pool.Connector$Builder$Driver.<init>(Connector.java:56)
at org.vibur.dbcp.pool.Connector$Builder.buildConnector(Connector.java:48)
at org.vibur.dbcp.ViburDBCPDataSource.doStart(ViburDBCPDataSource.java:248)
at org.vibur.dbcp.ViburDBCPDataSource.start(ViburDBCPDataSource.java:226)
... 24 more
My database is on a Microsoft SQL Server 2017 instance that uses Windows Authentication. I have added both the MSSQL JDBC (v6.4.0) updated IntelliJ with the -Djava.library.path VM option so that sqljdbc_auth.dll (required for Windows Authentication) is accessible.
From what I can tell in my research into this ambiguous error message, it could have many different causes, but ultimately boils down to just not being able to connect to the database somehow. Most of the other Q&A I've found seems to be specific to other databases or SQL Server that doesn't use Windows Authentication.
I have copied the JDBC URL directly from my datasource config in IntelliJ so I know that it is correct and works properly in the IDE.
What else is required to properly configure Hibernate to connect to SQL Server?
HibernateMain.java:
package hibernateTutorial.main;
import hibernateTutorial.model.Employee;
import hibernateTutorial.util.HibernateUtil;
import org.hibernate.Session;
import java.time.LocalDateTime;
public class HibernateMain {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setName("Nathan");
emp.setRole("CEO");
emp.setInsertTime(LocalDateTime.now());
// **********************************************************************************************
// Get Session
// **********************************************************************************************
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
// **********************************************************************************************
// Start transaction
// **********************************************************************************************
session.beginTransaction();
// **********************************************************************************************
// Save the model object
// **********************************************************************************************
session.save(emp);
// **********************************************************************************************
// Commit the transaction
// **********************************************************************************************
session.getTransaction().commit();
System.out.println("Employee ID: " + emp.getId());
// **********************************************************************************************
// Terminate the session factory or the program won't end
// **********************************************************************************************
HibernateUtil.getSessionFactory().close();
}
}
HibernateUtil.java:
package hibernateTutorial.util;
import hibernateTutorial.model.Employee1;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import java.util.Properties;
public class HibernateUtil {
// **********************************************************************************************
// XML-based configuration
// **********************************************************************************************
private static SessionFactory sessionFactory;
// **********************************************************************************************
// Annotation-based configuration
// **********************************************************************************************
private static SessionFactory sessionAnnotationFactory;
// **********************************************************************************************
// Property-based configuration
// **********************************************************************************************
private static SessionFactory sessionJavaConfigFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) sessionFactory = buildSessionFactory();
return sessionFactory;
}
private static SessionFactory buildSessionFactory() {
try {
// **********************************************************************************************
// Create the SessionFactory from hibernate.cfg.xml
// **********************************************************************************************
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
System.out.println("Hibernate configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate serviceRegistry created");
return configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable e) {
System.err.println("Initial SessionFactory creation failed. " + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionAnnotationFactory() {
if (sessionAnnotationFactory == null) sessionAnnotationFactory = buildSessionAnnotationFactory();
return sessionAnnotationFactory;
}
private static SessionFactory buildSessionAnnotationFactory() {
try {
// **********************************************************************************************
// Create the SessionFactory from hibernate-annotation.cfg.xml
// **********************************************************************************************
Configuration configuration = new Configuration();
configuration.configure("hibernate-annotation.cfg.xml");
System.out.println("Hibernate Annotation configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Annotation serviceRegistry created");
return configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable e) {
System.err.println("Initial SessionFactory creationg failed." + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionJavaConfigFactory() {
if (sessionJavaConfigFactory == null) sessionJavaConfigFactory = buildSessionJavaConfigFactory();
return sessionJavaConfigFactory;
}
private static SessionFactory buildSessionJavaConfigFactory() {
try {
Configuration configuration = new Configuration();
//Create Properties, can be read from property files too
Properties props = new Properties();
props.put("hibernate.connection.driver_class", "com.microsoft.sqlserver.jdbc.SQLServerDriver");
props.put("hibernate.connection.url", "jdbc:sqlserver://FADBOKT2493V\\KRAFTLAKEODB:51678;database=Dev_RepAssistDB;integratedSecurity=true");
props.put("hibernate.current_session_context_class", "thread");
configuration.setProperties(props);
//we can set mapping file or class with annotation
//addClass(Employee1.class) will look for resource
// com/journaldev/hibernate/model/Employee1.hbm.xml (not good)
configuration.addAnnotatedClass(Employee1.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Java Config serviceRegistry created");
return configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
}
Employee.java:
package hibernateTutorial.model;
import java.time.LocalDateTime;
public class Employee {
private int id;
private String name;
private String role;
private LocalDateTime insertTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public LocalDateTime getInsertTime() {
return insertTime;
}
public void setInsertTime(LocalDateTime insertTime) {
this.insertTime = insertTime;
}
}
Employee1.java:
package hibernateTutorial.model;
import javax.persistence.*;
import java.time.LocalDateTime;
#Entity
#Table(name = "tmp_employees",
uniqueConstraints =
{#UniqueConstraint(columnNames = {"id"})})
public class Employee1 {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, unique = true, length = 11)
private int id;
#Column(name = "name", length = 20, nullable = true)
private String name;
#Column(name = "role", length = 20, nullable = true)
private String role;
#Column(name = "insert_time", nullable = true)
private LocalDateTime insertTime;
}
employee.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"https://hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="hibernateTutorial.model.Employee" table="tmp_employees">
<id name="id" type="int">
<column name="id"/>
<generator class="increment"/>
</id>
<property name="name" type="java.lang.String">
<column name="name"/>
</property>
<property name="role" type="java.lang.String">
<column name="role"/>
</property>
<property name="insertTime" type="java.time.LocalDateTime">
<column name="insert_time"/>
</property>
</class>
</hibernate-mapping>
hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"https://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection properties - Driver, URL, user, password -->
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://servername:port;
database=test_db;integratedSecurity=true
</property>
<!-- Connection Pool Size -->
<property name="hibernate.connection.pool_size">5</property>
<!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- Outputs the SQL queries, should be disabled in Production -->
<property name="hibernate.show_sql">true</property>
<!-- Dialect is required to let Hibernate know the Database Type, MySQL, Oracle etc
Hibernate 4 automatically figure out Dialect from Database Connection Metadata -->
<property name="hibernate.dialect">org.hibernate.dialect.SQLServer2012Dialect</property>
<!-- mapping file, we can use Bean annotations too -->
<mapping resource="hibernateTutorial/employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
hibernate-annotation.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"https://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection properties - Driver, URL, user, password -->
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver:servername:port;database=test_db;integratedSecurity=true</property>
<!-- Connection Pool Size -->
<property name="hibernate.connection.pool_size">5</property>
<!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- Outputs the SQL queries, should be disabled in Production -->
<property name="hibernate.show_sql">true</property>
<!-- Dialect is required to let Hibernate know the Database Type, MySQL, Oracle etc
Hibernate 4 automatically figure out Dialect from Database Connection Metadata -->
<property name="hibernate.dialect">org.hibernate.dialect.SQLServer2012Dialect</property>
<!-- mapping with model class containing annotations -->
<mapping class="hibernateTutorial.model.Employee1"/>
</session-factory>
</hibernate-configuration>

Null pointer exception Custom Validation in spring + hibernate

My Custom Validation Classes
1.UserAvailablity.java
package com.vicky.finalYearProject.customValidations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
#Constraint(validatedBy = UserAvailabilityValidator.class)
#Target({ElementType.METHOD, ElementType.FIELD})
#Retention(RetentionPolicy.RUNTIME)
public #interface UserAvailability {
public String message() default "Email is already Registered";
public Class<?>[] groups() default { };
public Class<? extends Payload>[] payload() default { };
}
2.UserAvailabilityValidator.class
package com.vicky.finalYearProject.customValidations;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;
import com.vicky.finalYearProject.Service.CheckUserAvailabilityService;
public class UserAvailabilityValidator implements ConstraintValidator<UserAvailability, String>{
#Autowired
CheckUserAvailabilityService availabilityService;
#Override
public void initialize(UserAvailability constraintAnnotation) {
ConstraintValidator.super.initialize(constraintAnnotation);
}
#Override
public boolean isValid(String email, ConstraintValidatorContext context) {
boolean available = false;
available = availabilityService.isAvailable(email);//return true or false
return available;
}
}
My Entities
User.java
package com.vicky.finalYearProject.Entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
import org.springframework.stereotype.Component;
import com.vicky.finalYearProject.customValidations.UserAvailability;
#Entity
#Component
#Table( name = "customers",
uniqueConstraints=
#UniqueConstraint(columnNames={"email"})
)
public class User {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#NotNull
#Column(name = "email", length = 50)
#Pattern(regexp = "^([a-zA-Z0-9_\\-\\.]+)#([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5})$")
#UserAvailability//custom validator
private String email;
#NotNull
#Column(name = "password")
#Length(min = 1 , message = "Enter Valid Password")
private String password;
#NotNull
#Column(name = "firstName")
#Length(min = 1 , message = "Enter Valid firstName")
private String firstName;
#NotNull
#Column(name = "middleName")
#Length(min = 1 , message = "Enter Valid middleName")
private String middleName;
#NotNull
#Column(name = "lastName")
#Length(min = 1 , message = "Enter Valid lastName")
private String lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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;
}
#Override
public String toString() {
return "User [id=" + id + ", email=" + email + ", password=" + password + ", firstName=" + firstName
+ ", middleName=" + middleName + ", lastName=" + lastName + "]";
}
}
My xml form Mapping with User class... by form:form
*
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix= "form" uri ="http://www.springframework.org/tags/form" %>
<body bgcolor = "black">
<h1 style="color: white">ADD USER INFORMATION</h1>
<hr>
<div style="color: white">
<form:form action ="${pageContext.request.contextPath}/user/conformation"
modelAttribute="user"
method="post">
First Name : <form:input path="firstName"/>
<form:errors path ="firstName" cssClass="error"/>
<br><br>
Middle Name: <form:input path="middleName"/>
<form:errors path ="middleName" cssClass="error"/>
<br><br>
Last Name: <form:input path="lastName"/>
<form:errors path ="lastName" cssClass="error"/>
<br><br>
Email : <form:input path="email"/>
<form:errors path ="email" cssClass="error"/>
<br><br>
password : <form:input type="password" path="password"/>
<form:errors path ="password" cssClass="error"/>
<br><br>
<input type = "Submit" value="next"/>
</form:form>
</div>
<hr>
cancle
</body>
</html>
*
ERROR I GOT when I submit My jsp page
Aug 11, 2020 12:29:33 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select user0_.id as id1_0_, user0_.email as email2_0_, user0_.firstName as firstNam3_0_, user0_.lastName as lastName4_0_, user0_.middleName as middleNa5_0_, user0_.password as password6_0_ from customers user0_ where user0_.email='sdghag#jsjdhak.zdhzg'
Aug 11, 2020 12:29:40 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/finalYearProject2] threw exception [Request processing failed; nested exception is javax.validation.ValidationException: HV000028: Unexpected exception during isValid call.] with root cause
java.lang.NullPointerException
at com.vicky.finalYearProject.customValidations.UserAvailabilityValidator.isValid(UserAvailabilityValidator.java:26)
at com.vicky.finalYearProject.customValidations.UserAvailabilityValidator.isValid(UserAvailabilityValidator.java:1)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:180)
at org.hibernate.validator.internal.engine.constraintvalidation.SimpleConstraintTree.validateConstraints(SimpleConstraintTree.java:62)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:75)
at org.hibernate.validator.internal.metadata.core.MetaConstraint.doValidateConstraint(MetaConstraint.java:130)
at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:123)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:555)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForSingleDefaultGroupElement(ValidatorImpl.java:518)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:488)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:450)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:400)
at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:172)
at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:116)
at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreInsert(BeanValidationEventListener.java:80)
at org.hibernate.action.internal.EntityIdentityInsertAction.preInsert(EntityIdentityInsertAction.java:197)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:75)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:645)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:282)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:317)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:332)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:289)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:196)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:127)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
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:713)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:705)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:700)
at com.vicky.finalYearProject.DAO.UserDaoImplimantation.addUser(UserDaoImplimantation.java:16)
at com.vicky.finalYearProject.Service.PurchaseService.purchase(PurchaseService.java:46)
at com.vicky.finalYearProject.Controller.UserController.purchaseconformed(UserController.java:74)
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.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:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)
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.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
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.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:117)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
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.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
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.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)
Hibernaete.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>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">120699#mysqL</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/final_year_project</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
Spring Configuration
1.ViewResolverConfigrationClass.java
package com.vicky.finalYearProject.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.vicky.finalYearProject")
public class ViewResolverConfigrationClass {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewresolver = new InternalResourceViewResolver();
viewresolver.setPrefix("/WEB-INF/view/");
viewresolver.setSuffix(".jsp");
return viewresolver;
}
}
2.DispecherServletConfigClass.java
package com.vicky.finalYearProject.Configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class DispecherServletConfigClass extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {ViewResolverConfigrationClass.class};
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
I tried alot to figure out Even it works well without #UserAvailability in User.java Class
EVEN it works well with #UserAvailability when UserAvailabilityValidator.IsValid() returns false
Can Anyone please solve this issue For me...Thank you`enter code here
I THINK HIBERNATE IS AGAIN VALIDATING ALL CONSTRAINT AFTER SPRING THIS ERROR ERROR IS COME WHEN I TRY TO USE SAVE METHOD IN HIBERNATE
UserController.java
package com.vicky.finalYearProject.Controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.vicky.finalYearProject.Entity.Department;
import com.vicky.finalYearProject.Entity.Student;
import com.vicky.finalYearProject.Entity.University;
import com.vicky.finalYearProject.Service.StudentSignupService;
#Controller
#RequestMapping("/student")
public class StudentController {
#Autowired
Student student;
#Autowired
StudentSignupService studentSignupSvc;
List<String> universities;
List<String> departments;
#GetMapping("/signup")
public String studentLogin(Model model) {
universities = studentSignupSvc.getAllUniversity();
departments = studentSignupSvc.getAllDepartment();
model.addAttribute("student", student);
model.addAttribute("universityOptions", universities);
model.addAttribute("departmentOptions", departments);
return "student/signup";
}
#PostMapping("/conformation")
public String studentConformation(
#Valid #ModelAttribute("student") Student student,
BindingResult result,
Model model,
HttpServletRequest request) {
if(result.hasErrors()) {
model.addAttribute("universityOptions", universities);
model.addAttribute("departmentOptions", departments);
return "student/signup";
}
else {
String universityName = (String)request.getParameter("theUniversity");
String departmentName = (String)request.getParameter("theDepartment");
University university = studentSignupSvc.getUniversity(universityName);
Department department = studentSignupSvc.getDepartment(departmentName);
student.setUniversity(university);
student.setDepartment(department);
studentSignupSvc.signup(student); //CAUSE OF ERROR If I comment this line everything work fine
//and sigup service is perfactly auto wired i checked it.
return "student/studentConformation";
}
}
}
In the UserAvailabilityValidator class, is the availabilityService well autowired ? If the service is null, you will have this error.
Spring ought to inject dependencies into any ConstraintValidator-implementing class, even without marking them as #Bean or #Component, so I'm guessing you are missing the spring wiring.
Do you have a LocalValidatorFactoryBean in your spring configuration? From the documentation:
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
#Configuration
public class AppConfig {
#Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
}

Java Spring table doesn't exist

I'm writing a web app by using Spring and Hibernate but facing this kind of problem for the first time. Whenever I run my app on the server it says **"java.sql.SQLSyntaxErrorException: Table 'restaurantapp.users' doesn't exist."**The thing that I don't understand is I don't even have a table called "users" in my database and also I've never used a table "users" in my app. Code parts are below. Need help to solve this.
Entity class:
package com.jafndy.Restaurant.entity;
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="admin_login")
public class RestaurantAdmin {
#Id
#Column(name="user_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int user_id;
#Column(name="username")
private String username;
#Column(name="authority")
private String authority;
#Column(name="email")
private String email;
#Column(name="password")
private String password;
public RestaurantAdmin(int user_id, String username, String authority,
String email, String password) {
super();
this.user_id = user_id;
this.username = username;
this.authority = authority;
this.email = email;
this.password = password;
}
public RestaurantAdmin() {
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "RestaurantAdmin [user_id=" + user_id + ", username=" + username + ", authority=" + authority
+ ", email=" + email + ", password=" + password + "]";
}
}
Config classes:
package com.jafndy.Restaurant.config;
import java.beans.PropertyVetoException;
import java.util.Properties;
import javax.sql.DataSource;
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.PlatformTransactionManager;
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.view.InternalResourceViewResolver;
import com.mchange.v2.c3p0.ComboPooledDataSource;
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan(basePackages="com.jafndy.Restaurant")
#PropertySource("classpath:persistence-mysql.properties")
public class AppConfig {
//set up variable to hold variables
#Autowired
private Environment env;
//define a bean for the view resolver
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new
InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
//define a bean for security datasource
#Bean
public DataSource securityDataSource() {
//create a connection pool
ComboPooledDataSource securityDataSource = new ComboPooledDataSource();
//set the jdbc driver class
try {
securityDataSource.setDriverClass(env.getProperty("jdbc.driver"));
}catch(PropertyVetoException exc){
throw new RuntimeException();
}
//set database connection properties
securityDataSource.setJdbcUrl(env.getProperty("jdbc.url"));
securityDataSource.setUser(env.getProperty("jdbc.user"));
securityDataSource.setPassword(env.getProperty("jdbc.password"));
//set connection pool properties
securityDataSource.setInitialPoolSize(getIntProperty("connection.pool.initialPoolSize"));
securityDataSource.setMinPoolSize(getIntProperty("connection.pool.minPoolSize"));
securityDataSource.setMaxPoolSize(getIntProperty("connection.pool.maxPoolSize"));
securityDataSource.setMaxIdleTime(getIntProperty("connection.pool.maxIdleTime"));
return securityDataSource;
}
//define a bean for Hibernate
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(securityDataSource());
sessionFactory.setPackagesToScan("com.jafndy.Restaurant.entity");
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public PlatformTransactionManager hibernateTransactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
private final Properties hibernateProperties() {
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
hibernateProperties.setProperty("hibernate.show_sql", "true");
return hibernateProperties;
}
//helper method
//read environment property and convert it to int
private int getIntProperty(String propName) {
String propValue = env.getProperty(propName);
int intPropValue = Integer.parseInt(propValue);
return intPropValue;
}
}
package com.jafndy.Restaurant.config;
import
org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MySpringMvcDispatcherServletInitializer 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[] {"/"};
}
}
package com.jafndy.Restaurant.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//add a reference to our security DataSource
#Autowired
private DataSource securityDataSource;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(securityDataSource);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").hasAnyRole("CUSTOMER","ADMIN")
.antMatchers("/systems/**").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/authenticateUser")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.exceptionHandling().accessDeniedPage("/access-denied");
}
}
package com.jafndy.Restaurant.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}
Controller clases:
package com.jafndy.Restaurant.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class RestaurantControllerLogin {
#GetMapping("/login")
public String loginPage() {
return "login-page";
}
}
package com.jafndy.Restaurant.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class RestaurantController {
#GetMapping("/")
public String showHome() {
return "home";
}
}
persistence-mysql.properties file
#
# JDBC connection libraries
#
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/restaurantapp?useSSL=false
jdbc.user=restaurant
jdbc.password=restaurant_1_2_3
#
# Connection pool properties
#
connection.pool.initialPoolSize=5
connection.pool.minPoolSize=5
connection.pool.maxPoolSize=20
connection.pool.maxIdleTime=3000
#
# Setup Hibernate session factory
#
hibernate.packagesToScan=com.jafndy.Restaurant.entity
login-page.jsp
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<style>
.error{
color: red;
}
.logout{
color: green;
}
</style>
</head>
<body>
<h2>Restaurant Login</h2>
<form:form action="${pageContext.request.contextPath}/authenticateUser"
method="POST">
<c:if test="${param.error != null }">
<b class="error">Invalid username or password</b>
</c:if>
<c:if test="${param.logout != null }">
<i class="logout">You've been logged out</i>
</c:if>
<p>
Username: <input type="text" name="username"/>
</p>
<p>
Password: <input type="password" name="password"/>
</p>
<input type="submit" value="Log in"/>
</form:form>
</body>
</html>
home.jsp
<!DOCTYPE html>
<html>
<head>
<style>
h1{
display: none;
}
</style>
</head>
<body>
<h1 id="h1hidden"></h1>
<button
onclick="document.getElementById('h1hidden').style.display='block'">Click to
see</button>
</body>
</html>
And my error log
org.springframework.security.authentication.InternalAuthenticationServiceException: PreparedStatementCallback; bad SQL grammar [select username,password,enabled from users where username = ?]; nested exception is java.sql.SQLSyntaxErrorException: Table 'restaurantapp.users' doesn't exist
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:119)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:144)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:199)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:124)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
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(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [select username,password,enabled from users where username = ?]; nested exception is java.sql.SQLSyntaxErrorException: Table 'restaurantapp.users' doesn't exist
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:235)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1402)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:620)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:657)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:688)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:700)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:751)
at org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl.loadUsersByUsername(JdbcDaoImpl.java:227)
at org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl.loadUserByUsername(JdbcDaoImpl.java:184)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:104)
... 42 more
Caused by: java.sql.SQLSyntaxErrorException: Table 'restaurantapp.users' doesn't exist
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:118)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:960)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1019)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:76)
at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:666)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:605)
... 49 more
This is searching for users table from the user service of spring security. You need to either provide right configuration related to spring security or you can use in memory database and hardcore some dummy users along with roles. So apparently it is the problem of spring security configuration issue at this point. Hope it helps.. I am not in front of my laptop right now, will debug and post more preciously later.
Thats the kind of magic that Spring provides. When you configure Spring security with jdbcAuthentication(), Spring will use the default DaoAuthenticationProvider to authenticate incoming requests. You have created you own User class but Spring is unable to detect it, so it uses JdbcDaoImpl as the default implementation of UserDetailsService.
A closer look into the source gives the following information:
Default Schema A default database schema is assumed, with two tables "users"
and "authorities". (Source)
So, in order to use you own implementation, you have to provide a custom implementation of UserDetailsService, which loads users from your own table.

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped [from User]

I'm getting java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped [from User] error. I've gone through these question, but didn't helped me.
org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped
Hibernate error - QuerySyntaxException: users is not mapped [from users]
Database table image:
Database Table user.jpg
UserBean.java
package model;
import java.util.ArrayList;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import controller.Login;
import controller.userinfo;
import gfgshfhjdgfhjdhhjfhjd.iModel;
#Entity
#Table(name= "User")
public class UserBean implements iModel
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="Id")
private int id;
#Column(name="Username")
private String username ;
#Column(name="Password")
private String password ;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
public UserBean(){}
public ArrayList<?> getData() {
return userinfo.getUser();
}
}
Userinfo.java
package controller;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import model.UserBean;
import test.HibernateSessionFactory;
public class Userinfo {
public static void saveUser(UserBean user) {
Session session = HibernateSessionFactory.getSessionFactory().openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
public static ArrayList<?> getUser() {
Session session = HibernateSessionFactory.getSessionFactory().openSession();
session.beginTransaction();
List<UserBean> list = (List<UserBean>)session.createQuery("from User").list();
ArrayList<String> list2= new ArrayList<String>();
for(int i=0;i<list.size();i++) {
int tmp = list.get(i).getId();
StringBuilder sBuilder = new StringBuilder();
sBuilder.append(tmp);
list2.add(sBuilder.toString());
list2.add(list.get(i).getUsername());
list2.add(list.get(i).getPassword());
}
if (list != null) {
for (int i = 0; i < list.size(); i++) {
System.out.println("User ID : " + list.get(i).getId());
System.out.println("User First Name : "+ list.get(i).getUsername());
System.out.println("User Last Name : "+ list.get(i).getPassword());
}
}
session.getTransaction().commit();
return list2;
}
}
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/project</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="show_sql">true</property>
<!-- Specifying Session Context -->
<property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>
<!-- <property name="hibernate.hbm2ddl.auto">create</property> -->
<!-- Mapping With Model Class Containing Annotations -->
<mapping class="model.UserBean" />
</session-factory>
</hibernate-configuration>
Error Log:
May 06, 2018 4:16:04 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped [from User]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:133)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:164)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:670)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:103)
at controller.Userinfo.getUser(Userinfo.java:28)
at model.UserBean.getData(UserBean.java:55)
at controller.Login.doGet(Login.java:38)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2430)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2419)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped [from User]
at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79)
at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:217)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:141)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:553)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:662)
... 26 more
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:169)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:79)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:326)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3706)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3595)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:720)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:576)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:313)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:261)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:266)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189)
... 32 more
Help Please .. Thanks
#Table(name = ...) distinguishes the (resulting SQL) table name, bro!
#Entity(name = ...) distinguishes the "entity name" especially in jpql/hql/criteria queries - defaults to class name. – #xerx593
As I could see from your database scheme, column mapping names in UserBean.java are not correct (e.g. #Column(name="Username") while it should be lowercase). Possibly, the same problem with table name.
Could be a cause
Second possible option is that You didn't indicated to Hibernate what is the result entity. To do so replace createQuery("from User") with createQuery("from UserBean", UserBean.class)

Categories

Resources