Hibernate SQLException - java

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.

Related

Caused by: org.hibernate.MappingException: Unable to load class declared as <mapping class="xxxxx"/> in the configuration:

In my spring web application I am getting this error on launching my spring application
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 'transactionManager' defined in ServletContext resource [/WEB-INF/spring/data.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring/data.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: Unable to load class declared as <mapping class="reshetyk.alexey.diary.domain.DiaryUser"/> in the configuration:
Also I have this as a second error
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring/data.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: Unable to load class declared as <mapping class="reshetyk.alexey.diary.domain.DiaryUser"/> in the configuration:
The class DiaryUser is defined in the package and have the following properties assuming the getters and setters are well defined
this is the complete code of my entity class for DiaryUser class.java
#Entity
#Table(name = "USERS")
public class DiaryUser implements Serializable {
#Id
#Column(name = "ID_USER")
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(name = "LOGIN", unique = true, nullable = false)
private String login;
#Column(name = "PASSWORD", nullable = false)
private String password;
public DiaryUser() {
}
public DiaryUser(Integer id) {
this.id = id;
}
public DiaryUser(String login) {
this.login = login;
}
public DiaryUser(Integer id, String login, String password) {
this.id = id;
this.login = login;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
I have equally defined this in my hibernate.cfg.xml file
<hibernate-configuration>
<session-factory>
<mapping class="reshetyk.alexey.diary.domain.DiaryUser" />
<mapping class="reshetyk.alexey.diary.domain.DiaryCategory" />
<mapping class="reshetyk.alexey.diary.domain.DiaryRecord" />
</session-factory>
</hibernate-configuration>
this is my data.xml file that contains my database definition configuration for hibernate mappings
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<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"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
I am kind of confused as I dont know why I am getting this error?
Instead of using LocalSessionFactoryBean,try using the AnnotationSessionFactoryBean instead and specify the mapping classes as shown below(check the link:AnnotationSessionFactoryBean)
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>test.package.Foo</value>
<value>test.package.Bar</value>
</list>
</property>
</bean>
or
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="test.package"/>
</bean>
instead of defining the mappings under hibernate.cfg.xml.
Your sessionFactory details in data.xml file can be modified as below:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--<property name="configLocation" value="classpath:hibernate.cfg.xml"/>-->
<property name="annotatedClasses">
<list>
<value>reshetyk.alexey.diary.domain.DiaryUser</value>
<value>reshetyk.alexey.diary.domain.DiaryCategory</value>
<value>reshetyk.alexey.diary.domain.DiaryRecord</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
Please make sure that mapping resource is correctly defined.

Why Hibernate in showing two different Queries in the console for single Query?`

I am new to this Hibernate framework and using Hibernate 3 just to start using this framework.
I have a small module that is executing a update query.
public void saveProduct(Product prod) {
String hql = "UPDATE Product set description = :description, price = :price,ctr=ctr+1 WHERE id = :id";
Query query = this.sessionFactory.getCurrentSession().createQuery(hql);
query.setParameter("description", prod.getDescription());
query.setParameter("price", prod.getPrice());
query.setParameter("id", prod.getId());
logger.info(prod.toString());
int result = query.executeUpdate();
logger.info("Rows affected: " + result);
}
These are logs for this particular module and i have issue in this part hibernate is showing two different update queries one without column ctr and other one with column ctr or is it a normal behaviour:
May 23, 2016 5:55:37 PM com.mogae.dashboard.db.dao.ProductDaoImp saveProduct
INFO: Description: test311;Price: 1.7279999999999998
Hibernate:
update
products
set
description=?,
price=?
where
id=?
Hibernate:
update
products
set
description=?,
price=?,
ctr=ctr+1
where
id=?
May 23, 2016 5:55:37 PM com.mogae.dashboard.db.dao.ProductDaoImp saveProduct
INFO: Rows affected: 1
This is my xml configuration for DB connectivity:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<!-- the parent application context definition for the springapp application -->
<aop:config>
<aop:advisor pointcut="execution(* *..ProductManager.*(..))" advice-ref="txAdvice"/>
</aop:config>
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<bean id="productDao" class="com.mogae.dashboard.db.dao.ProductDaoImp">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>product.hbm.xml</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>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.user}"/>
<property name="password" value="${db.password}"/>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:db.properties</value>
</list>
</property>
</bean>
</beans>
and this is my hibernate mapping file :
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.mogae.dashboard.actions.domain.Product" table="products" lazy="false">
<id name="id" column="id" type="int">
<generator class="native">
<param name="sequence">products_id_seq</param>
</generator>
</id>
<property name="description" column="description" type="string" />
<property name="price" column="price" type="double" />
</class>
</hibernate-mapping>
and this is my entity (Product) class:
package com.mogae.dashboard.actions.domain;
import java.io.Serializable;
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("Description: " + description + ";");
buffer.append("Price: " + price);
return buffer.toString();
}
private String description;
private Double price;
private int id;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Please help i have been searching for this issue on the google and various hibernate forums but haven't found one.

Spring Data JPA query doesn't work, column does not exists

I use spring data jpa in my web-app, i have entity user
#Entity
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String password;
private String email;
private Boolean enabled;
private String name;
private String lastname;
private String userRole;
public User() {
}
public User(String password, String email, Boolean enabled, String name, String lastname, String userRole) {
this.password = password;
this.email = email;
this.enabled = enabled;
this.name = name;
this.lastname = lastname;
this.userRole = userRole;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "users_id_seq")
#SequenceGenerator(name="users_id_seq", sequenceName="users_id_seq", allocationSize = 1)
#Column(name = "id", nullable = false)
public Long getId() {
return id;
}
//Other columns
}
And i have UserRepository interface which extends CrudRepository.
When i call method findAll in my Controller, I get this error
01-May-2016 22:45:58.674 WARN [http-nio-8080-exec-3] org.hibernate.engine.jdbc.spi.SqlExceptionHelper.logExceptions SQL Error: 0, SQLState: 42703
01-May-2016 22:45:58.675 ERROR [http-nio-8080-exec-3] org.hibernate.engine.jdbc.spi.SqlExceptionHelper.logExceptions Error: column user0_.id does not exist
Position: 8
My spring-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<jpa:repositories base-package="com.birthright.repository"/>
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.birthright.entity"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL9Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<tx:annotation-driven/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/AutoService"/>
<property name="username" value="postgres"/>
<property name="password" value="root"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf"/>
</bean>
</beans>
My table in postgresql
CREATE TABLE public."user"
(
id integer NOT NULL DEFAULT nextval('users_id_seq'::regclass),
password character varying,
email character varying,
enabled boolean,
name character varying,
lastname character varying,
user_role character varying,
CONSTRAINT users_pkey PRIMARY KEY (id)
)
User is a reserved keyword in PostgreSQL. With a default naming strategy you, probably, had User table name.
Don't know why #Table(name = "user", schema = "public") works. Maybe PostgreSQL doesn't consider public.user as a keyword opposite User.
Please use plural names for tables. And using a system or subsystem prefix for a table name (xxx_users) is a good idea too.
A naming strategy can be used for such approach. Refer this as an example: Hibernate5NamingStrategy
An example of prefixes:
StrategyOptions

Spring 4 hibernate 4 #Transactional(read-only="true") does not work

I use hibernate 4, spring 4, and I want to use #Transaction annotation, but it doesn't work.
The user object still saved on sqlServer.
Any idea what I'm doing wrong?
[applicationContext.xml]
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan base-package="SpringDAO"/>
<context:component-scan base-package="SpringTest"/>
<context:component-scan base-package="service"/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation">
<value>hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.microsoft.sqlserver.jdbc.SQLServerDriver</value>
</property>
<property name="url">
<value>jdbc:sqlserver://127.0.0.1:1433;databaseName=test</value>
</property>
<property name="username">
<value>XXX</value>
</property>
<property name="password">
<value>XXX</value>
</property>
</bean>
[hibernate.cfg.xml]
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="SpringDAO.User" />
</session-factory>
</hibernate-configuration>
package SpringDAO;
#Repository("UserDAO3")
public class UserDAO3 {
SessionFactory sessionFactory;
#Autowired
public void setSessionFactory(SessionFactory value){
this.sessionFactory = value;
}
public SessionFactory getSessionFactory(){
return this.sessionFactory;
}
#Transactional(readOnly = true)
public boolean insert(Object user){
Session sess = this.sessionFactory.getCurrentSession();
sess.save(user);
return true;
}
}
package service;
#Service("UserService")
public class UserService {
public boolean addAction(User user){
boolean result = true;
UserDAO3 dao = (UserDAO3)SpringUtil.getBean("UserDAO3");
List<User> users = dao.searchAllUser();
for(User selectedUser : users){
if(selectedUser.getName().equals(user.getName())){
result = false;
break;
}
}
result = dao.insert(user);
return result;
}
}
From the docs,
This just
serves as a hint for the actual transaction subsystem; it will not
necessarily cause failure of write access attempts. A transaction
manager which cannot interpret the read-only hint will not throw an
exception when asked for a read-only transaction.
Whether the isolation level of the transaction can change depends on the implementation. Depending on the driver different things might occur, no guarantees, it does not enforce the failure.
POJO:
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Integer id;
Modification:
#Id
#Column(name = "id")
private Integer id;
It works after eliminating #GeneratedValue(strategy = GenerationType.AUTO)
have a look at #Transactional read-only flag pitfalls on ibm.com, the explanation there is really great. Your question is answered there.

Hibernate Search not indexing

I write Spring web-app using Hibernate Search 4.5.1. When I try search it returns emty list. I think that problem in indexing. Dir for indexes was created, but after entity saving files in dir are not changing.
This is my spring config file
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<context:component-scan base-package="project"/>
<context:annotation-config/>
<jpa:repositories base-package="project" transaction-manager-ref="hibernateTransactionManager"
entity-manager-factory-ref="entityManagerFactory"/>
<bean id="entityManagerFactory" name="managerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="packagesToScan" value="project"/>
<property name="dataSource" ref="postgresDataSource"/>
<property name="validationMode" value="NONE"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL81Dialect</prop>
</props>
</property>
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
</property>
</bean>
<bean id="postgresDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/LabourExchange"/>
<property name="username" value="postgres"/>
<property name="password" value="123456"/>
</bean>
<bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="postgresDataSource"/>
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="postgresDataSource"/>
<property name="packagesToScan" value="project"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.postgres.dialect}</prop>
<prop key="hibernate.max_fetch_depth">2</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">8</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
<prop key="hibernate.search.default.directory_provider">filesystem</prop>
<prop key="hibernate.search.default.indexBase">/var/lucene/indexes</prop>
</props>
</property>
</bean>
<!--security config-->
<security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/pages/**" access="isAuthenticated()"/>
<security:form-login
login-page="/auth/login.jsf"
default-target-url="/pages/home.jsf"
authentication-failure-url="/auth/login.jsf?status=error"/>
<security:logout logout-success-url="/hello.jsf"/>
</security:http>
<security:authentication-manager>
<security:authentication-provider user-service-ref="UserDetailsService">
</security:authentication-provider>
</security:authentication-manager>
</beans>
My entity file
#Entity
#Table(name = "resumes")
#Indexed
public class Resume {
#Id #Column(name = "id") #GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "title")
#Field(index= Index.YES, analyze= Analyze.YES, store= Store.NO)
#NotBlank #Size(min = 10, max = 100)
private String title;
#Column(name = "text")
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
#NotBlank #Size(min = 50, max = 10000)
private String text;
#Column(name = "salary")
#NotNull
private double salary;
#ManyToOne(optional = false)
#JoinColumn(name = "creator_id")
private User creator;
public User getCreator() {
return creator;
}
public void setCreator(User creator) {
this.creator = creator;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
I solved the problem by moving
<prop key="hibernate.search.default.directory_provider">filesystem</prop>
<prop key="hibernate.search.default.indexBase">/var/lucene/indexes</prop>
to jpaProperties tag

Categories