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
{
Related
I've some error to solve, here is the error:
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:165)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at model.Teacher_$$_jvstd69_0.toString(Teacher_$$_jvstd69_0.java)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getFormattedValue(HtmlBasicRenderer.java:517)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getFormattedValue(HtmlBasicRenderer.java:540)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:357)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:164)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1903)
at org.primefaces.component.column.Column.renderChildren(Column.java:344)
at org.primefaces.component.datatable.DataTableRenderer.encodeCell(DataTableRenderer.java:1019)
at org.primefaces.component.datatable.DataTableRenderer.encodeRow(DataTableRenderer.java:967)
at org.primefaces.component.datatable.DataTableRenderer.encodeRows(DataTableRenderer.java:878)
at org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:825)
at org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:788)
at org.primefaces.component.datatable.DataTableRenderer.encodeRegularTable(DataTableRenderer.java:281)
at org.primefaces.component.datatable.DataTableRenderer.encodeMarkup(DataTableRenderer.java:243)
at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:85)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1903)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1899)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1899)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:451)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
it's happen after relation 2 table that i generate from Hibernate tool
for table Student
#Entity
#Table(name = "student", schema = "public")
public class Student implements java.io.Serializable {
private static final long serialVersionUID = 3484556118289412550L;
private int stuId;
private Teacher teacher;
private String stuName;
private Integer stuAge;
public Student() {
}
public Student(int stuId) {
this.stuId = stuId;
}
public Student(int stuId, Teacher teacher, String stuName, Integer stuAge) {
this.stuId = stuId;
this.teacher = teacher;
this.stuName = stuName;
this.stuAge = stuAge;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "stu_id", unique = true, nullable = false)
public int getStuId() {
return this.stuId;
}
public void setStuId(int stuId) {
this.stuId = stuId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "stu_teachid")
public Teacher getTeacher() {
return this.teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
#Column(name = "stu_name", length = 40)
public String getStuName() {
return this.stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
#Column(name = "stu_age")
public Integer getStuAge() {
return this.stuAge;
}
public void setStuAge(Integer stuAge) {
this.stuAge = stuAge;
}
}
Teacher
#Entity
#Table(name = "teacher", schema = "public")
public class Teacher implements java.io.Serializable {
private static final long serialVersionUID = 3863374948774698083L;
private int teachId;
private String teachName;
private Set<Student> students = new HashSet<Student>(0);
public Teacher() {
}
public Teacher(int teachId) {
this.teachId = teachId;
}
public Teacher(int teachId, String teachName, Set<Student> students) {
this.teachId = teachId;
this.teachName = teachName;
this.students = students;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "teach_id", unique = true, nullable = false)
public int getTeachId() {
return this.teachId;
}
public void setTeachId(int teachId) {
this.teachId = teachId;
}
#Column(name = "teach_name", length = 40)
public String getTeachName() {
return this.teachName;
}
public void setTeachName(String teachName) {
this.teachName = teachName;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "teacher")
public Set<Student> getStudents() {
return this.students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
}
My applicationContext.xml
<context:component-scan base-package="controller"></context:component-scan>
<context:component-scan base-package="dao"></context:component-scan>
<context:component-scan base-package="model"></context:component-scan>
<context:component-scan base-package="service"></context:component-scan>
<!-- Enable Spring Annotation Configuration -->
<context:annotation-config />
<context:spring-configured />
<!-- Create Data Source bean -->
<bean id="DataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/university" />
<property name="username" value="postgres" />
<property name="password" value="1234" />
</bean>
<!-- Define SessionFactory bean -->
<bean id="SessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="DataSource" />
<property name="annotatedClasses">
<list>
<value>model.Student</value>
<value>model.Teacher</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.use_sql_comments">true</prop>
<prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
</props>
</property>
</bean>
<!-- Detect #Transactional Annotation -->
<tx:annotation-driven transaction-manager="txManager" />
<!-- Transaction Manager is defined -->
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
How to solve this problem ?
There are three ways to avoid the Lazy Initialization Exception:
Set the lazy property to false in the mapping file.I don’t recommend this approach because it will increment the database load and therefore, it will produce a decrease in performance.
Keep the session open. Don't close the session before you have processed the data. If the session is open during the request you could get the associated graph but you need to be sure that the action takes within the same transaction.
Eagerly fetch the associations. In the HQL query use the keyword "fetch" to retrieve the association. From my point of view this is the best solution to avoid the lazy initialization problem. In HQL, you just need to add the fetch keyword in the from clause to eagerly fetch an association.
Change the mapping of set of students from LAZY to EAGER
I want insert some data in one of my table, and I get next exception:
`java.sql.SQLException: ORA-02289: sequence does not exist`
Let's me to show my code. I have next classes:
#Entity
#Table(name="role")
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO, generator="role_seq_gen")
#SequenceGenerator(name="role_seq_gen", sequenceName="ROLE_SEQ")
private Long roleId;
#Column(name="role", unique=true)
private String role;
#ManyToMany(mappedBy = "roles")
private List<Tipster> tipsters;
// + getters and setters
}
#Entity
#Table(name="tipster")
public class Tipster implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO, generator="tipster_id_seq")
#SequenceGenerator(name="tipster_id_seq", sequenceName="tipster_id_seq")
#Column(name="tipsterId")
private Long tipsterId;
#NotEmpty
#Column(name="username", unique=true)
private String username;
#NotEmpty
#Column(name="email", unique=true)
private String email;
#NotEmpty
#Column(name="password", unique=true)
private String password;
#Column(name="active")
private int active;
#ManyToMany
#JoinTable
private List<Role> roles;
//+ getters and setters
}
This is a part of my application context code:
<context:annotation-config />
<task:annotation-driven />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<jpa:repositories base-package="com.gab.gsn.repository" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521/XE" />
<property name="username" value="gabrieltifui" />
<property name="password" value="123321" />
</bean>
<bean
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="emf">
<property name="packagesToScan" value="com.gab.gsn.entity" />
<property name="dataSource" ref="dataSource" />
<property name="jpaProperties">
<props>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.use_sql_comments">true</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
</props>
</property>
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider" />
</property>
</bean>
Now, I try to insert a row in my Role table with this method:
#PostConstruct
public void initDb(){
Role role = new Role();
role.setRole("User");
roleRepository.save(role);
}
When I my app on my Apache Server I get next exception:
Caused by: 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.id.SequenceGenerator.generateHolder(SequenceGenerator.java:122)
at org.hibernate.id.SequenceGenerator.generate(SequenceGenerator.java:115)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:84)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181)
... 57 more
Caused by: java.sql.SQLException: ORA-02289: sequence does not exist
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:113)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:754)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:219)
at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:813)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1051)
at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:854)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1156)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3415)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3460)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:80)
... 68 more
It seems like I don't create the ROLE_SEQ sequence, but I know that Hibernate should create it automatically. Who can explain me why I get this exception?
It could be a problem related with your permissions, first execute the next statement select * from all_sequences where sequence_name = 'YOUR_SEQUENCE' ; If the sequence exists you only have to grant the permission to the user that you are using in your application. use grant select on YOUR_SEQUENCE to YOUR_USER; to fix your problem.
I'm using Hibernate 3.6.0 with Mysql 5.5.15. I have an entity with a #GeneratedValue ID field. When I try to persist the entity it throws exception: No value specified for parameter 5. The fifth parameter is the ID field. How can I fix this problem?
The entity class:
#Entity
#Table(name = "T_DEVICE_HISTORY")
public class DeviceHistory {
#Id
#Column(name = "ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
#Column(name = "DEVICE_ID")
private String deviceId;
#Column(name = "GUID", length = 36)
private String guid;
#Column(name = "UPDATE_DATE")
private Date updated;
#Column(name = "STATUS", nullable = false)
#Enumerated(EnumType.STRING)
private DeviceStatus status;
// getters,setters ...
#PrePersist
public void setInitialState() {
setUpdated(new Date());
}
}
The code persisting the entity:
DeviceHistory deviceHistory = new DeviceHistory();
deviceHistory.setGuid(guid);
deviceHistory.setDeviceId(deviceId);
deviceHistory.setStatus(DeviceStatus.INACTIVE);
entityManager.persist(deviceHistory);
The stack trace:
06:12:58,123 ERROR [JDBCExceptionReporter] No value specified for parameter 5
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not insert: [com.evolok.idm.core.domain.DeviceHistory]
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:630)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:219)
at com.evolok.idm.core.domain.RestrictedUnregisterPerDurationDeviceManagementPolicyDelegate.unregisterDevice(RestrictedUnregisterPerDurationDeviceManagementPolicyDelegate.java:78)
at com.evolok.idm.core.domain.DeviceManagementPolicyEntity.unregisterDevice(DeviceManagementPolicyEntity.java:86)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.invoke(CGLIBLazyInitializer.java:157)
at com.evolok.idm.core.domain.DeviceManagementPolicyEntity$$EnhancerByCGLIB$$2ff84b00.unregisterDevice(<generated>)
at com.evolok.idm.services.core.UserProfileComponent.unregisterDevice(UserProfileComponent.java:479)
at com.evolok.idm.notification.proxies.UserProfileServiceNotificationProxy.unregisterDevice(UserProfileServiceNotificationProxy.java:186)
at com.evolok.idm.services.web.endpoints.rest.UserProfileResource.unregisterDevice(UserProfileResource.java:567)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.sca4j.pojo.component.InvokerInterceptor.invoke(InvokerInterceptor.java:192)
at org.sca4j.pojo.component.InvokerInterceptor.invoke(InvokerInterceptor.java:165)
at org.sca4j.fabric.component.scope.RequestScopeInterceptor.invoke(RequestScopeInterceptor.java:40)
at org.sca4j.rs.runtime.RsSourceWireAttacher$RsMethodInterceptor.intercept(RsSourceWireAttacher.java:163)
at com.evolok.idm.services.web.endpoints.rest.UserProfileResource$$EnhancerByCGLIB$$99ca8d93.unregisterDevice(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:156)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:67)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:163)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:111)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:71)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:111)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:63)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:654)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:612)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:603)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:309)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:425)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:590)
at org.sca4j.rs.runtime.rs.RsWebApplication.service(RsWebApplication.java:148)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.sca4j.runtime.webapp.ServletHostImpl.service(ServletHostImpl.java:138)
at org.sca4j.runtime.webapp.SCA4JServlet.service(SCA4JServlet.java:85)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:534)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1351)
at com.evolok.idm.web.TransactionFilter.doFilter(TransactionFilter.java:47)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1322)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:473)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:516)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:929)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:403)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:184)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:864)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:247)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:151)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:114)
at org.eclipse.jetty.server.Server.handle(Server.java:352)
at org.eclipse.jetty.server.HttpConnection.handleRequest(HttpConnection.java:596)
at org.eclipse.jetty.server.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:1051)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:590)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:212)
at org.eclipse.jetty.server.HttpConnection.handle(HttpConnection.java:426)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:508)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.access$000(SelectChannelEndPoint.java:34)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:40)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:451)
at java.lang.Thread.run(Thread.java:695)
Caused by: org.hibernate.exception.SQLGrammarException: could not insert: [com.evolok.idm.core.domain.DeviceHistory]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:40)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2158)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2638)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107)
at org.hibernate.ejb.event.EJB3PersistEventListener.saveWithGeneratedId(EJB3PersistEventListener.java:49)
at org.hibernate.event.def.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:131)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:87)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:38)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:618)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:592)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:596)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:213)
... 68 more
Caused by: java.sql.SQLException: No value specified for parameter 5
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:2176)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1993)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1937)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1922)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:73)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:33)
... 83 more
The generated statement:
insert into T_DEVICE_HISTORY (DEVICE_ID, GUID, STATUS, UPDATE_DATE, ID) values (?, ?, ?, ?, ?)
EDIT: Table structure:
CREATE TABLE `T_DEVICE_HISTORY` (
`ID` bigint(20) NOT NULL AUTO_INCREMENT,
`DEVICE_ID` varchar(255) DEFAULT NULL,
`GUID` varchar(36) DEFAULT NULL,
`STATUS` varchar(255) NOT NULL,
`UPDATE_DATE` datetime DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Edit 2 - persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="evolok-idm" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.evolok.idm.core.domain.DeviceHistory</class>
<!-- other classes... -->
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/evolok-idm-web"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.autocommit" value="false"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<property name="hibernate.connection.isolation" value="4"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="false"/>
</properties>
</persistence-unit>
</persistence>
From your code I can see that the updateDate is missing... is tat nullable field ?
AUTO is default strategy so you can remove. and try the following equivalent definition..
#Id
#Column(name = "ID")
#GeneratedValue
private long id;
Change your entity as follows, you need to add default constructor.
#Entity
#Table(name = "T_DEVICE_HISTORY")
public class DeviceHistory implements java.io.Serializable {
public DeviceHistory(){
super();
id = null ;
}
#Id
#Column(name = "ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
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).
This is what I do:
#Repository
#Transactional(propagation = Propagation.SUPPORTS)
public class ProfileDAOHibernateImpl implements ProfileDAO {
#Autowired
private SessionFactory sessionFactory;
private Session currentSession() {
return sessionFactory.getCurrentSession();
}
#Override
public Profile getProfile(String name) {
return (Profile) currentSession().createCriteria(Profile.class)
.add(Restrictions.eq("name", name)).uniqueResult();
}
...
}
Profile entity:
#Entity
#Table(name = "profiles")
public class Profile {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int Id;
#Column(name = "name", unique = true)
private String name;
#ManyToOne(optional = false, fetch = FetchType.EAGER)
#JoinColumn(name="partner_id", nullable = false)
private Partner partner;
...
}
Partner entity:
#Entity
#Table(name = "partners")
public class Partner {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#OneToMany(fetch = FetchType.LAZY, cascade={CascadeType.ALL}, mappedBy = "partner")
#OrderBy(value = "dateCreated desc")
private Set<Profile> profiles = new HashSet<Profile>();
#ManyToMany(fetch = FetchType.EAGER)
#OrderBy(value = "name asc")
#JoinTable(name = "partner_service",
joinColumns = { #JoinColumn(name = "partner_id") },
inverseJoinColumns = { #JoinColumn(name = "service_id") })
private Set<Service> services = new HashSet<Service>();
...
}
Service entity:
#Entity
#Table(name = "services")
public class Service {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "partner_service",
joinColumns = { #JoinColumn(name = "service_id") },
inverseJoinColumns = { #JoinColumn(name = "partner_id") })
private Set<Partner> partners = new HashSet<Partner>();
...
}
Here are my hibernate/datasource configurations:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="poolPreparedStatements" value="true" />
<property name="maxActive" value="20" />
<property name="initialSize" value="2" />
<property name="maxIdle" value="2" />
</bean>
<bean id="profileDAO" class="com.eniro.partnerapi.dao.impl.ProfileDAOHibernateImpl" />
<!-- Hibernate session factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.eniro.partnerapi.model" />
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">verify</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.jdbc.batch_size">30</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="dataSource" ref="dataSource" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
A Partner has a OneToMany to Profiles (and vice versa)
A Partner has a ManyToMany to Services
What I'm trying to achieve is that when I load a profile, I want its owning Partner to be loaded, and the Partner's Services at the same time. And yes, I want them to be eagerly loaded since they are rarely of great sets, and they are almost always needed all at the same time in this system.
An example scenario is:
Partner A has 3 profiles
Partner A has 5 services
The partners first Profile is fetched (profileX), at the same time the Partner and the Partner's Services are loaded.
Here is where my problem occurs (in the getProfile call in my DAO): Sometimes only the first service (based on id) is loaded from the database, and sometimes all 5 services are loaded.
What can be the cause of this? Anyone has any experience or anything for me to go on?
EDIT - adding additional info
We are using:
Hibernate 3.6.7.Final
MySQL connector 5.1.16
Spring 3.0.5.RELEASE
Quartz 1.6.1
MySQL 5.1.x
Tomcat 6.33
In a distributed environment where the application is run on two separate servers.
Alright, we managed to finally find the problem. It turns out it's not necessarily Hibernates fault.
We have a Quartz scheduler which was handling jobs on the side. The problem occurred once the scheduler (org.springframework.scheduling.quartz.SchedulerFactoryBean) started up. This is fine. However, we have two instances of the same application running in production, so the scheduler was using the database to synchronize between the two applications to keep a job from running at the same time from two instances.
However, this Quartz scheduler was communicating with the database in his own way (didn't find any code for it), which lead to clashes between Hibernates and Quartzs connections and thus giving the strange loading behaviour from the DAOs.
What exactly happened I can't say in detail, but we removed the DB dependency of Quartz and just used namespace to handle all jobs. After that, the problem was gone.
Warning to people using Hibernate/JDBC and Quartz scheduling between distributed applications: Be careful with how the components handle connections to the database.