Hibernate 4 lazy loading doesn't work - java

I am working on a web application using spring 3 and hibernate 4.
I am having trouble lazy-loading a set of granted permissions of a group to which a user belongs.
When a user object is retrieved from the database, its Group object doesn't have any permissions even though user.getGroup().getPermissions() is invoked explicitly.
I noticed that in debug mode, if I mouse-over the User object and then navigate to the Group object inside the User object, and then navigate to its permissions, I can see its type is shown as PersistentSet, and expanding it will load permissions properly. But in non-debug mode, permissions are never lazy-loaded. What am I missing here? Thanks in advance.
Here are the relationships among the entities:
Users have an one-to-many relationship with groups, and groups have a many-to-many relationship with permissions.
Here's the definition of the UserDaoImpl class
#Repository
#Transactional
public class UserDaoImpl implements UserDao {
#Autowired
private SessionFactory sessionFactory;
private Session getSession() {
return sessionFactory.getCurrentSession();
}
#Override
public User get(String username) {
Session session = getSession();
User user = (User) session.createCriteria(User.class).add(Restrictions.eq("username", username)).uniqueResult();
Group g = user.getGroup();
// calling g.getGrantedPermissions() doesn't load any permission
Set<Permission> permissions = g.getGrantedPermissions();
return user;
}
}
Here's the definition of the Permission class
#Entity
public class Permission {
#Id
#GeneratedValue
private Long id;
#Column
private String name;
#Column
private String description;
public Permission()
{
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Here's the definition of the Group class
#Entity
#Table(name="\"Group\"")
public class Group {
public static final String ROLE_VALID_USER = "ROLE_VALID_USER";
#Id
#GeneratedValue
private Long id;
#Column
private String description;
#Column
private String role;
#ManyToMany
#JoinTable(name = "granted_permission",
joinColumns = {#JoinColumn(name = "GROUP_ID", nullable = false, updatable = false) },
inverseJoinColumns = { #JoinColumn(name = "PERMISSION_ID", nullable = false, updatable = false) })
private Set<Permission> grantedPermissions;
public Group()
{
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Set<Permission> getGrantedPermissions() {
return grantedPermissions;
}
public void setGrantedPermissions(Set<Permission> grantedPermissions) {
this.grantedPermissions = grantedPermissions;
}
}
Here's the definition of the User class
#Entity
public class User {
#Id
#Column(name="USERNAME")
private String username;
#Column(name="PASSWORD")
private String password;
#Transient
private final boolean enabled = true;
#Column
private String name;
#Column(name="EMAIL")
private String email;
#Column(name="PHONE")
private String phone;
#ManyToOne
private Group group;
#ManyToOne
#JoinColumn(name="ORIGINAL_BRANCH_ID")
private Branch originalBranch;
#ManyToOne
#JoinColumn(name="ID_OF_RESPONSIBLE_BRANCH")
private Branch responsibleBranch;
public User()
{
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return group.getRole();
}
public boolean isEnabled() {
return enabled;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public Branch getOriginalBranch() {
return originalBranch;
}
public void setOriginalBranch(Branch originalBranch) {
this.originalBranch = originalBranch;
}
public Branch getResponsibleBranch() {
return responsibleBranch;
}
public void setResponsibleBranch(Branch responsibleBranch) {
this.responsibleBranch = responsibleBranch;
}
}
Here's the persistence configuration:
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<tx:annotation-driven />
<context:annotation-config />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<context:component-scan base-package="net.acme.prs" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="mysqlDataSource" />
<property name="packagesToScan" value="net.acme.prs" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQL5InnoDBDialect
</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<bean id="mysqlDataSource" 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/prs" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
</beans>

I cannot understand what is your problem because you haven't mentioned any error you encountered. If you simply found there was no SQL to fetch the grantedPermissions, it is what lazy-fetching is about: It is only fetched when it is accessed, and if it is not accessed, it won't be fetched.
The reason you see it being fetched during debug, is because when you are inspecting the grantedPermissions in debugger, it is accessing that property, which will trigger the lazy fetching. However, for non-debug mode, if you have no code accessing that property, no fetching is precisely what it supposed to do.
If what you are asking is, you have code in non-debug mode that will access grantedPermissions but lazy fetching failed when it is accessed, then it is due to the access is out of transaction: Hibernate needs to have an active Session to have lazy fetching happening. If the lazy-fetching happens out of the transaction, it will fail because there is no opened Session. You should revisit your design by considering
Scope of transaction: instead of having transaction around the DAO, you should put transaction boundary in a proper unit-of-work level: maybe your app service, or controller
Do proper join fetch/eager fetch, so that no lazy-fetching happens outside the transaction
EclipseLink, which is another JPA implementation, allows lazy-fetch after session is ended.

Follow http://docs.oracle.com/javaee/5/api/javax/persistence/FetchType.html
Example : If you want to auto load "grantedPermissions" in "Group", you have to change your annotation to #ManyToMany(fetch = FetchType.EAGER)

Related

Address value shows null

I have two classes Student and Address which implements IStudent ans IAddress interfaces respectively. Student class has a relationship with Address class. That is why i have declared a reference member of it.
public class Student implements IStudent {
private String code;
private String name;
#Autowired
private IAddress address;
#Override
public String getCode() {
return this.code;
}
#Override
public String getName() {
return this.name;
}
public void setCode(String code) {
this.code = code;
}
public void setName(String name) {
this.name = name;
}
public IAddress getAddress() {
return this.address;
}
public void setAddress(Address address) {
this.address = address;
}
}
and I have Address class
public class Address implements IAddress{
private String city;
private String pinCode;
private String houseNo;
private String roadName;
#Override
public String getCity() {
return this.city;
}
#Override
public String getPinCode() {
return this.pinCode;
}
#Override
public String getHouseNo() {
return this.houseNo;
}
#Override
public String getRoadName() {
return this.roadName;
}
public void setCity(String city) {
this.city = city;
}
public void setPinCode(String pinCode) {
this.pinCode = pinCode;
}
public void setHouseNo(String houseNo) {
this.houseNo = houseNo;
}
public void setRoadName(String roadName) {
this.roadName = roadName;
}
}
In my applicationContext.xml file i have written the following bean definitions
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<bean id="studentbean" class="main.Student">
<property name="code" value="S001"></property>
<property name="name" value="Subhabrata Mondal"></property>
</bean>
<bean id="addressbean" class="main.Address">
<property name="houseNo" value="119/2"></property>
<property name="roadName" value="South Avenue"></property>
<property name="city" value="Delhi"></property>
<property name="pinCode" value="110005"></property>
</bean>
</beans>
When i have checked Student object after initialization of bean, name and code has assigned with setter method. But the address is not assigned. Thus it shows null value for address. I have marked address with #Autowired annotation. Can you please help?
ApplicationContext factory = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student) factory.getBean("studentbean");
System.out.println(student.getAddress());
you need to explicitly wire to Address not IAddress since the CI only knows Address, if you want to wired
#Autowired
private Address address;
or you need to define a bean with type IAddress but make sure you do not have more than implementation or spring will get confused, if you have more than one implementation use can qualifiers to clear the ambiguity
This whole example is kind of strange but you can get rid of the #Autowired annotation and use following bean configuration instead;
<bean id="studentbean" class="main.Student">
<property name="code" value="S001"></property>
<property name="name" value="Subhabrata Mondal"></property>
<property name="address" >
<ref local="addressbean"/>
</property>
</bean>

Error producing xml from response body in spring

Hello guys so i have a bit issue. I wrote a simple rest application using spring framework. I was able to post and get the response in json but now i want to have the option of displaying both json and xml format. Now i'm getting error 406 when trying to display the format in xml. I already included the converter in dispatcher but having trouble displaying in xml format. Please i'm i missing soemthing. Also included the dependency in maven:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
Below is my dispatcher-servlet.xml which loads the controller. :
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc-annotation="http://www.springframework.org/schema/mvc"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="edu.sjsu.cmpe275.lab2.controller" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" >
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
<bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
</list>
</property>
</bean>
<mvc:annotation-driven/>
</beans>
below is my method in the controller upon entering the url when trying to produce the output in xml:
#RequestMapping(value="player/{id}", method=RequestMethod.GET, params="format=xml", produces=MediaType.APPLICATION_XML_VALUE)
#ResponseBody
public ResponseEntity<?> inXML(#PathVariable("id")long id) {
Person person = personImpl.findById(id);
if(person!=null){
return new ResponseEntity<Person>(person, HttpStatus.OK);
}
else
return new ResponseEntity<String>("Id doesn't exist", HttpStatus.NOT_FOUND);
}
Person POJO:
public class Person {
#Id
#Column(name="person_Id")
#GeneratedValue
private long id;
#Column(unique = true)
private String email;
private String first_name, last_name, description;
//#Embedded
private Address address;
#ManyToOne(cascade = CascadeType.ALL)
private Organization organization;
#OneToMany(cascade = CascadeType.ALL)
#JoinTable(name="Friends")
Collection<Person> persons = new ArrayList<Person>();
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
public Person() {}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

inner join between two tables Hibernate

I need to do Inner join between two tables, but without success, I have to find all the patients related to a particular User,I tried to query without success.
I am using mysql and hibernate 3.6.4.
This is my code
Patient.java
#Entity
public class Patient {
#Id
private int id;
private String paitentFirstName;
private String paitentLastName;
private Date dateOfbirth;
private String sex;
#ManyToMany(cascade = {CascadeType.ALL})
#JoinTable(name="User_Patient",
joinColumns={#JoinColumn(name="id")},
inverseJoinColumns={#JoinColumn(name="userName")})
private Set<User> users = new HashSet<User>();
public Set<User> getUsers() {
return users;
}
public void setMeetings(Set<User> users) {
this.users = users;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPaitentFirstName() {
return paitentFirstName;
}
public void setPaitentFirstName(String paitentFirstName) {
this.paitentFirstName = paitentFirstName;
}
public String getPaitentLastName() {
return paitentLastName;
}
public void setPaitentLastName(String paitentLastName) {
this.paitentLastName = paitentLastName;
}
public Date getDateOfbirth() {
return dateOfbirth;
}
public void setDateOfbirth(Date dateOfbirth) {
this.dateOfbirth = dateOfbirth;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
#Override
public String toString() {
return "Patient [id=" + id + ", paitentFirstName=" + paitentFirstName
+ ", paitentLastName=" + paitentLastName + ", dateOfbirth="
+ dateOfbirth + ", sex=" + sex + "]";
}
}
User.java
#Entity
public class User {
#Id
private String UserName;
#ManyToMany(mappedBy="users")
private Set<Patient> patients = new HashSet<Patient>();
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public Set<Patient> getEmployees() {
return patients;
}
public void setEmployees(Set<Patient> patients) {
this.patients = patients;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
private String password;
}
Hibernate configuration file
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test2</property>
<property name="connection.username">root</property>
<property name="connection.password">1234</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<!-- Names the annotated entity class -->
<mapping class="com.objects.Patient"/>
<mapping class="com.objects.User"/>
</session-factory>
</hibernate-configuration>
There is no need for explicit join.
With Hibernate version that do have HHH-5209 fixed, query can be written as follows:
SELECT p
FROM Patient p
WHERE :particularUser MEMBER OF p.users
With older versions IN ELEMENTS can be used instead:
SELECT p
FROM Patient p
WHERE :particularUser IN ELEMENTS (p.users)

Spring Data JPA auditing feature is not working in my project

I am reading the book 'ProSpring3' and I am trying to use the Spring Data JPA feature in my project.
I am posting the relevant files here.
src/main/java/foo/bar/domain/ContactAudit.java :
package foo.bar.domain;
import org.hibernate.annotations.Type;
import org.joda.time.DateTime;
import org.springframework.data.domain.Auditable;
import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import static javax.persistence.GenerationType.IDENTITY;
#Table(name = "CONTACT_AUDIT")
#Entity
public class ContactAudit implements Auditable<String, Long>{
private Long id;
private String firstName;
private String lastName;
private Date birthDate;
private int version;
private Set<Hobby> hobbies = new HashSet<Hobby>();
private Set<ContactTelDetail> contactTelDetails = new HashSet<ContactTelDetail>();
//Audit fields
private String createdBy;
private DateTime createdDate;
private String lastModifiedBy;
private DateTime lastModifiedDate;
//constructors
public ContactAudit() {
}
public ContactAudit(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public ContactAudit(String firstName, String lastName, Date birthDate, Set<Hobby> hobbies, Set<ContactTelDetail> contactTelDetails) {
this.firstName = firstName;
this.lastName = lastName;
this.birthDate = birthDate;
this.hobbies = hobbies;
this.contactTelDetails = contactTelDetails;
}
#Column(name = "ID")
#Id
#GeneratedValue(strategy = IDENTITY)
public Long getId() {
return id;
}
#Override
#Transient
public boolean isNew() {
if (id == null)
return true;
else
return false;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "FIRST_NAME")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "LAST_NAME")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "BIRTH_DATE")
#Temporal(TemporalType.DATE)
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
#Column(name = "VERSION")
#Version
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
#ManyToMany
#JoinTable(name = "contact_hobby_detail",
joinColumns = #JoinColumn(name = "CONTACT_ID"),
inverseJoinColumns = #JoinColumn(name = "HOBBY_ID"))
public Set<Hobby> getHobbies() {
return hobbies;
}
public void setHobbies(Set<Hobby> hobbies) {
this.hobbies = hobbies;
}
#OneToMany(mappedBy = "contact", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<ContactTelDetail> getContactTelDetails() {
return contactTelDetails;
}
public void setContactTelDetails(Set<ContactTelDetail> contactTelDetails) {
this.contactTelDetails = contactTelDetails;
}
#Column(name = "CREATED_BY")
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#Column(name = "CREATED_DATE")
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
public DateTime getCreatedDate() {
return createdDate;
}
public void setCreatedDate(DateTime createdDate) {
this.createdDate = createdDate;
}
#Column(name = "LAST_MODIFIED_BY")
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
#Column(name = "LAST_MODIFIED_DATE")
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
public DateTime getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(DateTime lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
//other methods
public String toString()
{
return "Contact - Id: " + id + ", First name: " + firstName + ", Last name: " + lastName + ", Birthday: " + birthDate
+ ", Create by: " + createdBy + ", Create date: " + createdDate + ", Modified by: " + lastModifiedBy + ", Modifed date: " + lastModifiedDate;
}
}
src/main/java/foo/bar/repository/ContactAuditRepository.java :
package foo.bar.repository;
import foo.bar.domain.ContactAudit;
import org.springframework.data.repository.CrudRepository;
public interface ContactAuditRepository extends CrudRepository<ContactAudit, Long>{
}
src/main/java/foo/bar/service/ContactAuditService.java :
package foo.bar.service;
import foo.bar.domain.ContactAudit;
import java.util.List;
public interface ContactAuditService {
public List<ContactAudit> findAll();
public ContactAudit findById(Long id);
public ContactAudit save(ContactAudit contact);
}
src/main/java/foo/bar/service/springjpa/ContactAuditServiceImpl.java
package foo.bar.service.springjpa;
import com.google.common.collect.Lists;
import foo.bar.domain.ContactAudit;
import foo.bar.repository.ContactAuditRepository;
import foo.bar.service.ContactAuditService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Service("contactAuditService")
#Repository
#Transactional
public class ContactAuditServiceImpl implements ContactAuditService{
#Autowired
private ContactAuditRepository contactAuditRepository;
#Override
#Transactional(readOnly = true)
public List<ContactAudit> findAll() {
return Lists.newArrayList(contactAuditRepository.findAll());
}
#Override
#Transactional(readOnly = true)
public ContactAudit findById(Long id) {
return contactAuditRepository.findOne(id);
}
#Override
public ContactAudit save(ContactAudit contact) {
return contactAuditRepository.save(contact);
}
}
src/main/java/foo/bar/springjpa/auditor/AuditorAwareBean.java :
package foo.bar.springjpa.auditor;
import org.springframework.data.domain.AuditorAware;
public class AuditorAwareBean implements AuditorAware<String>{
#Override
public String getCurrentAuditor() {
return "prospring3";
}
}
src/main/resources/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:context="http://www.springframework.org/schema/context" 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/context http://www.springframework.org/schema/context/spring-context.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">
<context:annotation-config />
<context:component-scan base-package="foo.bar.service.springjpa"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName">
<value>${jdbc.driverClassName}</value>
</property>
<property name="url">
<value>${jdbc.url}</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.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="packagesToScan" value="foo.bar.domain"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</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>
<context:property-placeholder location="jdbc.properties"/>
<jpa:repositories base-package="foo.bar.repository"
entity-manager-factory-ref="emf"
transaction-manager-ref="transactionManager"/>
<jpa:auditing auditor-aware-ref="auditorAwareBean"/>
<bean id="auditorAwareBean" class="foo.bar.springjpa.auditor.AuditorAwareBean"/>
</beans>
src/main/java/META-INF/persistence.xml :
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="NewPersistenceUnit"/>
</persistence>
src/main/java/META-INF/orm.xml :
<?xml version="1.0" encoding="UTF-8" ?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
version="2.0">
<description>JPA</description>
<persistence-unit-metadata>
<persistence-unit-defaults>
<entity-listeners>
<entity-listener class="org.springframework.data.jpa.domain.support.AuditingEntityListener"/>
</entity-listeners>
</persistence-unit-defaults>
</persistence-unit-metadata>
</entity-mappings>
--> And the starting point of the app
src/main/java/foo/bar/SpringJpaAuditSample.java :
package foo.bar;
import foo.bar.domain.ContactAudit;
import foo.bar.service.ContactAuditService;
import org.springframework.context.support.GenericXmlApplicationContext;
import java.util.Date;
import java.util.List;
public class SpringJpaAuditSample {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("spring-config.xml");
ContactAuditService contactService = ctx.getBean("contactAuditService", ContactAuditService.class);
List<ContactAudit> contacts = contactService.findAll();
listContacts(contacts);
//Add new contact
System.out.println("Add new contact");
ContactAudit contact = new ContactAudit();
contact.setFirstName("Michael");
contact.setLastName("Jackson");
contact.setBirthDate(new Date());
contactService.save(contact);
contacts = contactService.findAll();
listContacts(contacts);
}
private static void listContacts(List<ContactAudit> contacts)
{
System.out.println("");
System.out.println("Listing contacts without details:");
for(ContactAudit contact: contacts)
{
System.out.println(contact);
System.out.println();
}
}
}
The findAll returns this :
Listing contacts without details:
Contact - Id: 4, First name: Michael, Last name: Jackson, Birthday: 2013-05-27, Create by: null, Create date: 2013-05-27T04:02:36.000+03:00, Modified by: null, Modifed date: 2013-05-27T04:02:36.000+03:00
Which means that I get null instead of the string 'prospring3'.
Any ideas?
Thank you.
The 'error' I had with this project created with IntelliJ Idea is that I let the IDE create the META-INF directory wherever it chose and I have not noticed that the author had placed it inside resources directory.
The motivation for this fix came out of this post ("No Persistence Unit Found" error).

Why Hibernate Search takes so much time to build a Index?

I am trying to build a lucene index through hibernate searchFullTextSession.createIndexer().startAndWait()
but even for very little test data it won't end.
Here is my code
#Component("hibernateSearchMassIndexerService")
public class HibernateSearchMassIndexerServiceImpl implements HibernateSearchMassIndexerService {
public static final Logger log = LoggerFactory
.getLogger(HibernateSearchMassIndexerServiceImpl.class);
#Override
#Transactional
public void buildSearchIndex(Session session) {
log.debug("Indexing entities");
FullTextSession fullTextSession = Search.getFullTextSession(session);
try {
fullTextSession.createIndexer().startAndWait();
} catch (InterruptedException e) {
log.debug("Interrupted indexing process");
}
log.debug("Ended indexing of entities");
}
}
Entities
#Entity
#Indexed(index = "causa_penal")
#Table(name = "causas_penales")
public class CausaPenal implements Serializable {
private static final long serialVersionUID = 1L;
#Basic
#Column(name = "anio_causa")
#Field
private Integer annioCausa;
#OneToMany(mappedBy = "causaPenal")
#ContainedIn
#OrderBy
private List<AudienciaOral> audienciasOrales;
#ManyToMany(cascade = CascadeType.ALL)
private List<DefensorPenal> defensoresPenales;
#OneToMany(cascade = CascadeType.ALL)
private List<DelitoConfigurado> delitosConfigurados;
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
#Column(name = "id")
#DocumentId
private Integer id;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "causapenal_imputados")
#IndexedEmbedded(depth = 1)
private List<ParteMaterial> imputados;
#ManyToMany(cascade = CascadeType.ALL)
private List<MinisterioPublico> ministeriosPublicos;
#Basic
#Column(name = "numero_causa")
#Field
private Integer numeroCausa;
#Version
#Column(name = "opt_lock")
private Integer version;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "causapenal_victimas")
#IndexedEmbedded(depth = 1)
private List<ParteMaterial> victimas;
public CausaPenal() {
}
public CausaPenal(Integer id, Integer version, Integer numeroCausa, Integer annioCausa,
List<DelitoConfigurado> delitosConfigurados, List<ParteMaterial> victimas,
List<ParteMaterial> imputados, List<MinisterioPublico> ministeriosPublicos,
List<DefensorPenal> defensoresPenales, List<AudienciaOral> audienciasOrales) {
super();
this.id = id;
this.version = version;
this.numeroCausa = numeroCausa;
this.annioCausa = annioCausa;
this.delitosConfigurados = delitosConfigurados;
this.victimas = victimas;
this.imputados = imputados;
this.ministeriosPublicos = ministeriosPublicos;
this.defensoresPenales = defensoresPenales;
this.audienciasOrales = audienciasOrales;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (!(obj instanceof CausaPenal)) {
return false;
}
CausaPenal o = (CausaPenal) obj;
return new EqualsBuilder().append(this.numeroCausa, o.numeroCausa)
.append(this.annioCausa, o.annioCausa).isEquals();
}
public Integer getAnnioCausa() {
return this.annioCausa;
}
public List<AudienciaOral> getAudienciasOrales() {
return this.audienciasOrales;
}
public List<DefensorPenal> getDefensoresPenales() {
return this.defensoresPenales;
}
public List<DelitoConfigurado> getDelitosConfigurados() {
return this.delitosConfigurados;
}
public Integer getId() {
return this.id;
}
public List<ParteMaterial> getImputados() {
return this.imputados;
}
public List<MinisterioPublico> getMinisteriosPublicos() {
return this.ministeriosPublicos;
}
public Integer getNumeroCausa() {
return this.numeroCausa;
}
public Integer getVersion() {
return this.version;
}
public List<ParteMaterial> getVictimas() {
return this.victimas;
}
#Override
public int hashCode() {
return new HashCodeBuilder(13, 33).append(this.numeroCausa).append(this.annioCausa)
.toHashCode();
}
public void setAnnioCausa(Integer annioCausa) {
this.annioCausa = annioCausa;
}
public void setAudienciasOrales(List<AudienciaOral> audienciasOrales) {
this.audienciasOrales = audienciasOrales;
}
public void setDefensoresPenales(List<DefensorPenal> defensoresPenales) {
this.defensoresPenales = defensoresPenales;
}
public void setDelitosConfigurados(List<DelitoConfigurado> delitosConfigurados) {
this.delitosConfigurados = delitosConfigurados;
}
public void setId(Integer id) {
this.id = id;
}
public void setImputados(List<ParteMaterial> imputados) {
this.imputados = imputados;
}
public void setMinisteriosPublicos(List<MinisterioPublico> ministeriosPublicos) {
this.ministeriosPublicos = ministeriosPublicos;
}
public void setNumeroCausa(Integer numeroCausa) {
this.numeroCausa = numeroCausa;
}
public void setVersion(Integer version) {
this.version = version;
}
public void setVictimas(List<ParteMaterial> victimas) {
this.victimas = victimas;
}
#Override
public String toString() {
return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
}
#Entity
#Indexed(index = "partes_materiales")
#Table(name = "partes_materiales")
public class ParteMaterial implements Serializable {
private static final long serialVersionUID = 1L;
#Basic
#Column(name = "alias")
private String alias;
#Basic
#Column(name = "apellido_materno")
#Field
private String apellidoMaterno;
#Basic
#Column(name = "apellido_paterno")
#Field
private String apellidoPaterno;
#Basic
#Column(name = "descripcion_persona_moral")
private String descripcionPersonaMoral;
#ElementCollection
#JoinTable(name = "partes_materiales_domicilios")
private List<Domicilio> domicilios;
#Basic
#Column(name = "edad")
private Integer edad;
#Enumerated(EnumType.STRING)
#Column(name = "estado_civil")
private EstadoCivil estadoCivil;
#Temporal(TemporalType.DATE)
#Column(name = "fecha_nacimiento")
private Date fechaNacimiento;
#Enumerated(EnumType.STRING)
#Column(name = "genero")
private Genero genero;
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
#Column(name = "id")
#DocumentId
private Integer id;
#Basic
#Column(name = "identificacion_personal")
private String identificacion;
#Basic
#Column(name = "idioma")
private String idioma;
#Basic
#Column(name = "lugar_nacimiento")
private String lugarNacimiento;
#Basic
#Column(name = "nombres")
#Field
private String nombres;
#Basic
#Column(name = "profesion_oficio")
private String profesionOrOficio;
#Version
#Column(name = "opt_lock")
private Integer version;
public ParteMaterial() {
}
public ParteMaterial(String alias, String apellidoMaterno, String apellidoPaterno,
String descripcionPersonaMoral, List<Domicilio> domicilios, Integer edad,
EstadoCivil estadoCivil, Date fechaNacimiento, Genero genero, Integer id,
String identificacion, String idioma, String lugarNacimiento, String nombres,
String profesionOrOficio, Integer version) {
super();
this.alias = alias;
this.apellidoMaterno = apellidoMaterno;
this.apellidoPaterno = apellidoPaterno;
this.descripcionPersonaMoral = descripcionPersonaMoral;
this.domicilios = domicilios;
this.edad = edad;
this.estadoCivil = estadoCivil;
this.fechaNacimiento = fechaNacimiento;
this.genero = genero;
this.id = id;
this.identificacion = identificacion;
this.idioma = idioma;
this.lugarNacimiento = lugarNacimiento;
this.nombres = nombres;
this.profesionOrOficio = profesionOrOficio;
this.version = version;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (!(obj instanceof ParteMaterial)) {
return false;
}
ParteMaterial o = (ParteMaterial) obj;
return new EqualsBuilder().append(this.nombres, o.nombres)
.append(this.apellidoPaterno, o.apellidoPaterno)
.append(this.apellidoMaterno, o.apellidoMaterno)
.append(this.descripcionPersonaMoral, o.descripcionPersonaMoral).isEquals();
}
public String getAlias() {
return this.alias;
}
public String getApellidoMaterno() {
return this.apellidoMaterno;
}
public String getApellidoPaterno() {
return this.apellidoPaterno;
}
public String getDescripcionPersonaMoral() {
return this.descripcionPersonaMoral;
}
public List<Domicilio> getDomicilios() {
return this.domicilios;
}
public Integer getEdad() {
return this.edad;
}
public EstadoCivil getEstadoCivil() {
return this.estadoCivil;
}
public Date getFechaNacimiento() {
return this.fechaNacimiento;
}
public Genero getGenero() {
return this.genero;
}
public Integer getId() {
return this.id;
}
public String getIdentificacion() {
return this.identificacion;
}
public String getIdioma() {
return this.idioma;
}
public String getLugarNacimiento() {
return this.lugarNacimiento;
}
public String getNombres() {
return this.nombres;
}
public String getProfesionOrOficio() {
return this.profesionOrOficio;
}
public Integer getVersion() {
return this.version;
}
#Override
public int hashCode() {
return new HashCodeBuilder(31, 147).append(this.nombres).append(this.apellidoPaterno)
.append(this.apellidoMaterno).append(this.descripcionPersonaMoral).toHashCode();
}
public void setAlias(String alias) {
this.alias = alias;
}
public void setApellidoMaterno(String apellidoMaterno) {
this.apellidoMaterno = apellidoMaterno;
}
public void setApellidoPaterno(String apellidoPaterno) {
this.apellidoPaterno = apellidoPaterno;
}
public void setDescripcionPersonaMoral(String descripcionPersonaMoral) {
this.descripcionPersonaMoral = descripcionPersonaMoral;
}
public void setDomicilios(List<Domicilio> domicilios) {
this.domicilios = domicilios;
}
public void setEdad(Integer edad) {
this.edad = edad;
}
public void setEstadoCivil(EstadoCivil estadoCivil) {
this.estadoCivil = estadoCivil;
}
public void setFechaNacimiento(Date fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
public void setGenero(Genero genero) {
this.genero = genero;
}
public void setId(Integer id) {
this.id = id;
}
public void setIdentificacion(String identificacion) {
this.identificacion = identificacion;
}
public void setIdioma(String idioma) {
this.idioma = idioma;
}
public void setLugarNacimiento(String lugarNacimiento) {
this.lugarNacimiento = lugarNacimiento;
}
public void setNombres(String nombres) {
this.nombres = nombres;
}
public void setProfesionOrOficio(String profesionOrOficio) {
this.profesionOrOficio = profesionOrOficio;
}
public void setVersion(Integer version) {
this.version = version;
}
#Override
public String toString() {
return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
}
Spring config:
<?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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:util="http://www.springframework.org/schema/util"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${datasource.driverClassName}" />
<property name="url" value="${datasource.url}" />
<property name="username" value="${datasource.username}" />
<property name="password" value="${datasource.password}" />
<property name="initialSize" value="${datasource.poolInitialSize}" />
</bean>
<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="hibernateProperties">
<props>
<prop key="hibernate.current_session_context_class">
mx.gob.jgtjo.apps.schedule.web.conversation.ConversationalCurrentSessionContext
</prop>
<prop key="hibernate.dialect">${org.hibernate.dialect.dialectmysqlInno}</prop>
<prop key="hibernate.hbm2ddl.auto">${org.hibernate.ddl.mode}</prop>
<prop key="hibernate.connection.release_mode">${org.hibernate.transaction.release_mode}</prop>
<prop key="hibernate.search.default.directory_provider">${org.hibernate.search.directoryprovidr}</prop>
<prop key="hibernate.search.default.indexBase">
${org.hibernate.search.index.base_directory}
</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
<property name="dataSource" ref="dataSource" />
<property name="hibernateManagedSession" value="true" />
</bean>
<tx:annotation-driven order="0" transaction-manager="transactionManager" />
<context:component-scan base-package="mx.gob.jgtjo.apps.schedule.dao.hibernate" />
</beans>
Hibernate Config
<?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 name="jgtjoSessionFactory">
<!--Entity -->
<mapping class="mx.gob.jgtjo.apps.schedule.model.AudienciaOral" />
<mapping class="mx.gob.jgtjo.apps.schedule.model.CausaPenal" />
<mapping class="mx.gob.jgtjo.apps.schedule.model.DefensorPenal" />
<mapping class="mx.gob.jgtjo.apps.schedule.model.Delito" />
<mapping class="mx.gob.jgtjo.apps.schedule.model.EventoAudiencia" />
<mapping class="mx.gob.jgtjo.apps.schedule.model.Juez" />
<mapping class="mx.gob.jgtjo.apps.schedule.model.MinisterioPublico" />
<mapping class="mx.gob.jgtjo.apps.schedule.model.ParteMaterial" />
<mapping class="mx.gob.jgtjo.apps.schedule.model.Sala" />
<mapping class="mx.gob.jgtjo.apps.schedule.model.TipoAudiencia" />
<mapping class="mx.gob.jgtjo.apps.schedule.model.User" />
<mapping class="mx.gob.jgtjo.apps.schedule.model.Rol" />
<mapping class="mx.gob.jgtjo.apps.schedule.model.DelitoConfigurado" />
</session-factory>
</hibernate-configuration>
And a little bit of my logging:
09:33:18,767 [ssIndexerServiceImpl] (tp-bio-8080"-exec-10) DEBUG : Indexing entities
09:33:18,773 [orphicIndexHierarchy] (tp-bio-8080"-exec-10) TRACE : Targeted indexed classes for [class java.lang.Object]: [class mx.gob.jgtjo.apps.schedule.model.CausaPenal, class mx.gob.jgtjo.apps.schedule.model.ParteMaterial]
09:33:18,774 [MassIndexerImpl ] (tp-bio-8080"-exec-10) DEBUG : Targets for indexing job: [class mx.gob.jgtjo.apps.schedule.model.CausaPenal, class mx.gob.jgtjo.apps.schedule.model.ParteMaterial]
09:33:18,819 [orphicIndexHierarchy] (tp-bio-8080"-exec-10) TRACE : Targeted indexed classes for [class mx.gob.jgtjo.apps.schedule.model.CausaPenal, class mx.gob.jgtjo.apps.schedule.model.ParteMaterial]: [class mx.gob.jgtjo.apps.schedule.model.CausaPenal, class mx.gob.jgtjo.apps.schedule.model.ParteMaterial]
09:33:18,869 [Workspace ] (tp-bio-8080"-exec-10) TRACE : IndexWriter opened using batch configuration
09:33:18,869 [PurgeAllWorkDelegate] (tp-bio-8080"-exec-10) TRACE : purgeAll Lucene index using IndexWriter for type: class mx.gob.jgtjo.apps.schedule.model.CausaPenal
09:33:18,889 [Workspace ] (tp-bio-8080"-exec-10) TRACE : IndexWriter opened using batch configuration
09:33:18,890 [PurgeAllWorkDelegate] (tp-bio-8080"-exec-10) TRACE : purgeAll Lucene index using IndexWriter for type: class mx.gob.jgtjo.apps.schedule.model.ParteMaterial
09:33:18,891 [OptimizeWorkDelegate] (tp-bio-8080"-exec-10) TRACE : optimize Lucene index: class mx.gob.jgtjo.apps.schedule.model.CausaPenal
09:33:18,893 [OptimizeWorkDelegate] (tp-bio-8080"-exec-10) TRACE : optimize Lucene index: class mx.gob.jgtjo.apps.schedule.model.ParteMaterial
09:33:18,940 [WrapInJTATransaction] ( collectionsloader-2) TRACE : TransactionFactory does not require a TransactionManager: don't wrap in a JTA transaction
09:33:18,940 [WrapInJTATransaction] ( collectionsloader-3) TRACE : TransactionFactory does not require a TransactionManager: don't wrap in a JTA transaction
09:33:18,940 [WrapInJTATransaction] ( collectionsloader-2) TRACE : TransactionFactory does not require a TransactionManager: don't wrap in a JTA transaction
09:33:18,944 [nsumerEntityProducer] (hIndexingWorkspace-2) TRACE : created
09:33:18,946 [WrapInJTATransaction] ( collectionsloader-4) TRACE : TransactionFactory does not require a TransactionManager: don't wrap in a JTA transaction
09:33:18,947 [nsumerEntityProducer] (hIndexingWorkspace-2) TRACE : created
09:33:18,948 [WrapInJTATransaction] (arch: entityloader-1) TRACE : TransactionFactory does not require a TransactionManager: don't wrap in a JTA transaction
09:33:18,932 [WrapInJTATransaction] ( collectionsloader-1) TRACE : TransactionFactory does not require a TransactionManager: don't wrap in a JTA transaction
09:33:18,932 [WrapInJTATransaction] ( collectionsloader-1) TRACE : TransactionFactory does not require a TransactionManager: don't wrap in a JTA transaction
09:33:18,950 [WrapInJTATransaction] (arch: entityloader-2) TRACE : TransactionFactory does not require a TransactionManager: don't wrap in a JTA transaction
09:33:18,951 [WrapInJTATransaction] ( collectionsloader-3) TRACE : TransactionFactory does not require a TransactionManager: don't wrap in a JTA transaction
09:33:18,974 [IdentifierProducer ] (hIndexingWorkspace-2) TRACE : created
09:33:18,948 [nsumerEntityProducer] (arch: entityloader-1) TRACE : started
09:33:18,973 [WrapInJTATransaction] ( collectionsloader-4) TRACE : TransactionFactory does not require a TransactionManager: don't wrap in a JTA transaction
09:33:18,951 [nsumerEntityProducer] (hIndexingWorkspace-1) TRACE : created
09:33:18,950 [nsumerEntityProducer] (arch: entityloader-2) TRACE : started
09:33:18,975 [WrapInJTATransaction] (: identifierloader-1) TRACE : TransactionFactory does not require a TransactionManager: don't wrap in a JTA transaction
09:33:18,978 [nsumerEntityProducer] (hIndexingWorkspace-1) TRACE : created
09:33:18,978 [WrapInJTATransaction] (arch: entityloader-1) TRACE : TransactionFactory does not require a TransactionManager: don't wrap in a JTA transaction
09:33:18,979 [nsumerEntityProducer] (arch: entityloader-1) TRACE : started
09:33:18,977 [IdentifierProducer ] (: identifierloader-1) TRACE : started
09:33:18,979 [IdentifierProducer ] (hIndexingWorkspace-1) TRACE : created
09:33:18,988 [WrapInJTATransaction] (arch: entityloader-2) TRACE : TransactionFactory does not require a TransactionManager: don't wrap in a JTA transaction
09:33:18,989 [nsumerEntityProducer] (arch: entityloader-2) TRACE : started
09:33:19,049 [WrapInJTATransaction] (: identifierloader-1) TRACE : TransactionFactory does not require a TransactionManager: don't wrap in a JTA transaction
09:33:19,050 [IdentifierProducer ] (: identifierloader-1) TRACE : started
I do not why but it seems to me that hibernate search is somehow entering a infinite loop. Any help is welcome.
In case you haven't figured it out already, check your maximum allowed connections, as the mass indexer uses a lot of connections. For example, if you use a pooled data source like c3p0:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="username"/>
<property name="password" value="password"/>
<property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/>
<property name="jdbcUrl" value="jdbc:oracle:thin:#my.dbserver.com:1521:PRODUCTION"/>
<property name="initialPoolSize" value="1"/>
<property name="minPoolSize" value="1"/>
<property name="maxPoolSize" value="10"/>
</bean>
Try setting initialPoolSize to 3 and maxPoolSize 100 or higher and try again.
Hope that helps!

Categories