I'm pretty new to Spring, and I probably miss something obvious here. I'm working on a project that dates back to 2008 or so, which uses Spring (v4.2.5) and Hibernate (v3.5.6). I've copied some code from another project of around the same time-period, and currently try to access the Hibernate Session from that copied code.
Some things I've tried, which all gave back null for both the HibernateTemplate and HibernateSession:
1.
org.hibernate.Session session = org.springframework.orm.hibernate3.SessionFactoryUtils
.getSession(getSessionFactory(), true);
// getSessionFactory comes from the Parent class
// org.springframework.orm.hibernate3.support.HibernateDaoSupport
2.
org.hibernate.Session session = org.springframework.orm.hibernate3.SessionFactoryUtils
.getSession(HibernateUtil.getSessionFactory(), true);
// Where HibernateUtil is our own factory-class:
import java.io.PrintStream;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
static {
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
}
3.
org.springframework.orm.hibernate3.HibernateTemplate hibernateTemplate = getHibernateTemplate();
org.hibernate.Session session = org.springframework.orm.hibernate3.SessionFactoryUtils
.getSession(hibernateTemplate.getSessionFactory(), true);
// getHibernateTemplate comes from the Parent class
// org.springframework.orm.hibernate3.support.HibernateDaoSupport
4.
org.springframework.orm.hibernate3.HibernateTemplate hibernateTemplate = getSpringHibernateTemplate();
org.hibernate.Session session = org.springframework.orm.hibernate3.SessionFactoryUtils
.getSession(hibernateTemplate.getSessionFactory(), true);
// Where getSpringHibernateTemplate is:
#InjectObject("spring:hibernateTemplate")
public abstract HibernateTemplate getSpringHibernateTemplate();
// With the following bean in our ourprojectname-general.xml:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="mappingDirectoryLocations">
<!-- Add all Hibernate mappings to the list below -->
<list>
<value>/WEB-INF/hbm</value>
</list>
</property>
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<prop key="net.sf.ehcache.configurationResourceName">spinoff/dao/ehcache.xml</prop>
<!-- Determines the size of the JDBC fetch, that is the maximum number
of rows that are exchanged between Hibernate and the database in one go.
It's been increased to reduce overhead when searching for all entiteits -->
<prop key="hibernate.jdbc.fetch_size">500</prop>
<prop key="hibernate.dialect">spinoff.objects.spatial.oracle.OracleSpatialDialect</prop>
<prop key="hibernate.default_batch_fetch_size">25</prop>
<prop key="hibernate.generate_statistics">false</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="use_sql_comments">false</prop>
<prop key="hibernate.transaction.flush_before_completion">true</prop>
<prop key="hibernate.connection.release_mode">after_transaction</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
5.
I've also tried this SO answer with the same result:
java.lang.IllegalArgumentException: No SessionFactory specified
at org.springframework.util.Assert.notNull(Assert.java:115)
...
On most other places in the code it's done like at 1, and it was also done like this in the copied code in the other project.
My guess is that I need to #InjectObject or #AutoWired a getter for the Spring-bean of either the HibernateTemplate or Session, something like I've tried at 4, but it remains returning null.
Could anyone point me to an answer? All I want is a Hibernate DB-Session in my class. If you need to see the code of any other .java or .xml files let me know.
Ok, as correctly pointed out by #M.Deinum in the comments, I was looking at my problem at the completely wrong spot. It turned out I forgot to copy a few String-beans from the other project's XML-files where I copied the java files from.
So, after copying and slightly modifying those beans it worked by just using Session session = SessionFactoryUtils.getSession(getSessionFactory(), true);
Here are the beans:
<bean id="ourDaoTarget" class="our.dao.OurDao">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="ourDao" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<list>
<value>plus.dao.IOurDao</value>
</list>
</property>
<property name="target" ref="ourDaoTarget" />
<property name="interceptorNames">
<list>
<value>hibernateInterceptor</value>
</list>
</property>
</bean>
<bean id="messageProcessor" class="our.plus.MessageProcessor">
<property name="ourDao" ref="ourDao" />
</bean>
And in the MessageProcessor class where the Dao was used I had to add a default constructor and getter & setter for the Dao.
Again thanks, #M.Deinum
Related
I have legacy hbm.xml configured persistent classes and Annotated persistent classes, so currently we have to specify per which session factory is being used in the DAO bean.
Unfortunately, that means that I'm running into an issue where we have a mix of DAO's that I'd like to use, aren't all associated to a single session factory.
I'd like to combine both into a single session factory bean since we can't just move everything over all at once.
How would I go about doing this?
Note: my current workaround is to Annotate some of the xml configured ones and then create two DAO beans: one for each Session Factory.
HBM.XML:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingLocations">
<value>hbm/path/*.hbm.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
Annotated:
<bean id="annotatedSessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="path.batch.persistent"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
Thanks M.Deinum and orid:
I was overthinking this.
There was never a need for two session factories.
So I just had to refactor the context file to:
<bean id="annotatedSessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="path.batch.persistent"/>
<property name="mappingLocations">
<value>hbm/path/*.hbm.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
I need to configure #TypeDefs for use custom #Type on package level. When I configured it following manner I am getting ClassNotFoundException. But when I put #TypeDefs on the class level it is working fine.
I have found similar kind of stackoverflow post but I haven't any idea to how to configure <resource package="com.foo.bar.thepackage"/> entry with my application-context.xml file.
According some post (as bellow), noted this a Spring related bug
I believe this is due to a bug in Spring, where it doesn't scan the annotations in package-info, but only those on classes annotated with #Entity, #Embeddable, or #MappedSuperclass. See https://jira.springsource.org/browse/SPR-8589.
Can any one help me to resolve this issue. Thanks.
#TypeDefs declaration with package-info.java
#TypeDefs
({
#TypeDef(
name="encryptedString",
typeClass=EncryptedStringType.class,
parameters={
#Parameter(name="encryptorRegisteredName",
value="abcHibernateStringEncryptor")
}
)
})
package com.abc.core.model;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;
import org.hibernate.annotations.Parameter;
import org.jasypt.hibernate4.type.EncryptedStringType;
application-context.xml
<!-- ############################### General Configurations #################################################### -->
<!-- Enable annotation-driven configuration and auto-detection -->
<context:annotation-config/>
<!-- Enable Spring configuration-detection -->
<context:spring-configured/>
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="com.abc"/>
<!-- Configure property placeholders for environment-specific properties customization -->
<context:property-placeholder ignore-resource-not-found="true" location="classpath*:/project.properties"/>
<!-- ############################### Persistence Related Configurations ######################################## -->
<!-- JPA adapter -->
<bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
</bean>
<!-- EntityManager factory -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />
<property name="packagesToScan" value="com.abc.core.model" />
<property name="jpaProperties">
<props>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgresPlusDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.use_sql_comments">false</prop>
<prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
<prop key="hibernate.connection.autocommit">false</prop>
</props>
</property>
</bean>
<!-- Transaction manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- JPA repositories -->
<jpa:repositories base-package="com.abc"
transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory"/>
<!-- Use #Transactional annotation on methods -->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
<!-- ## JASYPT related configurations ## -->
<!-- jasypt encryptor for string -->
<bean id="abcStringEncryptor"
class="org.jasypt.encryption.pbe.StandardPBEStringEncryptor">
<property name="algorithm">
<value>PBEWithMD5AndDES</value>
</property>
<property name="password">
<value>XXX</value>
</property>
</bean>
<!-- hibernate encryptor for string -->
<bean id="theHibernateStringEncryptor"
class="org.jasypt.hibernate4.encryptor.HibernatePBEStringEncryptor">
<property name="registeredName">
<value>abcHibernateStringEncryptor</value>
</property>
<property name="encryptor">
<ref bean="abcStringEncryptor" />
</property>
</bean>
Entity class with custom #Type mapping
package com.stee.rcm.core.model;
#Entity
#Table(name = "trail")
public class Trail implements Serializable {
#Id
#GeneratedValue
#Column(name = "ID")
private Integer id;
#Type(type="encryptedString")
#Column(name = "DESCRIPTION")
private String description;
}
Exception
Caused by: java.lang.ClassNotFoundException : encryptedString
I too faced same issue, It seems spring have some issue to scan TypeDef when they are at package-info.java class.
Declaring resource in the configuration is nothing but packagesToScan.You have already used in your configuration and even this does not help in scanning TypeDefs.
<resource package="com.foo.bar.thepackage"/>
We can go with any of below approaches
Declare TypeDef in each pojo classes(where ever userType/CustomType is used).
Explicitly register CustomType to hibernate configuration.This can be done in two ways:
Registering CustomType programmatic.
configuration.registerTypeOverride(new EncryptedStringType(),new String[]{"encryptedString"});
Declaring TypeDef in session factory bean configuration and extending local session factory bean.
Spring.xml :
<bean id="DateTypeSessionFactory" class="com.runtime.data.factory.TypeResolverSessionFactoryBean">
<property name="dataSource" ref="DateTypeDataSource"/>
<property name="packagesToScan" value="com.p27.datetype"/>
<property name="customTypes">
<array value-type="com.runtime.data.CustomType">
<ref bean="dateTimeCustomType"/>
</array>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
${DateType.dialect}
</prop>
<prop key="hibernate.show_sql">
false
</prop>
<prop key="hibernate.globally_quoted_identifiers">
false
</prop>
<prop key="hibernate.hbm2ddl.auto">
${DateType.hbm2ddl}
</prop>
</props>
</property>
</bean>
<bean id="persistentLocalDateTimeType" class="com.studio.common.data.type.WMPersistentLocalDateTime"/>
<bean id="dateTimeCustomType" class="com.runtime.data.CustomType">
<property name="type" ref="persistentLocalDateTimeType"/>
<property name="keys">
<list>
<value>DateTime</value>
<value>org.joda.time.LocalDateTime</value>
</list>
</property>
</bean>
public class CustomType {
private UserType type;
private String[] keys;
//getters & setters
}
SessionFactoryBean :
public class TypeResolverSessionFactoryBean extends LocalSessionFactoryBean {
private CustomType[] customTypes;
#Override
protected SessionFactory buildSessionFactory(LocalSessionFactoryBuilder sfb) {
if(customTypes != null) {
registerCustomTypes(sfb);
}
return sfb.buildSessionFactory();
}
protected void registerCustomTypes(LocalSessionFactoryBuilder sfb) {
for (CustomType customType : customTypes) {
sfb.registerTypeOverride(customType.getType(), customType.getKeys());
}
}
public void setCustomTypes(CustomType[] customTypes) {
this.customTypes = customTypes;
}
}
I've got a Hibernate 4 / Spring MVC 3.2.4/ Spring Data 1.4.1 with Spring Security application in which I am trying to integrate EventListeners on my entity classes. I think I have everything configured properly, and when I run my unit tests, I can see my event listeners being fired. However, when i run my full MVC application, the event listeners are never fired.
I'm a bit lost where/how to debug this problem. My EntityManagerFactory is setup pretty much the same in both cases:
PRODUCTION:
<beans profile="tomcat">
<!-- application datasource -->
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton" lazy-init="true">
<property name="jndiName" value="java:comp/env/jdbc/josak" />
</bean>
<!-- entity manager -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
<property name="packagesToScan" value="com.ia.domain"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.query.substitutions">true '1', false '0'</prop>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
</props>
</property>
</bean>
</beans>
UNIT TESTS:
<beans profile="test">
<jdbc:embedded-database id="dataSource" type="H2"></jdbc:embedded-database>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
<property name="packagesToScan" value="com.ia.domain"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.query.substitutions">true '1', false '0'</prop>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.use_sql_comments">true</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
</props>
</property>
</bean>
</beans>
so I presume that it isn't the case of the Unit test entityManagerFactory being defined differently.
My unit test is fairly simple:
#Transactional
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration({"classpath:META-INF/spring/applicationContext*.xml"})
#ActiveProfiles("test")
public class UserServiceImplTest {
#Test
public void updateUser(){
User newInfo = dod.getNewTransientUser(15);
userService.saveUser(newInfo);
}
}
If I put a breakpoint in my #PrePersist method, I see that the method is called.
My MVC controller is also fairly straight-forward:
#RequestMapping( method=RequestMethod.GET, value="getUserInfo/{userId}", produces=MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
#PreAuthorize("hasRole('ROLE_PERMISSION_RATE_VIEW')")
#Transactional
public String getUserInfo( #PathVariable long userId ){
userService.saveUser(createUser());
return "done";
}
where createUser() simply returns a new User object with filled fields. However, my breakpoint in my EventListener is never hit, nor do I see anything in my logs indicating that it was.
If it is helpful, I can post by event listener class as well, but didn't think it would have much value.
My Entity class is defined as:
#Entity
#EntityListeners( AuditEventListener.class)
public class User {
#TableGenerator( name="UUIDGenerator", pkColumnValue="user_id", table="uuid_generator", allocationSize=1)
#Id
#GeneratedValue(strategy = GenerationType.TABLE, generator="UUIDGenerator")
#Column(name = "id")
private Long id;
...
}
Am I missing something obvious here? Is there a reason why this is not working from within the MVC application, but is from within the unit test? My Unit test uses a full Spring context configuration as well so I am very confused as to the difference between the two cases.
I realize that this is a very nebulous question, but any guidance how to further debug this would be much appreciated.
As sad as it sounds, I think I have tracked the error down to being a jRebel problem. Not in jRebel itself, however, I had a rebel.xml config file that was pointing to my entities' classpath, even though I wanted jRebel to load the entities from my webapp class path (they are in 2 seperate modules). I have since modified my pom.xml and removed the rebel.xml file, and everything seems to work.
I am trying to config two sessionFactories using spring. My config looks similar to the one listed here
Here's my config.xml
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url">
<value>${hibernate.connection.url}</value>
</property>
<property name="driverClassName">
<value>${hibernate.connection.driver_class}</value>
</property>
<property name="username">
<value>${hibernate.connection.username}</value>
</property>
<property name="password">
<value>${hibernate.connection.password}</value>
</property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="mappingResources">
<list>
...Mappings
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
${hibernate.dialect}
</prop>
<prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.default_batch_fetch_size">${hibernate.default_batch_fetch_size}</prop>
<prop key="hibernate.c3p0.min_size">${hibernate.c3p0.min_size}</prop>
<prop key="hibernate.c3p0.max_size">${hibernate.c3p0.max_size}</prop>
<prop key="hibernate.c3p0.timeout">${hibernate.c3p0.timeout}</prop>
<prop key="hibernate.c3p0.max_statements">${hibernate.c3p0.max_statements}</prop>
<prop key="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</prop>
</props>
</property>
</bean>
<bean id="dataSource2"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url">
<value>${hibernate.connection.mirror_url}</value>
</property>
<property name="driverClassName">
<value>${hibernate.connection.driver_class}</value>
</property>
<property name="username">
<value>${hibernate.connection.mirror_username}</value>
</property>
<property name="password">
<value>${hibernate.connection.mirror_password}</value>
</property>
</bean>
<bean id="sessionFactory2"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource2" />
</property>
<property name="mappingResources">
<list>
...Mappings
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
${hibernate.dialect}
</prop>
<prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.default_batch_fetch_size">${hibernate.default_batch_fetch_size}</prop>
<prop key="hibernate.c3p0.min_size">${hibernate.c3p0.min_size}</prop>
<prop key="hibernate.c3p0.max_size">${hibernate.c3p0.max_size}</prop>
<prop key="hibernate.c3p0.timeout">${hibernate.c3p0.timeout}</prop>
<prop key="hibernate.c3p0.max_statements">${hibernate.c3p0.max_statements}</prop>
<prop key="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</prop>
</props>
</property>
</bean>
Then each dao gets a different sessionFactory assigned
<bean id="productDao"
class="test.dao.ProductDaoHibernate">
<property name="sessionFactory"><ref bean="sessionFactory" /></property>
</bean>
<bean id="currencyDao"
class="test.dao.CurrencyDaoHibernate">
<property name="sessionFactory"><ref bean="sessionFactory2" /></property>
</bean>
This config gets loaded when its added to the context
web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/test-data.xml /WEB-INF/classes/test-services.xml ... </param-value>
</context-param>
The problem shows whenever I start the server each sessionFactory built, but at the end of the second one this shows up:
[INFO] [org.springframework.beans.factory.support.DefaultListableBeanFactory]:? - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#97aaa6: defining beans [... Many elements...]; root of factory hierarchy
[INFO] [org.springframework.orm.hibernate3.LocalSessionFactoryBean]:? - Closing Hibernate SessionFactory
[INFO] [org.hibernate.impl.SessionFactoryImpl]:? - closing
[INFO] [org.springframework.orm.hibernate3.LocalSessionFactoryBean]:? - Closing Hibernate SessionFactory
[INFO] [org.hibernate.impl.SessionFactoryImpl]:? - closing
Any help, or lead would be appreciated, if you need more info please ask
spring4.2 & hibernate5.1.5
#Bean
public LocalSessionFactoryBean aaaSessionFactory() {
LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
localSessionFactoryBean.setDataSource(smsDataSource());
localSessionFactoryBean.setHibernateProperties(getHibernateProperties());
localSessionFactoryBean.setPackagesToScan(new String[]{"com.xxx.pojo"});
localSessionFactoryBean.setPhysicalNamingStrategy(new CustomNamingStrategy());
localSessionFactoryBean.setEntityInterceptor(new DynamicTableInterceptor());
return localSessionFactoryBean;
}
#Bean
public LocalSessionFactoryBean bbbSessionFactoryMultiple() {
LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
localSessionFactoryBean.setDataSource(smsDataSource());
localSessionFactoryBean.setHibernateProperties(getHibernateProperties());
localSessionFactoryBean.setPackagesToScan(new String[]{"com.xxx.pojo"});
localSessionFactoryBean.setPhysicalNamingStrategy(new CustomNamingStrategy());
localSessionFactoryBean.setEntityInterceptor(new DynamicTableInterceptor());
return localSessionFactoryBean;
}
public class xxx extends HibernateDaoSupport{***
#Autowired
public void anyMethodName(#Qualifier("aaaSessionFactory") SessionFactory sessionFactory) {
setSessionFactory(sessionFactory);
}
Actually this is supposed to be a comment, but don't have enough reputation (requires 50 points)
It seems you are trying to create 2 different bean id's which are of exactly same configuration. One way is to figure out whether 2 different session objects pointing to same configuration is required. Other way is to try adding the configurations in different files and load separately. Please add how you r trying to use these configurations in code.
I want to do: #Autowire Session session. For hibernate 3, the process is described here. it uses ...hibernate3.SessionFactoryUtils.getSession. but in spring 3.2 there is no such method in ...hibernate4.SessionFactoryUtils
Great changes have taken place in Spring3.x, a few days ago I met the same problem, Through the offical document we know that Spring won't provide HibernateTemplate and HibernateDaoSupport any longer, we are advised to use Hibernate pure API, and about your confusion here is my solution:
first, define a sessionFactory bean in applicationContext.xml,
<!-- sessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="packagesToScan">
<list>
<value>com.bbs.*.entity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
${hibernate.dialect}
</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.connection.autocommit">${hibernate.connection.autocommit}</prop>
<prop key="hibernate.connection.url">jdbc:mysql://localhost/bbs</prop>
<prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
<prop key="hibernate.connection.username">root</prop>
<prop key="hibernate.connection.password">123456</prop>
</props>
</property>
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
and then, in your DAO
#Autowired
#Qualifier("sessionFactory")
private SessionFactory sessionFactory;
public Session getSession() {
return sessionFactory.getCurrentSession();
}
in this way you'll get the hibernate session, then do what you want, just enjoy it:)