Spring Data Repository caching results - caching

I am a complete spring data noob. I have an interface as follows
public interface UserBalanceRepository extends PagingAndSortingRepository<UserBalance, Integer>
{
#Cachable("UserList")
#Query("select userId from UserBalance")
List<Integer> ListUserIds(Pageable pageable);
}
My cache configuration looks like this:
<cache:annotation-driven />
<!-- generic cache manager -->
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean class="org.springframework.cache.concurrent.ConcurrentCacheFactoryBean" p:name="UserList"/>
</set>
</property>
</bean>
The caching does absolutely nothing. I guess it is because the proxied class does not have the #Cachable annotation, but how do I make the caching work? Is there a different way to do caching?
My last resort will be to put the calls that need to be cached inside a wrapper class and cache there.

I was facing the same issue. Your code is the same with mine. I am using eclipseLink and i had to enable caching on persistence.xml too. I just added a property,
[...]
<class>com.project.web.model.entity.ReturnOrder</class>
<class>com.project.web.model.entity.BillingAddress</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://connection string"/>
<property name="javax.persistence.jdbc.user" value="user"/>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.password" value="pass"/>
<!-- PROPERTY ADDED -->
<property name="eclipselink.cache.shared.default" value="true"/>
</properties>
</persistence-unit>
</persistence>
Also, this is a very good tutorial.

Related

Spring-Hibernate Caching with Memcached

I have an application whose back end has been made with Spring and Hibernate.
I Want to apply memcaching to make the application more scalable. At first i thought that i could integrate the second level cache of hibernate with memcache but the problem arouse was that all the HQL written in the application r like book.grade.id where Book & Grade are two separate entities, hence, the second level cache mechanism failed.
Can anyone recommend me a way to implement caching? I have had a look at EHCache but i want the Memcache implementation for now. My application will be hit by several servers but only 1 Database Server will exist. Given the required conditions, any recommendations?
Below mentioned are the steps you can follow.
pom.xml changes to include the abstract cache mechanism for memcache and client implementation using xmemcache.
com.google.code.simple-spring-memcached
spring-cache
3.1.0
<dependency>
<groupId>com.google.code.simple-spring-memcached</groupId>
<artifactId>xmemcached-provider</artifactId>
<version>3.1.0</version>
</dependency>
Note : You need to include cglib too as this is aop based.
configuration.xml file changes
**defining beans**
<bean name="cacheManager" class="com.google.code.ssm.spring.SSMCacheManager">
<property name="caches">
<set>
<bean class="com.google.code.ssm.spring.SSMCache">
<constructor-arg name="cache" index="0" ref="defaultCache"/>
<!-- 5 minutes -->
<constructor-arg name="expiration" index="1" value="300"/>
<!-- #CacheEvict(..., "allEntries" = true) doesn't work -->
<constructor-arg name="allowClear" index="2" value="false"/>
</bean>
</set>
</property>
</bean>
<bean name="defaultCache" class="com.google.code.ssm.CacheFactory">
<property name="cacheName" value="defaultCache" />
<property name="cacheClientFactory">
<bean name="cacheClientFactory"
class="com.google.code.ssm.providers.xmemcached.MemcacheClientFactoryImpl" />
</property>
<property name="addressProvider">
<bean class="com.google.code.ssm.config.DefaultAddressProvider">
<property name="address" value="x.x.x.x:11211" />
</bean>
</property>
<property name="configuration">
<bean class="com.google.code.ssm.providers.CacheConfiguration">
<property name="consistentHashing" value="true" />
</bean>
</property>
</bean>
Sample method...
#Cacheable(value="defaultCache", key="new Integer(#id).toString().concat('.BOOKVO')")
public BookVO getBookById(Integer id){
...
}
with this changes your method will hit the db only if the key is not found in the memcache server.

Spring data-jpa and exception handling

Recently I had been discovered Spring Data Jpa. The one thing I was not able to make it working was proper exception translation to Spring's Exception hierarchy.
According to this Spring Data JPA forces CGLib proxying to non repository classes the <jpa:repositories /> activates persistence exception translation for Spring beans annotated with #Repository. The reference documentation in this post points to spring-data-jpa 1.1.1.
But when you look at the docs for version 1.3.0 this paragraph has been removed. Also I was plying with #Repository annotation putting it wherever possible but with no success.
My question is: Is it possible to achieve proper exception translation with the recent spring-data-jpa lib version 1.3.0?
Ok. I will put some configuration here:
...
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="oracle.jdbc.OracleDriver"/>
<property name="jdbcUrl" value="jdbc:oracle:thin:#localhost:1521:pbase"/>
<property name="user" value="sa"/>
<property name="password" value="pass"/>
</bean>
<context:annotation-config/>
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="persistenceUnitName" value="prjPersistenceUnit"></property>
<property name="persistenceXmlLocation" value="classpath:META-INF/mpersistence.xml"></property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter"
p:showSql="true"/>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf"/>
</bean>
<tx:annotation-driven/>
<jpa:repositories base-package="com.mycompany.repository" />
Content of mpersistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="prjPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<description>Persistence unit which uses EclipseLink JPA 2.0 implementation.</description>
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.mycompany.Setting</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="eclipselink.target-server" value="JBoss"/>
<property name="eclipselink.target-database" value="Oracle10g"/>
<property name="eclipselink.weaving" value="static"/>
</properties>
</persistence-unit>
</persistence>
My rpository
#Repository
public interface TestRepository extends JpaRepository<Setting, Long> {
Setting findByNamee(String name);
}
Here findByNamee should rise some Spring database exception as a real property in the databese is name not namee. But I always get
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Though, when configuring a regular Dao object with #Repository annotation everything works as expected.
I am trying to deploy it on Tomcat 6.0 with eclipseLink 2.3.2.
You could check some working example code I published since then at https://github.com/zagyi/examples/tree/master/spring-data-jpa
You have to inject the EclipseLink Jpa Dialect to the EntityManagerFactory, because the exception translator is in the dialect.

Exception while creating EntityManagerFactory - Lookup failed for 'persistence/myPU' in SerialContext

I'm working with Glassfish application server and trying to connect my spring-hibernate web application to my db, I have the following configurations:
In Glassfish I have added a jdbc connection and send a successful ping to the DB.
I also added a JDBC resource (in glassfish) with jndi name: jdbc/myResource. This resource is under the connection pool in which I have created and tested (in step 1).
My EntityManaget is annotated with #PersistenceContext:
#PersistenceContext(unitName = "myPU")
protected EntityManager entityManager;
Under \src\main\resources\META-INF\ I created my persistence.xml file:
<persistence-unit name="myPU">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/myResource</jta-data-source>
<properties>
<!-- Glassfish transaction manager lookup -->
<property name="hibernate.transaction.manager_lookup_class"
value="org.hibernate.transaction.SunONETransactionManagerLookup" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"></property>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.default_schema" value="PUBLIC" />
<property name="hibernate.format_sql" value="true" />
<!-- Validates the existing schema with the current entities configuration -->
<property name="hibernate.hbm2ddl.auto" value="validate" />
</properties>
</persistence-unit>
This is how my applicationContext looks like:
bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<jee:jndi-lookup id="emf" jndi-name="persistence/myPU" />
<!-- In order to enable EntityManager injection -->
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
<property name="persistenceUnits">
<map>
<entry key="myPU" value="persistence/myPU" />
</map>
</property>
</bean>
In my web.xml I have:
<persistence-unit-ref>
<persistence-unit-ref-name>persistence/myPU</persistence-unit-ref-name>
<persistence-unit-name>myPU</persistence-unit-name>
When I publish I keep getting:
No bean named 'myPU' is defined. Please see server.log for more details.
Why is it looking for the persistence unit as a bean?
Any ideas what am I doing wrong?
Thanks in advance
Resolved - I added transaction-type="JTA" to my persistence.xml.
For some reason I was under the impression that if I'm specifying a jta-data-source in my persistence.xml the default transaction-type should be "JTA", maybe it isn't. I don't really understand the relation of the exception I had to this solution but at the moment my persistence.xml has the following line:
<persistence-unit name="myPU" transaction-type="JTA">
And it works like a charm.

Spring + Spring Data JPA Configuration

currently I'm fooling around with a Spring setup. My goal is to use JPA to get access to a Websphere datasource using it's JNDI name. I'm using Spring Data JPA to make life easier for me and worked through some tutorials to get the basic idea.
Bad thing: none of those is talking about the Spring configuration for my JPA szenario + I never worked with JPA / JDBC before.
So I hope you can help me out here. I got 2 configuration files:
applicationContext.xml
<bean id="txManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<bean id="eManager" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"></bean>
Since i'm using the #Transactual annotion within my code, i'm using the annotation-driven tag for the txManager. I'm just not really sure what else i should configure for the txManager and what the sessionFactory tag is doing. Is there any documentation for all supported XML tags? Am I missing a importent tag for my szenario?
Same about eManager - not sure if thats right in any way.
persistence.xml
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="spring-jpa">
<jta-data-source>jdbc/myJNDI</jta-data-source>
</persistence-unit>
</persistence>
Same thing here: don't really know what i'm doing. I know i need a persistence unit / provider. I know that many are using hibernate for this, but i would like to stay native and use pure JavaEE / Spring if possible.
I'm just not sure how to configure that.
Currently my project is crashing, telling me: "JPA PersistenceProvider returned null"
The best way is to obtain the EntityManagerFactory from the JNDI via Spring's JNDI support:
<jee:jndi-lookup id="entityManagerFactory" jndi-name="persistence/myPersistenceUnit" />
<jpa:repositories base-package="com.acme.repositories" />
<tx:jta-transactionManager />
This will cause the transaction manager being used from the application server as well. You can also try to setup a JpaTransactionManager and wire the EntityManagerFactory obtained from JNDI into it. You can pull even more configuration into your Spring config files if you only lookup the datasource through an <jee:jndi-lookup /> namespace element and follow the further configuration instructions in the Spring Data JPA reference documentation. Nevertheless it's usually better to use the container resources you can actually get if you decide to use container resources at all.
I just started working with Spring, jpa mysql etc... and I might be able to help you out.
I'll show you the way that I have my configuration right know.
I'm using hibernate by the way for my database connection, I've never did it without so no help from me there :)
My configuration:
Spring-config.xml:
<context:component-scan base-package="com.MYPACKAGE"/>
<!-- To find all your controllers -->
<tx:annotation-driven/>
<!-- This will pickup all your #Transactional annotations-->
<import resource="../database/DataSource.xml"/>
<import resource="../database/Hibernate.xml"/>
<!-- These are my database config files-->
Datasource.xml:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/DATABASENAME"/>
<property name="username" value="USERNAME"/>
<property name="password" value="PASSWORD"/>
</bean>
Hibernate.xml:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false"/>
<property name="generateDdl" value="true"/>
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect"/>
</bean>
</property>
</bean>
I left out the standard xml text that you need to include at the top of your .xml files, but I trust you to work that out yourself ;)
This setup works for me and I hope it can help you out!
If you have any question regarding this post please let me know!
Good luck!
for those using JBoss, the jndi names can be set in persistence.xml properties like this:
<persistence-unit name="punit" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/myDS/jta-data-source>
<class>com.company.model.Document</class>
<class>com.company.model.DocumentIndividual</class>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create" />
<!-- <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/> -->
<property name="javax.persistence.logging.level" value="INFO" />
<property name="hibernate.show_sql" value="true" />
<property name="jboss.entity.manager.jndi.name" value="java:/my_em"/>
<property name="jboss.entity.manager.factory.jndi.name" value="java:/my_emf"/>
</properties>
</persistence-unit>
as described in here section 4.4.2

Hibernate (JPA,JSF 2.0, Spring) switch from HyperSQL to Oracle - Configuration is being ignored

i'm currently in the process of working on a midsized Webproject, using JSF 2.0 with Spring.As IDE i use Eclipse with JBoss Tools. The Webapp is deployed to a Tomcat v7.0 Server.
I use Hibernate/JPA/C3P0/ to connect to the Database (previously HyperSQL) I now tried to switch to an Oracle DB, which i did a number of times before and it never was a problem, however now it seems, that the changed configuartion is just being ignored. When i fire up the Server, it still uses the HyperSQl Driver and the old DB, although i cleaned the workdirectory of Tomcat, removed and redeployed the Webapp (which i built from scratch of course).
The project is split in two, one webapp and one service part. The project are dependent in Eclipse. However, although all of the businesslogic is implemented in the service layer, i can just remove it and the webapp doesn't throw an error and i can start it as if nothing has changed. This tells me that it must be cached somewhere and it is not refreshed on the server...I also deleted the server, added a freshly downloaded instance - still the same thing...Does anyone have an Idea what this could be about?
Here is my service.spring.xml:
<!-- Enable processing of #PersistenceContext and #PersistenceUnit -->
<context:annotation-config/>
<!-- Enable transaction configuration with #Transactional -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- Configure a c3p0 pooled data source -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="user"/>
<property name="password" value="password"/>
<property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/>
<property name="jdbcUrl" value="jdbc:oracle:thin:#dburl"/>
<property name="initialPoolSize" value="1"/>
<property name="minPoolSize" value="1"/>
<property name="maxPoolSize" value="10"/>
</bean>
<!-- Configure the JPA entity manager factory with Hibernate -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false"/>
<property name="database" value="ORACLE"/>
<property name="generateDdl" value="true"/>
</bean>
</property>
<property name="persistenceUnitName" value="mygourmet"/>
</bean>
<!-- Configure transaction manager for JPA -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
And my persistence.xml:
<persistence-unit name="mygourmet" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.OracleDialect" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="false" />
<property name="hibernate.use_sql_comments" value="false" />
<property name="hibernate.connection.autocommit" value="false" />
<property name="hibernate.cache.use_query_cache" value="false" />
<property name="hibernate.cache.use_second_level_cache" value="false" />
<property name="hibernate.hbm2ddl.auto" value="create" />
</properties>
I used the exact same configuration on another project and it works like a charm...Any hints are highly appreciated, thank you guys in advance!
Problem solved - i did a mvn clean install, generated new eclipse projects and imported them back into eclipse. It seems the changes in my service module were not recognized by eclipse.

Resources