cache database query in application server - mysql

I had webapps using spring jdbc template and now , want to improve performance of my application , so i want to cache result of some DATABASE QUERY in my Tomcat server.How i can achieve dis concept.
Thanks

Spring 3.1 has introduced a Caching Abstraction. You should be able to make use of this to cache the results of your DAO method calls.
The documentation is here and it was included in the Spring blog here.

I have it working, but Alex is correct, there are a few different ways to configure this, depending on what you want as your Caching backend.
For cache configuration, I've selected ehcache, as it's simple to configure, but has powerful features for configuring ttl/etc.
Configuration:
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<cache:annotation-driven />
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager"><ref local="ehcache"/></property>
</bean>
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:configLocation="classpath:ehcache.xml"/>
</beans>
ehcache.xml:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false" monitoring="autodetect"
dynamicConfig="true">
<!-- http://ehcache.org/documentation/configuration.html -->
<!-- Also See org.springframework.cache.ehcache.EhCacheFactoryBean -->
<diskStore path="java.io.tmpdir"/>
<cache name="resourceBundle"
overflowToDisk="false"
eternal="false"
maxElementsInMemory="500"
timeToIdleSeconds="86400"
timeToLiveSeconds="86400"/>
</ehcache>
I had issues with running the ehcache 2.5 in my junit environment, due to caches with duplicate names running concurrently was not allowed, and they didn't seem to shut down right away, but here is my pom entry:
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.4.7</version>
</dependency>
Finally, on your repository, do the following:
#Repository
public class someStore {
#PersistenceContext
EntityManager em;
//The value here needs to match the name of the cache configured in your ehcache xml. You can also use Spel expressions in your key
#Cachable(value = "resourceBundle", key = "#basename+':'+#locale.toString()")
public ResourceBundle getResourceBundle(final String basename, final Locale locale){
...
}
#CacheEvict(value = "resourceBundle", key = "#basename+':'+#locale.toString()")
public void revertResourceBundle(final String basename, final Locale locale){
...
}
}

Related

Composite Persistence Unit using a single JAR file

I have searched the web and this site already for an answer. Although I found one link through a Google search, I subsequently lost the link and can't find it again.
I have been working on an e-commerce web site running on Glassfish 4.1.1 that originally had a single database (DB) using EclipseLink 2.6.4, but it now requires three that will reside on multiple servers (in order to keep customer data secure). The site worked fine with the single DB. I split the data from the single DB into three. The entities and JPA controllers defined in the J2EE code are all the same (I preserved the code so I wouldn't have to rewrite everything, only make minor changes such as annotations, etc.), but they are now located in three different MySQL databases. The three databases have relationships to one another.
In theory (and according the the link I saw and lost) a composite persistence unit (PU) can be defined to incorporate all three PU's for the three different data sources all within a single JAR file and using tags for the entity-PU mappings. Most of the examples (and the Eclipselink and Oracle Persistence API documentation) use a Composite PU with multiple JAR files (e.g.: https://github.com/forgemo/eclipselink-composite-persistence-unit-example).
Can anyone point me in the right direction as to how to create a composite PU without having to use a separate JAR file for each database PU?
My current persistence.xml file (musltiple PUs but not a composite) is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
>
<persistence-unit name="PU1" transaction-type="JTA">
<jta-data-source>java:app/jdbc/db1</jta-data-source>
<class>com.mysite.myproject.Database.Items</class>
<class>com.mysite.myproject.Database.Manufacturer</class>
<class>com.mysite.myproject.Database.Category</class>
<class>com.mysite.myproject.Database.Cart</class>
<class>com.mysite.myproject.Database.AuditTable</class>
<class>com.mysite.myproject.Database.Images</class>
<class>com.mysite.myproject.Database.Procedures</class>
<class>com.mysite.myproject.Database.Warehouse</class>
<class>com.mysite.myproject.Database.Wishlist</class>
<class>com.mysite.myproject.Database.Purchases</class>
<class>com.mysite.myproject.Database.TaxTables</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="eclipselink.logging.level" value="FINE"/>
</properties>
</persistence-unit>
<persistence-unit name="PU2" transaction-type="JTA">
<jta-data-source>java:app/jdbc/db2</jta-data-source>
<class>com.mysite.myproject.Database.AccessList</class>
<class>com.mysite.myproject.Database.Users</class>
<class>com.mysite.myproject.Database.Customer</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="eclipselink.logging.level" value="FINE"/>
</properties>
</persistence-unit>
<persistence-unit name="PU3" transaction-type="JTA">
<jta-data-source>java:app/jdbc/db3</jta-data-source>
<class>com.mysite.myproject.Database.Key1</class>
<class>com.mysite.myproject.Database.Key2</class>
<class>com.mysite.myproject.Database.Key3</class>
<class>com.mysite.myproject.Database.Key4</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
<property name="eclipselink.logging.level" value="FINE"/>
</properties>
</persistence-unit>
The above persistence.xml works fine as long as there are no relationships between data sources (e.g. - relationship between Wishlist and Customer tables results in "[class com.mysite.myproject.Database.Wishlist] uses a non-entity [class com.mysite.myproject.Database.Customer] as target entity in the relationship attribute [field customer]" at deployment).
As it turns out, it seems a composite persistence unit is not needed (which probably explains why nobody can answer the question and there is little documentation about them).
After finding many, many bugs in Glassfish, Geronimo, WebLogic, and Ecplipselink, and NetBeans, I was finally able to get the system working using multiple persistence units (PU) without using a composite PU. JTA is able to persist all entities including their references to entities outside their own PU. One key factor to making this work is to make sure classes not part of a PU are NOT excluded by adding this to your PU definition in persistence.xml:
<exclude-unlisted-classes>false</exclude-unlisted-classes>
as in the following complete PU example (one of the three I use in my project):
<persistence-unit name="DHWPU" transaction-type="JTA">
<jta-data-source>jdbc/dhw</jta-data-source>
<class>Database.AuditTable</class>
<class>Database.Cart</class>
<class>Database.Category</class>
<class>Database.Images</class>
<class>Database.Items</class>
<class>Database.Manufacturer</class>
<class>Database.Procedures</class>
<class>Database.Purchases</class>
<class>Database.TaxTables</class>
<class>Database.Warehouse</class>
<class>Database.Wishlist</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="none"/>
<property name="eclipselink.logging.level" value="FINE"/>
</properties>
</persistence-unit>

CAstle Windsor: How to reference a second xml config file that is an embedded resource?

We have one xml configuration file that we use in production. We also have a little test app that has a couple of additional needs. What I'd like to do is create a second, testing-only xml config file that references the embedded production configuration file. Is there any way to do this?
I'm aware of the "include" element, but am not sure where in the file it is supposed to be placed--in the castle node? The components node?
I feel like the answer is here but I'm too dense to figure it out.
Thanks for any help you can provide.
UPDATE
This is how our production config file is set up:
<?xml version="1.0" encoding="utf-8"?>
<OurCompany>
<Framework>
<castle>
<installers>
<!-- some installers-->
<installers>
<components>
<!--some components-->
<components>
<castle>
<Framework>
<OurCompany>
My most recent attempt at a non-production config file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<OurCompany>
<Framework>
<castle>
<include uri="assembly://AssemblyContainingEmbeddedXml/MyEmbeddedConfig.xml" />
<components>
<!--components I only want registered with container when running in non-production environment-->
<components>
<castle>
<Framework>
<OurCompany>
The exception I get reads:
Configuration parser encountered Framework, but it was expecting to find installers, facilities or components. There might be either a typo on or you might have forgotten to nest it properly.
(In the actual message, "Framework," "installers," "facilities," and "components" are enclosed in angle brackets.)
The bottom of the page you reference has an example of loading from an embedded resourced:
IResource resource = new AssemblyResource("assembly://Acme.Crm.Data/Configuration/services.xml");
container = new WindsorContainer(new XmlInterpreter(resource));

NHibernate with sql Server 2008 dialect don't support variable limits

I'm fighting with a strange behavior here...
Doing an asp.net mvc3 application with NHibernate as ORM and MS SQL Server 2008 as the DB, I'm running into these exeption:
System.NotSupportedException: Dialect does not support variable limits.
The code is pretty simple, a classic pagination query:
public IList<Agenzia> getAllAgenzie(int maximumRows, int startRowIndex)
{
using (var session = PersistenceManager.Istance.GetSession()) {
var result = (from agenzia in session.Query<Agenzia>()
select agenzia)
.Skip(startRowIndex)
.Take(maximumRows)
.ToList();
return result;
}
}
And here's the NHibernate configuration
<?xml version="1.0" encoding="utf-8" ?>
<!-- NHibernate Configuration -->
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory name="NHibernate.xlns">
<property name="dialect">
NHibernate.Dialect.MsSql2008Dialect
</property>
<property name="connection.driver_class">
NHibernate.Driver.SqlClientDriver
</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
Any idea what's wrong with it? I can't believe that NHibernate don't support this simple pagination...
What version of NHibernate are you using? (latest is 3.2)
It works without problems for me.
Also, this is redundant:
(from agenzia in session.Query<Agenzia>() select agenzia)
It's equivalent to:
session.Query<Agenzia>()

How to dynamically pass parameters in web.xml using weblogic 10.3.x?

I am trying to pass a JVM parameter for a variable configured in web.xml as a context-parameter using a -D notation when starting weblogic server. I have already tried this same configuration using Tomcat 7 and it works as expected, but it DOES NOT work in weblogic server 10.3.3. Any clues?
web.xml
<?xml version="1.0" encoding="UTF-8" ?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>testeParWebXml</display-name>
<context-param>
<description>Habilita ou desabilita a configuração de debug do Facelets! Página de debug do Seam.</description>
<param-name>facelets.DEVELOPMENT</param-name>
<param-value>${habilitar.debug}</param-value>
</context-param>
<welcome-file-list>
Then when starting the jvm I pass the parameter using:
-Dhabilitar.debug=true
And I built a Servlet to test:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter pw = response.getWriter();
String valorParametro = getServletContext().getInitParameter("facelets.DEVELOPMENT");
pw.write("Param value from web.xml ==>> " + valorParametro);
}
As I mentioned using Tomcat if I change the value to false or true in the -Dhabilitar.debug flag it correctly prints the value in the servlet.
Param value from web.xml ==>> true
In weblogic I get the output like:
Param value from web.xml ==>> ${habilitar.debug}
As noticed weblogic DOES NOT parse the value of the variable set in web.xml.
Is it possible to make this work properly in weblogic 10.3.3?
Looks like there is not a consistent behavior across different containers. IMHO you should not do it that way. I have always used (and have always seen people using) web.xml containing default values (rather than parameterized values) for stuff.
Please see these additional resources (including some not-so-elegant but working approaches to your problem):
Best practices for defining and initializing variables in web.xml and then accessing them from Java code
Referencing Environment Variables in web.xml
http://www.coderanch.com/t/79094/Websphere/environment-variable-referance-Web-xml
First attempt:
I believe that filtering crucial files such as web.xml is not a good practice. However you can use ant or maven to do that.
===
Second attempt:
Ok If identical packages are mandatory, I would prefer changing doPost method. Instead of passing the value to there, it could be passed key and set by System.getProperty method at there. And also setting a default value such as development environment makes sense.

JNDI and javax.sql.DataSource

I'm someone that used to do some J2EE coding in the past and I'm coming back into the fold to work on a new J2EE project. A lot has changed since 2001, so I need to ask this very basic question.
I'm using syntax like this in my database class:
#Resource(name = "jdbc/MyDatabase")
private javax.sql.DataSource dataSource;
I understand this is a new feature (annotations) but I'm not really sure how it works. Later on in my class I make this call:
Connection c = dataSource.getConnection();
And it throws a NullPointerException everytime. I step into this in the debugger and as it turns out, dataSource IS null.
It seems magical and weird that I do not initialize dataSource myself in the code. Any idea what I'm doing wrong?
My web.xml contains the following block to establish the resource:
<resource-env-ref>
<resource-env-ref-name>jdbc/MyDatabase</resource-env-ref-name>
<resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>
And I've added this to my Context by using a context.xml file in META-INF. The Context entry looks like:
<Resource name="jdbc/MyDatabase" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="username" password="password" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/mydb?autoReconnect=true"/>
I'm using Tomcat 6, MySQL 5, the latest MySQL driver (not the older v3 but the newest v5 driver).
Update: This is not working for me because I'm using it in a plain-old class. I've created a new project and added a servlet to it. The DataSource is non-null in the servlet.
You need at least to have the following in either the appserver's /conf/context.xml or the the webapplication's /META-INF/context.xml file:
<Resource
name="jdbc/MyDatabase"
type="javax.sql.DataSource"
driverClassName="com.your.Driver"
url="jdbc:your://url"
username="foo"
password="bar"
/>
Also see http://tomcat.apache.org/tomcat-6.0-doc/jndi-resources-howto.html
And in the webapp's /WEB-INF/web.xml you need to define the following:
<resource-env-ref>
<resource-env-ref-name>jdbc/MyDatabase</resource-env-ref-name>
<resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>
Edit: I now see that you edited your post to add the coding. I also see that you used resource-ref instead of resource-env-ref. The first refers to an external resource (read: not webcontainer-managed) and the second refers to an internal (environmental) resource (read: webcontainer-managed). Replace it and see.
Does your web.xml define the resource? Take a look at this example. Could you post your web.xml or the code that defines the jdbc/MyDatabase?