How to implement mapping in hibernate using annotation? - java

I am trying to implement OneToMany and ManyToOne mapping in hibernate but I got error in dispatcher-servlet.xml while adding mapping class.
It return error:
> cvc-complex-type.2.4.a: Invalid content was found starting with
> element 'mapping'. "http:// www.springframework.org/schema/beans"]}'
> is expected.
dispatcher-servlet.xml file:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.tushar.hibernate.model.User</value>
<value>com.tushar.hibernate.model.Sender</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.c3p0.max_statements">${connectionpool.maximum.statements}</prop>
</props>
</property>
<mapping class="com.tushar.hibernate.model.User" /> <!-- This is the line which return an error -->
<mapping class="com.tushar.hibernate.model.Sender" />
</bean>
Model Class User:
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue
#Column(name = "u_id")
private int userId;
#Column(name = "name")
private String name;
#Column(name = "mobile")
private String mobile;
#Column(name = "email")
private String email;
private Set<Sender> userSenderId = new HashSet<Sender>(0);
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#OneToMany(cascade = CascadeType.ALL)
#JoinTable(name = "user_sender", joinColumns = { #JoinColumn(name = "u_id") }, inverseJoinColumns = { #JoinColumn(name = "s_id") })
public Set<Sender> getUserSenderId() {
return userSenderId;
}
public void setUserSenderId(Set<Sender> userSenderId) {
this.userSenderId = userSenderId;
}
}
Model Class Sender:
#Entity
#Table(name = "sender")
public class Sender {
#Id
#GeneratedValue
#Column(name = "s_id")
private int sId;
#Column(name = "sender_id")
private String senderId;
#ManyToOne(cascade=CascadeType.ALL)
private User user;
public int getsId() {
return sId;
}
public void setsId(int sId) {
this.sId = sId;
}
public String getSenderId() {
return senderId;
}
public void setSenderId(String senderId) {
this.senderId = senderId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
This are the two class that I want to map each other
#OneToMany for User to Sender
And #ManyToOne for Sender to User
But after running project it return some errors like:
Aug 05, 2017 10:20:43 PM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/spring-hibernate] has started
Aug 05, 2017 10:20:43 PM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesJdbc
SEVERE: The web application [/spring-hibernate] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
Aug 05, 2017 10:20:43 PM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
SEVERE: The web application [/spring-hibernate] appears to have started a thread named [MySQL Statement Cancellation Timer] but has failed to stop it. This is very likely to create a memory leak.
Aug 05, 2017 10:20:44 PM org.apache.catalina.startup.TldConfig execute
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Aug 05, 2017 10:20:44 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Aug 05, 2017 10:20:44 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Aug 05, 2017 10:20:45 PM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: user, for columns: [org.hibernate.mapping.Column(userSenderId)]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:684)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1282)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1195)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1085)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5349)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5641)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.StandardContext.reload(StandardContext.java:4119)
at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:425)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1341)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1542)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1552)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1552)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1520)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: user, for columns: [org.hibernate.mapping.Column(userSenderId)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:336)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:310)
at org.hibernate.mapping.Property.isValid(Property.java:241)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:496)
at org.hibernate.mapping.RootClass.validate(RootClass.java:270)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1358)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1849)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:343)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:431)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:416)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
... 30 more
Aug 05, 2017 10:20:45 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet [dispatcher] in web application [/spring-hibernate] threw load() exception
org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: user, for columns: [org.hibernate.mapping.Column(userSenderId)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:336)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:310)
at org.hibernate.mapping.Property.isValid(Property.java:241)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:496)
at org.hibernate.mapping.RootClass.validate(RootClass.java:270)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1358)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1849)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:343)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:431)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:416)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:684)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1282)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1195)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1085)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5349)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5641)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.StandardContext.reload(StandardContext.java:4119)
at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:425)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1341)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1542)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1552)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1552)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1520)
at java.lang.Thread.run(Thread.java:745)
Aug 05, 2017 10:20:45 PM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/spring-hibernate] is completed
Above error returns when I tried to do mapping in model without writing mapping property in dispatcher-servlet.xml file.

You have already declared the model classes in the xml:
<list>
<value>com.tushar.hibernate.model.User</value>
<value>com.tushar.hibernate.model.Sender</value>
</list>
You don't need to add the mapping entries, and also this configuration is used by spring and mapping tag in not allowed here. If you are using hibernate.cfg.xml file then you can declare your mappings there(Only if you are not using annotations).
You just need to add #Entity annotation on top of your model classes.

<mapping class="com.tushar.hibernate.model.User" />
this tag is not present in <bean> tag..
If you have hibernate configuration file then use following tag to configure that cfg file in sessionfactory bean of spring cfg file-
<property name="configLocation" value="hibernate_cfg_file_name"/>
if you remove <mapping> tag then may your program work....
try it...

Related

Incorrect syntax near the keyword 'table' and could not extract ResultSet

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.

JavaFX desktop app - Using HSQLDB (embedded) and Hibernate

Is there good tutorial on using HSQLDB, Hibernate and JavaFX. I am using eclipse as my IDE. My Project model has variables defined like this:
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "PROJECTID")
private long projectId;
#Column(name = "PROJECTNAME")
private final StringProperty projectName;
#Column(name = "PROJECTJIBP")
private final StringProperty projectJIBP;
Is this valid way of using Hibernate with JavaFX ?
persistance.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<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" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="test" transaction-type="RESOURCE_LOCAL">
<class> handwrittencode.eiar.model.Project</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:mem:test" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="show_sql" value="true"/>
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
</properties>
</persistence-unit>
</persistence>
I am getting this error message:
Jun 28, 2014 7:53:27 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
Jun 28, 2014 7:53:27 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
Jun 28, 2014 7:53:27 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
Jun 28, 2014 7:53:27 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
name: test
...]
Jun 28, 2014 7:53:27 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
Jun 28, 2014 7:53:27 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jun 28, 2014 7:53:27 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jun 28, 2014 7:53:28 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Jun 28, 2014 7:53:28 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Jun 28, 2014 7:53:28 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [org.hsqldb.jdbcDriver] at URL [jdbc:hsqldb:mem:test]
Jun 28, 2014 7:53:28 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=sa}
Jun 28, 2014 7:53:28 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Jun 28, 2014 7:53:28 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jun 28, 2014 7:53:28 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.HSQLDialect
Jun 28, 2014 7:53:28 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000422: Disabling contextual LOB creation as connection was null
Initial SessionFactory creation failed.javax.persistence.PersistenceException: [PersistenceUnit: test] Unable to build Hibernate SessionFactory
Exception in Application constructor
java.lang.reflect.InvocationTargetException
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:483)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:367)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:305)
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:483)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Unable to construct Application instance: class handwrittencode.eiar.MainApp
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:884)
at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:56)
at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:158)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
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:408)
at com.sun.javafx.application.LauncherImpl$7.run(LauncherImpl.java:791)
at com.sun.javafx.application.PlatformImpl$7.run(PlatformImpl.java:335)
at com.sun.javafx.application.PlatformImpl$6$1.run(PlatformImpl.java:301)
at com.sun.javafx.application.PlatformImpl$6$1.run(PlatformImpl.java:298)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$6.run(PlatformImpl.java:298)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$300(WinApplication.java:39)
at com.sun.glass.ui.win.WinApplication$4$1.run(WinApplication.java:112)
... 1 more
Caused by: java.lang.ExceptionInInitializerError
at handwrittencode.eiar.util.EntityManagerUtil.<clinit>(EntityManagerUtil.java:16)
at handwrittencode.eiar.MainApp.<init>(MainApp.java:32)
... 15 more
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: test] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1225)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.access$600(EntityManagerFactoryBuilderImpl.java:119)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:853)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:397)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:75)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:54)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at handwrittencode.eiar.util.EntityManagerUtil.<clinit>(EntityManagerUtil.java:12)
... 16 more
Caused by: org.hibernate.MappingException: Could not determine type for: javafx.beans.property.StringProperty, at table: PROJECT, for columns: [org.hibernate.mapping.Column(projectAddress)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:336)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:310)
at org.hibernate.mapping.Property.isValid(Property.java:241)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:496)
at org.hibernate.mapping.RootClass.validate(RootClass.java:270)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1358)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1849)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
... 24 more
Exception running application handwrittencode.eiar.MainApp
EDIT
package handwrittencode.eiar.model;
import java.time.LocalDate;
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.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import handwrittencode.eiar.util.LocalDateAdapter;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
#Entity
#Table(name = "PROJECT")
public class Project {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "PROJECTID")
private long projectId;
private final StringProperty projectName;
private final StringProperty projectJIBP;
private final StringProperty projectState;
private final StringProperty projectAddress;
private final StringProperty projectManager;
private final ObjectProperty<LocalDate> projectCreated;
private final ObjectProperty<LocalDate> projectStart;
private final ObjectProperty<LocalDate> projectEnd;
public Project()
{
this(null,null,null,null,null);
}
public Project(String projectName, String projectJIBP, String projectState, String projectAddress, String projectManager)
{
this.projectName = new SimpleStringProperty(projectName);
this.projectJIBP = new SimpleStringProperty(projectJIBP);
this.projectState = new SimpleStringProperty(projectState);
this.projectAddress = new SimpleStringProperty(projectAddress);
this.projectManager = new SimpleStringProperty(projectManager);
this.projectCreated = new SimpleObjectProperty<LocalDate>(LocalDate.of(1999, 2, 21));
this.projectStart = new SimpleObjectProperty<LocalDate>(LocalDate.of(1999, 2, 21));
this.projectEnd = new SimpleObjectProperty<LocalDate>(LocalDate.of(1999, 2, 21));
}
#Column(name = "PROJECTNAME")
public String getProjectName() {
return projectName.get();
}
public void setProjectName(String projectName) {
this.projectName.set(projectName);
}
public StringProperty projectNameProperty() {
return this.projectName;
}
/**/
#Column(name = "PROJECTJIBP")
public String getProjectJIBP(){
return projectJIBP.get();
}
public void setProjectJIBP(String projectJIBP) {
this.projectJIBP.set(projectJIBP);
}
public StringProperty projectJIBPProperty() {
return this.projectJIBP;
}
/**/
#Column(name = "PROJECTSTATE")
public String getProjectState(){
return projectState.get();
}
public void setProjectState(String projectState) {
this.projectState.set(projectState);
}
public StringProperty projectStateProperty() {
return this.projectState;
}
/**/
#Column(name = "PROJECTADDRESS")
public String getProjectAddress(){
return projectAddress.get();
}
public void setProjectAddress(String projectAddress) {
this.projectAddress.set(projectAddress);
}
public StringProperty projectAddressProperty() {
return this.projectAddress;
}
/**/
#Column(name = "PROJECTMANAGER")
public String getProjectManager(){
return projectManager.get();
}
public void setProjectManager(String projectManager) {
this.projectManager.set(projectManager);
}
public StringProperty projectManagerProperty() {
return this.projectManager;
}
/**/
#XmlJavaTypeAdapter(LocalDateAdapter.class)
public LocalDate getProjectCreated() {
return projectCreated.get();
}
public void setProjectCreated(LocalDate projectCreated) {
this.projectCreated.set(projectCreated);
}
public ObjectProperty<LocalDate> projectCreatedProperty() {
return projectCreated;
}
/**/
#XmlJavaTypeAdapter(LocalDateAdapter.class)
public LocalDate getProjectStart() {
return projectStart.get();
}
public void setProjectStart(LocalDate projectStart) {
this.projectStart.set(projectStart);
}
public ObjectProperty<LocalDate> projectStartProperty() {
return projectStart;
}
/**/
#XmlJavaTypeAdapter(LocalDateAdapter.class)
public LocalDate getProjectEnd() {
return projectEnd.get();
}
public void setProjectEnd(LocalDate projectEnd) {
this.projectEnd.set(projectEnd);
}
public ObjectProperty<LocalDate> projectEndProperty() {
return projectEnd;
}
}
Is this valid way of using Hibernate with JavaFX ?
No: use property access instead of field access:
private final StringProperty projectName;
#Column(name = "PROJECTNAME")
public final String getProjectName() {
return projectName.get();
}
public final void setProjectName(String projectName) {
this.projectName.set(projectName);
}
public StringProperty projectNameProperty() {
return projectName;
}
etc...
This enables Hibernate to determine the types from the return types of the get methods, rather than from the types of the actual fields; so it can persist Strings instead of StringPropertys, and so on.
See Steven Van Impe's blog and my blog

org.hibernate.MappingException: Unknown entity: library.model.Person

I've been struggling with this all day but haven't yet found a solution.
I have a simple entity mapping to a database table:
#Entity
#Table(name = "PERSON")
public class Person implements Serializable {
// Attributes.
#Id
#Column(name = "ID", unique = true, nullable = false)
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
#Column(name = "NAME", nullable = false, length=50)
private String name;
#Column(name = "ADDRESS", nullable = false, length=100)
private String address;
#Column(name = "TELEPHONE", nullable = false, length=10)
private String telephone;
#Column(name = "EMAIL", nullable = false, length=50)
private String email;
#OneToMany(cascade=CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name="PERSON_ID")
private List<Book> books;
// Constructors.
public Person() {
this.id = 0;
this.name = ("");
this.address = ("");
this.telephone = ("");
this.email = ("");
this.books = null;
}
This entity is governed by a Spring controller with the following method:
#RequestMapping(value = "/register", method = RequestMethod.POST)
public String post(#ModelAttribute("person") Person person,
BindingResult bindingResult,
SessionStatus sessionStatus,
Model model /* ,
HttpSession session */) throws DAOException {
logger.info(PersonController.class.getName() + ".post() method called.");
personValidator.validate(person, bindingResult);
if (bindingResult.hasErrors()) {
return "register";
}
else {
// Write Person to database.
personService.insert(person);
// Set view.
sessionStatus.setComplete();
return "options";
}
}
The service class is:
#Service("personService")
#Transactional
public class PersonService {
#Autowired
PersonDAO personDAO;
public void insert(Person person) throws DAOException {
personDAO.insert(person);
}
And the DAO is as follows:
#Repository("PersonDAO")
public class PersonDAOImpl implements PersonDAO {
#Autowired
private SessionFactory sessionFactory;
static final Logger logger = Logger.getLogger(PersonDAOImpl.class.getName());
#Override
public void insert(Person person) throws DAOException {
logger.info(PersonDAOImpl.class.getName() + ".insert() method called.");
Session session = sessionFactory.openSession();
Transaction transaction = session.getTransaction();
try {
transaction.begin();
session.save(person);
transaction.commit();
}
catch(RuntimeException e) {
transaction.rollback();
throw new DAOException(e);
}
finally {
session.close();
}
}
And of course the part of my Spring servlet binding everything together:
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.DerbyDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.current_session_context_class ">thread</prop>
<!-- What to do with the database schema. -->
<prop key="hbm2ddl.auto">validate</prop>
<!-- validate: validate the schema, makes no changes to the database.
update: update the schema.
create: creates the schema, destroying previous data.
create-drop: drop the schema at the end of the session. -->
</props>
</property>
</bean>
So why am I getting the message:
org.hibernate.MappingException: Unknown entity: library.model.Person
If I try things like:
<property name="packagesToScan" value="library.model" />
<property name="annotatedClasses">
<list>
<value>library.model.Person</value>
</list>
</property>
At the moment I am getting:
Jun 15, 2014 10:50:58 PM org.apache.catalina.core.ApplicationContext
log INFO: Initializing Spring root WebApplicationContext Jun 15, 2014
10:51:02 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener
instance of class
org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'personController': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: library.services.PersonService
library.controller.PersonController.personService; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'personService': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: library.dao.PersonDAOImpl
library.services.PersonService.personDAO; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'PersonDAOImpl': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: org.hibernate.SessionFactory
library.dao.PersonDAOImpl.sessionFactory; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'sessionFactory' defined in ServletContext
resource [/WEB-INF/library-servlet.xml]: Invocation of init method
failed; nested exception is java.lang.NoClassDefFoundError:
javax/persistence/NamedStoredProcedureQuery at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at
org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at
org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at
org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at
org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4681)
at
org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5184)
at
org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5179)
at java.util.concurrent.FutureTask.run(FutureTask.java:266) 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:744)
Try replacing:
<property name="annotatedClasses">
<list>
<value>library.model.Person</value>
</list>
</property>
With:
<property name="packagesToScan">
<list>
<value>library.model</value>
</list>
</property>
In your sessionFactory properties.
If you get an error saying the property "packagesToScan" could not be found then you should add the spring-orm library to your project. If you're using maven then you can add:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>YOUR SPRING VERSION HERE</version>
</dependency>

Error creating bean with name 'sessionFactory' defined in ServletContext resource

So I'm trying to implement Spring Framework and Hibernate to my web project.
I got hibernate to work at one point (register user and add it to database), but after some time nothing is working.
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Sat Jul 20 22:45:19 EET 2013]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/root-context.xml]
INFO : org.springframework.beans.factory.config.PropertyPlaceholderConfigurer - Loading properties file from ServletContext resource [/WEB-INF/jdbc.properties]
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#7b4dab69: defining beans [messageSource,propertyConfigurer,dataSource,sessionFactory,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager]; root of factory hierarchy
WARN : org.hibernate.internal.util.xml.DTDEntityResolver - HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#7b4dab69: defining beans [messageSource,propertyConfigurer,dataSource,sessionFactory,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager]; root of factory hierarchy
ERROR: org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring/root-context.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1482)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:608)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4797)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5291)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at org.hibernate.mapping.Constraint$ColumnComparator.compare(Constraint.java:134)
at org.hibernate.mapping.Constraint$ColumnComparator.compare(Constraint.java:130)
at java.util.TimSort.countRunAndMakeAscending(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at org.hibernate.mapping.Constraint.generateName(Constraint.java:82)
at org.hibernate.cfg.Configuration.buildUniqueKeyFromColumnNames(Configuration.java:1572)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1395)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1756)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1840)
at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:247)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:373)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:358)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1541)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1479)
... 22 more
and Caused by: java.lang.NullPointerException
root-context.xml
<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/jdbc.properties" />
</bean>
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.databaseurl}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.something.*" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/imdb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="hibernate.connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Echo all executed SQL to stdout for debugging -->
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="springers.Model.Bean.UserAccount" />
<mapping class="springers.Model.Bean.Movie" />
<mapping class="springers.Model.Bean.TvShow" />
<mapping class="springers.Model.Bean.Connector_User_TvShow" />
</session-factory>
data object example:
#Entity
#Table(name = "USERS")
public class UserAccount {
private int user_pk;
private String username;
private String password;
private String e_mail;
private String country;
#Id
#GeneratedValue
#Column(name = "USER_PK")
public int getUser_pk() { return user_pk; }
#Column(name = "USERNAME", nullable = false, length = 12, unique = true)
public String getUsername() { return username; }
#Column(name = "PASSWORD", nullable = false, length = 12)
public String getPassword() { return password; }
#Column(name = "E_MAIL", nullable = false, length = 50, unique = true)
public String getE_mail() { return e_mail; }
#Column(name = "COUNTRY", nullable = false, length = 25)
public String getCountry() { return country; }
public void setUser_pk (int user_pk) { this.user_pk = user_pk; }
public void setUsername(String username) { this.username = username; }
public void setPassword(String password) { this.password = password; }
public void setCountry (String country) { this.country = country; }
public void setE_mail (String e_mail) { this.e_mail = e_mail; }
user tvshow connector bean:
#Entity
#Table(name = "USER_TVSHOW_CONNECTOR",
uniqueConstraints = #UniqueConstraint(columnNames = {"user_fk", "tvShow_fk"}))
public class Connector_User_TvShow {
private int utc_pk;
private boolean toWatch = false;
private boolean favorite = false;
private boolean reminder = false;
private UserAccount user_fk;
private TvShow tvShow_fk;
#Id
#GeneratedValue
#Column(name = "UTC_PK")
public int getUtc_pk() { return utc_pk; }
#Column(name = "TO_WATCH", nullable = false)
public boolean isToWatch() { return toWatch; }
#Column(name = "FAVOURITE", nullable = false)
public boolean isFavorite() { return favorite; }
#Column(name = "REMINDER", nullable = false)
public boolean isReminder() { return reminder; }
#OneToOne(cascade = CascadeType.ALL)
public UserAccount getUser_fk() { return user_fk; }
#OneToOne(cascade = CascadeType.ALL)
public TvShow getTvShow_fk() { return tvShow_fk; }
public void setUtc_pk (int utc_pk) { this.utc_pk = utc_pk; }
public void setToWatch (boolean toWatch) { this.toWatch = toWatch; }
public void setFavorite (boolean favorite) { this.favorite = favorite; }
public void setReminder (boolean reminder) { this.reminder = reminder; }
public void setUser_fk (UserAccount user_fk) { this.user_fk = user_fk; }
public void setTvShow_fk (TvShow tvShow_fk) { this.tvShow_fk = tvShow_fk; }
Add #JoinColumn(name="user_fk") and #JoinColumn(name="tvShow_fk") to your getUser_fk and getTvShow_fk.
I just had the same NullPointerException.
You will get this NPE if there is a typo in the column name of a #UniqueConstraint annotation
The cause of your Exception was the same one:
java.lang.NullPointerException
at org.hibernate.mapping.Constraint$ColumnComparator.compare(Constraint.java:134)
at org.hibernate.mapping.Constraint$ColumnComparator.compare(Constraint.java:130)
at java.util.TimSort.countRunAndMakeAscending(TimSort.java:324)
at java.util.TimSort.sort(TimSort.java:189)
at java.util.TimSort.sort(TimSort.java:173)
at java.util.Arrays.sort(Arrays.java:659)
at org.hibernate.mapping.Constraint.generateName(Constraint.java:82)
at org.hibernate.cfg.Configuration.buildUniqueKeyFromColumnNames(Configuration.java:1572)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1395)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1756)
at ...
There was a bug report for this issue. The ticket has been fixed. If you update to hibernate 4.3 or later, there will be a better exception message.
PS: but in your case it's just because you didn't specify any column name on the join annotation (see the answer of #alex).

Column cannot be null could not insert

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.

Categories