Using EJB and JPA for data caching
Knowing how to build a simple and local cache for your application is an important skill. It may have a big impact on some data access performance and it is quite easy to do.
This recipe will show you how.
Getting ready
Simply add a Java EE dependency to your project:
<dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency>
How to do it...
- Let's create a
User
class to be our cached object:
public class User { private String name; private String email; //DO NOT FORGET TO IMPLEMENT THE GETTERS AND SETTERS }
- And then create a singleton to hold our user list cache:
@Singleton @Startup public class UserCacheBean { protected Queue<User> cache = null; @PersistenceContext private EntityManager em; public UserCacheBean() { } ...