dear developers.
I'm going to ask you a question which I think hard to solve for me just because I don't know the basic why to answer,
what I mean?? Let's see. The associations in JBoss documentations did not get the comprehensive answer: Why I should use JoinTable instead of Foreign Key and I do not completely understand how mappings works,
What do I mean by this? I know what is association are ManyToMany or ManyToOne etc. and for what aims they are, but how they work's and collaborate with each other don't need an answer about bi-directional or unidirectional or joinTable or associations, I would like to have the link where I can find full info about my two questions:
1) Why I should use JoinTable instead of Foreign Key????
2) how entity work's and collaborate with each other(without explanations what is manyToMany etc. associations and bi or unidirectional associations are)???
So, I have piece of code where I stuck because misunderstanding, I'm just trying to insert data I'm MYSQL database: Name_INSTITUTION and TYPE_NAME(Type of institution):*
My entity class:
#Entity
#Table(name="INSTITUTION")
public class Institution implements Serializable{
private static final long serialVersionUID = -7636394097858726922L;
private int Id;
#Id
#GeneratedValue(strategy=IDENTITY)
#Column(name="ID")
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
private int Version;
#javax.persistence.Version
#Column(name="VERSION")
public int getVersion() {
return Version;
}
public void setVersion(int version) {
Version = version;
}
private String Name_Institution;
#Column(name="NAME_INSTITUTION")
public String getName_Institution() {
return Name_Institution;
}
public void setName_Institution(String name_Institution) {
Name_Institution = name_Institution;
}
private Type type_inInstitution;
#ManyToOne
#Cascade(org.hibernate.annotations.CascadeType.ALL)
#JoinTable(name="TYPE_INSTITUTION",
joinColumns=#JoinColumn(name="INSTITUTION_ID"),
inverseJoinColumns=#JoinColumn(name="TYPE_ID"))
public Type getType_inInstitution() {
return type_inInstitution;
}
public void setType_inInstitution(Type type_inInstitution) {
this.type_inInstitution = type_inInstitution;
}
}
My second entity class:
#Entity
#Table(name="TYPE")
public class Type implements Serializable {
private static final long serialVersionUID = -4246217431412815552L;
private String type;
public Type(){}
public Type(String type) {
this.type = type;
}
private int Type_Id;
#Id
#GeneratedValue(strategy=IDENTITY)
#Column(name="ID")
public int getType_Id() {
return Type_Id;
}
public void setType_Id(int type_Id) {
Type_Id = type_Id;
}
private String Type_Name;
#Column(name="TYPE_NAME")
public String getType_Name() {
return Type_Name;
}
public void setType_Name(String type_Name) {
Type_Name = type_Name;
}
private int Version;
#Version
#Column(name="VERSION")
public int getVersion() {
return Version;
}
public void setVersion(int version) {
Version = version;
}
private Set<Institution> set_Institution_inType = new HashSet<Institution>();
#OneToMany
#JoinTable(name="TYPE_INSTITUTION", joinColumns=#JoinColumn(name="TYPE_ID"), inverseJoinColumns=#JoinColumn(name="INSTITUTION_ID"))
public Set<Institution> getSet_Institution_inType() {
return set_Institution_inType;
}
public void setSet_Institution_inType(Set<Institution> set_Institution_inType) {
this.set_Institution_inType = set_Institution_inType;
}
public void addType(Institution institution) {
institution.setType_inInstitution(this);
getSet_Institution_inType().add(institution);
}
}
The DAO Class:
#Repository("daoInsertDataInterface")
#Transactional
public class InsertDataService implements DaoInsertDataInterface{
private org.apache.commons.logging.Log log= LogFactory.getLog(InsertDataService.class);
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
#Resource(name="sessionFactory")
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public Institution insertData(Institution institution) {
sessionFactory.getCurrentSession().saveOrUpdate(institution);
log.info(institution.getId());
return institution;
}
}
My metada config:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"><value>${jdbc.driverClassName}</value></property>
<property name="url"><value>${jdbc.connectionValues}</value></property>
<property name="username"><value>${jdbc.userName}</value></property>
<property name="password"><value>${jdbc.password}</value></property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref ="sessionFactory"/>
</bean>
<context:property-placeholder location="connection.properties"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:component-scan base-package="edu.demidov.dom, edu.demidov.dao" />
<context:annotation-config />
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref ="dataSource"/>
<property name="packagesToScan" value="edu.demidov.dom"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
And the error:
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader -
Loading XML bean definitions from class path resource
[app-context.xml] INFO :
org.springframework.context.annotation.ClassPathBeanDefinitionScanner
- JSR-330 'javax.inject.Named' annotation found and supported for component scanning INFO :
org.springframework.context.support.GenericXmlApplicationContext -
Refreshing
org.springframework.context.support.GenericXmlApplicationContext#c93274:
startup date [Thu May 09 11:38:23 EDT 2013]; root of context hierarchy
INFO :
org.springframework.beans.factory.config.PropertyPlaceholderConfigurer
- Loading properties file from class path resource [connection.properties] INFO :
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
- JSR-330 'javax.inject.Inject' annotation found and supported for autowiring INFO :
org.springframework.beans.factory.support.DefaultListableBeanFactory -
Pre-instantiating singletons in
org.springframework.beans.factory.support.DefaultListableBeanFactory#1b9c2f0:
defining beans
[dataSource,transactionManager,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,daoInsertDataInterface,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,sessionFactory,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor];
root of factory hierarchy Hibernate: insert into TYPE (TYPE_NAME,
VERSION) values (?, ?) WARN : org.hibernate.util.JDBCExceptionReporter
- SQL Error: 1048, SQLState: 23000 ERROR: org.hibernate.util.JDBCExceptionReporter - Column 'TYPE_NAME' cannot
be null Exception in thread "main"
org.hibernate.exception.ConstraintViolationException: could not
insert: [edu.demidov.dom.Type] at
org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
at
org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at
org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2327)
at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2834)
at
org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273) at
org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
at
org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
at
org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
at
org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at
org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at
org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:117)
at
org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at
org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:685)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:677)
at
org.hibernate.engine.CascadingAction$5.cascade(CascadingAction.java:252)
at org.hibernate.engine.Cascade.cascadeToOne(Cascade.java:392) at
org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:335) at
org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:204) at
org.hibernate.engine.Cascade.cascade(Cascade.java:161) at
org.hibernate.event.def.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:450)
at
org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:282)
at
org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
at
org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
at
org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at
org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at
org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:117)
at
org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at
org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:685)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:677)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:673)
at
edu.demidov.dao.InsertDataService.insertData(InsertDataService.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601) at
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy22.insertData(Unknown Source) at
edu.demidov.dao.AppTEst.main(AppTEst.java:22)
Caused by:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Column 'TYPE_NAME' cannot be null at
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411) at
com.mysql.jdbc.Util.getInstance(Util.java:386) at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1041) at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120) at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052) at
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503) at
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664) at
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2815) at
com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
at
org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:94)
at
org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57)
... 44 more SS
Thank you, guys.
Why I should use JoinTable insted of Foreign Key?
You should not. You have the choice. If you prefer using a join table, use a join table. If you prefer using a join column (foreign key in the child table), use a join column. If you have an already existing schema that you can't change, choose the option that corresponds to the existing schema.
how entity work's and collaborate with each other
I'm not sure what you mean by that. If an entity School has a OneToMany association with an entity Teacher, when you get a school from the session, and ask for its teachers, Hibernate will load them from the database for you. If you add a teacher to the collection of teachers of a school, Hibernate will populate the join column or the join table for you. The goal is simply to manipulate objects as if theyr were simple objects stored in memory, and have Hibernate load and save them for you from/to the database.
Now regarding the exception and the title of your question, the exception message says it clearly:
insert into TYPE (TYPE_NAME, VERSION) values (?, ?) WARN : org.hibernate.util.JDBCExceptionReporter - SQL Error: 1048, SQLState: 23000 ERROR: org.hibernate.util.JDBCExceptionReporter - Column 'TYPE_NAME' cannot be null
You're trying to insert an antity of type Type (what a badly chosen name!) with a null name. And the database column doesn't acept null. So you get this exception. Either change the table definition if null is a valid Type name, or fix your code to make sure you don't try to insert a null name.
Also, respect the Java naming conventions. Your code is really hard to read.
Related
Following a tutorial found on yt channel i tried to make a simple application using Hibernate. When I execute the code I get a bunch of exceptions and I can't indentify the reason why. However, results of creating a table and inserting data is visible and it works fine - this confuses me the most. Below I provide code for necessary classes, persistence.xml and stack trace. How can I solve this problem?
STACK TRACE:
cze 24, 2017 7:39:31 PM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Error executing DDL via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlString(SchemaDropperImpl.java:375)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlStrings(SchemaDropperImpl.java:359)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applyConstraintDropping(SchemaDropperImpl.java:331)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.dropFromMetadata(SchemaDropperImpl.java:230)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.performDrop(SchemaDropperImpl.java:154)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:126)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:112)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:144)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:309)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:452)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:889)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at org.hibernate.test.Main.main(Main.java:12)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'hibernate_tests.employee' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2486)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2444)
at com.mysql.jdbc.StatementImpl.executeInternal(StatementImpl.java:845)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:745)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)
... 16 more
cze 24, 2017 7:39:31 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#363042d7] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
cze 24, 2017 7:39:31 PM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#59d2400d'
cze 24, 2017 7:39:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/hibernate_tests]
persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="myDatabase" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.user" value="miki" />
<property name="javax.persistence.jdbc.password" value="***" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/hibernate_tests" />
<property name="hibernate.dialect.storage_engine" value="innodb" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL57Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create" />
</properties>
</persistence-unit>
Main.java
public class Main {
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("myDatabase");
EntityManager entityManager = entityManagerFactory.createEntityManager();
Employee employee = new Employee();
Address address = new Address();
employee.setAddress(address);
employee.setFirstName("aaa");
employee.setLastName("bbb");
employee.setSalary(10000);
address.setLocalization("ccc");
address.setStreet("ddd");
address.setPostalCode("12-456");
/* entityManager.getTransaction().begin();
entityManager.persist(address);
entityManager.persist(employee);
entityManager.getTransaction().commit();*/
entityManager.close();
entityManagerFactory.close();
}
}
Employee.java
#Entity
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "Imie")
private String firstName;
#Column(name = "Nazwisko")
private String lastName;
#Transient
private double salary;
#OneToOne
#JoinColumn
private Address address;
/*sett.&gett*/
}
Address.java
#Entity
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "Miejscowosc")
private String localization;
#Column(name = "Ulica")
private String street;
#Column(name = "Kod_Pocztowy")
private String postalCode;
/*sett.&gett.*/
First make sure that your database hibernate_tests contain the table employee, Second to be sure put the name of your table in the Entity like :
#Entity
#Table(name = "employee", catalog = "hibernate_tests", schema = "schema_name")
public class Employee {...}
If you have a default schema then you don't need to use it just use :
#Entity
#Table(name = "employee")
public class Employee {...}
If this still not work you can check using the name of your database :
#Entity
#Table(name = "employee", catalog = "hibernate_tests")
public class Employee {...}
I managed to find what caused the problem. Everytime before execution of java code I manually dropped down tables. When program is executed, hibernate first tries to drop the tables assuming that they exist in the database. Since I dropped them previously there was exception that table doesn't exist.
When I don't drop tables manually there is no exception.
I have created a project with SQL Server which the files:
UserDAO.java*
public class UserDAO
{
private static SessionFactory sessionFactory;
static
{
sessionFactory = HibernateUtility.getSessionFactory();
}
#SuppressWarnings("unchecked")
public static List<User> findAll()
{
Session session = sessionFactory.openSession();
Criteria crit = session.createCriteria(User.class);
List<User> userList = crit.list();
return userList;
}
}
UserService.java
public class UserService
{
public static void main(String[] args)
{
List<User> listUsers = UserDAO.findAll();
for(User u : listUsers)
{
System.out.println("User is = " + u.getUserName());
}
}
}
hibernate.cfg.xml
<?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>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</property>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433;database=happy</property>
<property name="hibernate.connection.username">lm</property>
<property name="hibernate.connection.password">pp</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">validate</property>
<mapping class="com.annotation.day1.entity.User"/>
</session-factory>
</hibernate-configuration>
After running the project, the exception bellow displayed:
Hibernate:
select
this_.id as id1_0_0_,
this_.password as password2_0_0_,
this_.userName as userName3_0_0_
from
User this_
Aug 07, 2016 9:29:00 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 156, SQLState: S0001
Aug 07, 2016 9:29:00 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Incorrect syntax near the keyword 'User'.
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:89)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2065)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1862)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
at org.hibernate.loader.Loader.doQuery(Loader.java:909)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2553)
at org.hibernate.loader.Loader.doList(Loader.java:2539)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
at org.hibernate.loader.Loader.list(Loader.java:2364)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:126)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1682)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:380)
at com.annotation.day1.dao.UserDAO.findAll(UserDAO.java:74)
at com.annotation.day1.service.UserService.main(UserService.java:24)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near the keyword 'User'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:197)
Any help is appreciated. Thanks in advance.
USER is a Reserve Word and needs to be escaped in query using square bracket [] while querying.
If you are using annotations, escape through single quotes. '', like below
#Table(name="`user`")
Also refer here for similar issue.
Faced pretty similar issue, when Column name value has space in between.
Note : Hibernate 5.3.7 with SQLServer 2014
#Entity
#Table(name = "TableName")
public class Customer {
#Id
#Column(name = "cid")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int customerId;
#Column(name = "Customer Name")
private String customerName;
---
---
ERROR:
Solution 1 : Template Literals
Solution 2:
-We could remove the space or add '_' in between
#Column(name = "CustomerName") or #Column(name = "Customer_Name")
Note: Name is also a reserved word in SQLServer.
I have a simple Entity written in Eclipse(Java), and I try to start my project with tome, but I get this exception.
Caused by: <openjpa-2.4.0-nonfinal-1598334-r422266:1599166 nonfatal general error> org.apache.openjpa.persistence.PersistenceException: unexpected token: TO {stmnt 1004327302 ALTER TABLE Flight ADD COLUMN to VARCHAR(20)} [code=-5581, state=42581]
at org.apache.openjpa.jdbc.meta.MappingTool.record(MappingTool.java:559)
at org.apache.openjpa.jdbc.meta.MappingTool.record(MappingTool.java:455)
at org.apache.openjpa.jdbc.kernel.JDBCBrokerFactory.synchronizeMappings(JDBCBrokerFactory.java:160)
at org.apache.openjpa.jdbc.kernel.JDBCBrokerFactory.synchronizeMappings(JDBCBrokerFactory.java:164)
at org.apache.openjpa.jdbc.kernel.JDBCBrokerFactory.newBrokerImpl(JDBCBrokerFactory.java:122)
at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:208)
at org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:155)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:226)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:59)
at org.apache.openejb.assembler.classic.ReloadableEntityManagerFactory.createEntityManager(ReloadableEntityManagerFactory.java:160)
at org.apache.openejb.persistence.JtaEntityManagerRegistry.getEntityManager(JtaEntityManagerRegistry.java:119)
at org.apache.openejb.persistence.JtaEntityManager.getEntityManager(JtaEntityManager.java:96)
at org.apache.openejb.persistence.JtaEntityManager.proxyIfNoTx(JtaEntityManager.java:326)
at org.apache.openejb.persistence.JtaEntityManager.createQuery(JtaEntityManager.java:280)
at com.airline.utils.DatabaseUtils.deleteData(DatabaseUtils.java:42)
at com.airline.utils.DatabaseUtils.addTestDataToDB(DatabaseUtils.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:192)
at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:173)
at org.apache.openejb.monitoring.StatsInterceptor.record(StatsInterceptor.java:181)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler.synchronizedBusinessMethod(EjbObjectProxyHandler.java:308)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler.businessMethod(EjbObjectProxyHandler.java:303)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler._invoke(EjbObjectProxyHandler.java:92)
at org.apache.openejb.core.ivm.BaseEjbProxyHandler.invoke(BaseEjbProxyHandler.java:308)
... 44 more
Here is my Flight Entity with which I hava this problem :
#Entity
#NamedQueries({ #NamedQuery(name = "Flight.getAll", query = "SELECT f FROM Flight f") })
public class Flight implements Serializable {
#Transient
private static final long serialVersionUID = 1L;
public Flight() {
super();
}
public Flight(FlightDestination to, Integer flightPrice, Date date) {
super();
this.flightPrice = flightPrice;
this.date = date;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Enumerated(EnumType.STRING)
private FlightDestination to;
private Integer flightPrice;
#Temporal(TemporalType.DATE)
private Date date;}
The problem is with my FlightDestination to field
FlightDestination:
public enum FlightDestination {
SOFIA, MUNICH, BERLIN, PARIS, VALENCIA, ROME, NEW_YORK, BARCELONA}
And this is my persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="airline">
<description>Container Persistence Unit</description>
<jta-data-source>airlineDatabase</jta-data-source>
<class>com.airline.models.Passenger</class>
<class>com.airline.models.Flight</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<property name="openjpa.Log" value="DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE" />
<property name="openjpa.ConnectionFactoryProperties" value="PrintParameters=true" />
</properties>
Passenger is my other Entity which work perfectly when I remove Flight Entity.
to is a Keyword in mysql. Rename the property.
For more Information see https://dev.mysql.com/doc/refman/5.7/en/keywords.html
I am trying to implement inheritance using hibernate and using simple program
Well I am declaring a class of person having four attributes-age,sex,name,id(which is auto generated)
Now I have two classes inheriting the base class
The first class is native where one attribute is there that defines pincode whereas the other class is foreign where psotcode is defined
Following is my whole code
person.java
package com;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Person {
private String Name;
private int age;
private String sex;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private String id;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
native.java
package com;
import javax.persistence.Entity;
#Entity
public class Native extends Person {
private int pincode;
public int getPincode() {
return pincode;
}
public void setPincode(int pincode) {
this.pincode = pincode;
}
}
foreign.java
package com;
import javax.persistence.Entity;
#Entity
public class Foreign extends Person {
private String postcode;
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
}
mainclass.java
package com;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class Classmain {
public static void main(String args[])
{
Person person = new Person();
person.setName("krish");
person.setSex("M");
person.setAge(23);
Native native = new Native();
native.setPincode(201545);
native.setAge(23);
native.setName("victor");
native.setSex("M");
Foreign foreign = new Foreign();
foreign.setPostcode("sfadfas0");
foreign.setName("michelle");
foreign.setAge(31);
foreign.setSex("F");
SessionFactory sessionfactory = new AnnotationConfiguration()
.configure().buildSessionFactory();
Session session = sessionfactory.openSession();
session.beginTransaction();
session.save(person);
session.save(foreign);
session.save(native);
session.getTransaction().commit();
session.close();
}
}
Following is my hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/Inherit1</property>
<property name="connection.username">root</property>
<property name="connection.password">vvvvvvvv</property>
<property name="hbm2ddl.auto">update</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<mapping class="com.Person" />
<mapping class="com.Native" />
<mapping class="com.Foreign" />
</session-factory>
</hibernate-configuration>
However I am getting the following error
INFO: HHH000232: Schema update complete
Hibernate: insert into Person (Name, age, sex, DTYPE) values (?, ?, ?, 'Person')
Jun 7, 2013 7:12:30 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1146, SQLState: 42S02
Jun 7, 2013 7:12:30 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Table 'Inherit1.Person' doesn't exist
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:136)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2975)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3487)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:377)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:214)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:194)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:178)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:321)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:286)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:192)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:206)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:191)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:764)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:756)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:752)
at com.Classmain.main(Classmain.java:33)
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'Inherit1.Person' doesn't exist
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3283)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1332)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1604)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1519)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1504)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:133)
... 22 more
What could be the reason?
OK, I found your error, but you should have seen in your logs the previous errors:
ERROR: HHH000389: Unsuccessful: create table Person (DTYPE varchar(31) not null, id varchar(255) not null auto_increment, Name varchar(255), age integer not null, sex varchar(255), pincode integer, postcode varchar(255), primary key (id))
07-jun-2013 17:17:35 org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: Incorrect column specifier for column 'id'
If you look at the definition of id, you are trying to declare an auto-increment field with a String variable in Person class. Change it with int and it will work perfectly.
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
A unique table named Person is created and data are inserted correctly.
Try to add #Table(name="table_name") annotations to inherited entities.
I have been trying to use Spring and Hibernate together. At the moment I am trying to make Hibernate create the tables automatically. According to the documentation and examples I have found online, this should be achievable by setting the hibernate.hbm2ddl.auto to create, create-drop or update. For some reason this is not working. Below is where I am declaring my beans (in \WEB-INF\dispatcher-servlet.xml):
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/MY_SHOP" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>com.crimsonwing.dto.UserDTO</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
This is how I am declaring my DTO:
#Entity
#Table(name = "USER", uniqueConstraints = #UniqueConstraint(columnNames = { "EMAIL", "UID" }))
public class UserDTO implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
// Validation Annotation
#Size(min = 8, max = 30, message = "User name must be between 8 and 30 characters long.")
// Database Anotation
#Column(name = "NAME", insertable = true, updatable = true, nullable = false)
private String name;
// Validation Annotation
#NumberFormat(style = Style.NUMBER)
#Min(1)
#Max(99)
// Database Anotation
#Column(name = "AGE", insertable = true, updatable = true, nullable = false)
private int age;
// Validation Annotation
#UniqueEmail
#Email(message = "Email is incorrect format.")
#NotEmpty(message = "Email cannot be left empty")
// Database Anotation
#Column(name = "EMAIL", insertable = true, updatable = true, nullable = false)
private String email;
// Database Anotation
#Id
#Column(name = "UID", insertable = false, updatable = false, nullable = false)
#GeneratedValue()
private String userUID;
public UserDTO(String name, int age, String email)
{
super();
this.name = name;
this.age = age;
this.email = email;
}
public UserDTO()
{
/* WILL BE USED BY HIBERNATE */
}
...
And this is how I am trying to access the database:
#Repository
public class UserDAOImpl implements IUserDAO
{
#Resource
private HibernateTemplate hibernateTemplate;
#Override
public bbolean userExists(String userEmail)
{
UserDTO user = new UserDTO();
user.setEmail(userEmail);
DetachedCriteria detachedCriteria = DetachedCriteria.forClass(user.getClass());
return (this.hibernateTemplate.findByCriteria(detachedCriteria).size() > ) ? true : false;
}
...
Anyone can point me out in the right direction? Is there a missing setting or something I did wrong? I am using MySQL version 5.1.58-1ubuntu1 on an Ubuntu x64 platform with spring 3.1 and hibernate 3.6.10.
Thanks.
EDIT: Stacktrace added for completeness:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'MY_SHOP.USER' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2624)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2127)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2293)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1953)
at org.hibernate.loader.Loader.doQuery(Loader.java:802)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
at org.hibernate.loader.Loader.doList(Loader.java:2542)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276)
at org.hibernate.loader.Loader.list(Loader.java:2271)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:119)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1716)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347)
at org.springframework.orm.hibernate3.HibernateTemplate$36.doInHibernate(HibernateTemplate.java:1056)
at org.springframework.orm.hibernate3.HibernateTemplate$36.doInHibernate(HibernateTemplate.java:1)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.findByCriteria(HibernateTemplate.java:1046)
at org.springframework.orm.hibernate3.HibernateTemplate.findByCriteria(HibernateTemplate.java:1039)
at com.crimsonwing.dao.impl.UserDAOImpl.userExists(UserDAOImpl.java:36)
at com.crimsonwing.service.impl.UserServiceImpl.userExists(UserServiceImpl.java:28)
at com.crimsonwing.facades.impl.UserFacadeImpl.userExists(UserFacadeImpl.java:34)
at com.crimsonwing.validator.uniqueemail.impl.UniqueEmailValidator.isValid(UniqueEmailValidator.java:26)
at com.crimsonwing.validator.uniqueemail.impl.UniqueEmailValidator.isValid(UniqueEmailValidator.java:1)
at org.hibernate.validator.engine.ConstraintTree.validateSingleConstraint(ConstraintTree.java:278)
at org.hibernate.validator.engine.ConstraintTree.validateConstraints(ConstraintTree.java:153)
at org.hibernate.validator.engine.ConstraintTree.validateConstraints(ConstraintTree.java:117)
at org.hibernate.validator.metadata.MetaConstraint.validateConstraint(MetaConstraint.java:84)
at org.hibernate.validator.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:452)
at org.hibernate.validator.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:397)
at org.hibernate.validator.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:361)
at org.hibernate.validator.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:313)
at org.hibernate.validator.engine.ValidatorImpl.validate(ValidatorImpl.java:139)
at org.springframework.validation.beanvalidation.SpringValidatorAdapter.validate(SpringValidatorAdapter.java:101)
at org.springframework.validation.DataBinder.validate(DataBinder.java:722)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.validateIfApplicable(ModelAttributeMethodProcessor.java:154)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:107)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:74)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:155)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Edit:
As per parasietje's suggestion, this is the resulting HQL:
Hibernate: select this_.UID as UID2_0_, this_.AGE as AGE2_0_, this_.EMAIL as EMAIL2_0_, this_.NAME as NAME2_0_ from USER this_
I do not get any other HQL. If I remember correctly, when the table is being created you also get to see the resulting HQL statement, which is not what is happening in this case.
Does the schema MY_SHOP actually exists, my understanding is Hibernate is not gonna create a schema , it will just create class under an existing schema.
So try creating the schema if not and also try adding the schema in the table annotation.
#Entity
#Table(name = "USER", , schema="MY_SHOP", uniqueConstraints = #UniqueConstraint(columnNames = { "EMAIL", "UID" }))
public class UserDTO implements Serializable
{