Archive

Posts Tagged ‘JEE Development’

A Handy and Highly Reusable JPA 2.0 Data Access Object

January 4th, 2011 negarnil 5 comments

Hi ! In this post I’ll show you a highly reusable Data Access Object for Java web applications which will reduce the development time of your DAOs.

Consider the following DAO and it’s implementation.

public interface UserDao {

     User storeUser(User user);

     void removeUser(User user);

     List<User> findAllUsers();

     User findUserById(long id);

}
public class JpaUserDao implements UserDao {

     @PersistentContext
     private EntityManager em;

     @Override
     public User storeUser(User user) {
          User merged = em.merge(user);
          em.persist(merged);
          return merged;
     }

     @Override
     public void removeUser(User user) {
          em.remove(user);
     }

     @Override
     public List<User> findAllUsers() {
          return (List <User>) em.createQuery("from User").getResultList();
     }

     @Override
     public User findUserById(Long id) {
        return em.find(User.class, id);
     }
}

It looks pretty cool ! We just coded a JPA 2.0 Data Access Object. This means we used standard Java libraries (javax.persistence package).

The problem with the above code is that you are going to repeat it for each entity in your application. Having those 40 lines of CRUD (Create-Remove-Update-Delete) code doesn’t only lead you to more development effort but only to a poorly maintainable application. A code generator like Spring Roo can do the work but we can avoid any code generation tools by applying some Java inheritance and spicy code like using Java Generics and Reflection. You’ll see how to use those forty lines for infinite entities DAOs.

First of all let’s create a generic DAO:

public interface BaseDao<T> {

	T store(T t);

	void remove(T t);

	List<T> findAll();

	T findById(long id);

}

The above interface will be extended by all your DAO interfaces.

We should now create a generic implementation of the above interface which will be extended by all the DAO implementations of your application.

@SuppressWarnings("unchecked")
@Repository
public abstract class JpaBaseDao<T extends Serializable> implements BaseDao<T> {

	private Class<T> clazz;

	@PersistenceContext
	protected EntityManager em;

	protected JpaBaseDao() {
		Class<T> getClass = (Class<T>) getClass();
		ParameterizedType genericSuperclass = (ParameterizedType) getClass.getGenericSuperclass();
		clazz = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
	}

	@Override
	public T store(T t) {
		T merged = em.merge(t);
		em.persist(merged);
		return merged;
	}

	@Override
	public void remove(T t) {
		em.remove(t);
	}

	@Override
	public List<T> findAll() {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<T> query = cb.createQuery(clazz);
		query.from(clazz);
		return em.createQuery(query).getResultList();
	}

	@Override
	public T findById(long id) {
		return em.find(clazz, id);
	}
}

The @Repository annotation is a Spring annotation which Indicates that an annotated class is a “Repository” (or “DAO”). A class thus annotated is eligible for Spring DataAccessException translation. The annotated class is also clarified as to its role in the overall application architecture for the purpose of tools, aspects, etc. Note that you don’t need it if you are not using Spring.

The @PersistenContext is a javax.persistence annotation which expresses a dependency on an EntityManager persistence context.

The final code:

public interface UserDao extends BaseDao<User> {

     // Custom access methods (which are not CRUD's) go here

}
public class JpaUserDao extends JpaBaseDao<User> implements UserDao {

   // Custom access methods implementations go here

}

Then in a service layer, let’s say a Spring service, you can access the BaseDao CRUD methods from any DAO which inherits it.

@Service
public class UserService {

     @Autowired
     private UserDao userDao;

     @Transactional
     public User saveUser(User user) {
          return userDao.store(user);
     }

}

Well, that’s all ! I hope you find it useful.

If you enjoyed this post follow me on twitter or leave a feedback !

Share

Getting the Best MySQL Performance in Your Products: Part 1, The Fundamentals

September 4th, 2010 negarnil No comments

Hi ! I found this must-to-read webcast which explains the basics of MySQL performance, it is quite new ! In my opinion anyone who aims to manage a database application should at least be aware of these topics !

If you use Hibernate to manage the database layer of your web applications you should never be satisfied with the default configuration it provides. Hibernate does provides caching strategies and other tuning features like c3p0 but you can go much further of that configurations to better optimize the database.

I recommend you to launch the webcast and follow it using the slides which you can download as a PDF. Apparently, the MySQL expert who speaks during the webcast had problems to change the slides just before starting explaining the next one, so for some moments it’s kind of messy.

Launch the webcast from here or click the image below.

You can also check this video from Google Talks which explains some other topics about performance tuning in MySQL.

Bye ! Keep around !

If you enjoyed this post follow me on twitter or leave a feedback !

Share

Multi-Tenant Data Architecture

February 8th, 2010 negarnil No comments

Hi, another great article taken from the MSDN Architecture Center. All about multitenancy, what is and how multitenant applications are build.

Trust, or the lack thereof, is the number one factor blocking the adoption of software as a service (SaaS). A case could be made that data is the most important asset of any business—data about products, customers, employees, suppliers, and more. And data, of course, is at the heart of SaaS. SaaS applications provide customers with centralized, network-based access to data with less overhead than is possible when using a locally-installed application. But in order to take advantage of the benefits of SaaS, an organization must surrender a level of control over its own data, trusting the SaaS vendor to keep it safe and away from prying eyes.

To earn this trust, one of the highest priorities for a prospective SaaS architect is creating a SaaS data architecture that is both robust and secure enough to satisfy tenants or clients who are concerned about surrendering control of vital business data to a third party, while also being efficient and cost-effective to administer and maintain.

Continue reading…

Share

Developing Aspects with Spring AOP

January 28th, 2010 negarnil 2 comments

Hi, I found this video which is an extract of a 4-day (and US$ 1600) of a Spring’s course. It covers the basics of AOP (Aspect Orientated Programming) and explains the Spring’s approach. It contains lots of code examples and screen records which also helps to better understand the Spring framework.

Taken from the Spring website:

In this highly practical SpringSource course Jeff Brown will teach you how to develop aspects with Spring AOP. This training gives you both theoretical as well as practical knowledge on Spring AOP.

In this training you will be provided with an:

  • - Introduction to AOP
  • - What problem does AOP solve
  • - The Spring AOP approach
  • - Defining pointcuts
  • - Implementing advice

File: s2university_aop2.mov (open with Quicktime, Itunes, etc…)
Size: 185 mb

Download

Share
Categories: JEE Development Tags: , ,