As I was working on the data access layer of my project, I noted that I have a lot of stuff to do to be able to access the Mapper from my web layer just for some simple CRUD actions.
Lot of stuff and even if I can detect some similarities, it’s not exactly the same, so I can’t just decide to put it in an interface or some abstract class, but lazy one day, lazy allways (it sounds better in french :D)…
After using my unique neurone to find solution, I finally arrive to a solution that I will present here.
To briefly describe my architecture, I have a web layer which access a service layer and then, the service layer can reach the data layer.
A requirement in my application is the user management (firstname, lastname, address, etc…), it’s what I will use to illustrate my solution.
First, I wanted to define a generic Dao to access my User object, to do that, the search all user is the simpler mechanism.
I need a simple POJO:
public class User { private Integer usrId; private String usrName; private String usrFname; [...] }
Now, the Dao, it will be responsible of accessing the MyBatis Mapper, and it will need to be able to manage all the Mapper, it’s why I defined a new interface which will contain the CRUD method:
public interface Mapper<T> { List<T> findAll(); int insert(T record); T selectByPrimaryKey(Integer id); void updateByPrimaryKey(T object); void deleteByPrimaryKey(Integer id); }
The MyBatis interface must now implement this interface specifying the User object:
public interface UserMapper extends Mapper<User>{ int insert(User record); List<User> findAll(); User selectByPrimaryKey(Integer userId); void updateByPrimaryKey(User user); void deleteByPrimaryKey(Integer usrId); }
The Mapper is fine, it can be used by my Dao, in first, I define its interface:
public interface Dao { public List findAll(); public T find(Integer id); public T merge(T obj); public void delete(T obj); }
And the implementation which references the generic mapper I want to use:
public class DaoImpl implements Dao{ protected Mapper mapper; public DaoImpl(Mapper mapper) { super(); this.mapper = mapper; } @Override public List findAll() { return mapper.findAll(); } [...]
there no problem to use the generic T because the real object is only known by the mapper “implementation”
And now the definition of my dao using Spring:
<bean id="userDao" class="net.classnotfound.dao.DaoImpl"> <constructor-arg index="0" ref= "userMapper"/> </bean> <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="net.classnotfound.mapper.UserMapper" /> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean>
As you can see, the Dao is User agnostic, the Mapper is responsible of accessing the right objet. Now, ma Dao can be used with any Mapper, just by changing the Spring configuration.
But when we speak about CRUD, it’s not only getting the full list of records from the database, we need to be able to insert, update and delete, for that, you often need to add some data as the creation date or update date.
Usually, using JPA/Hibernate, I used a @PreUpdate or @PrePersist, but they are part of the JPA specifications, I cannot use it.
It’s why I decided to create some new interface to be able to acces to this particular fields.
For that, I defined 4 new interfaces, I will just present 2 of them but you can imagine the others:
public interface Identifiable { Integer getId(); void setId(Integer id); }
public interface Updatable { void setUpdateDate(Date date); }
My user class must now implement these interfaces:
public class User implements Identifiable, Deletable, Updatable, Creatable
I can now add the update method in my DAO:
@Override public T merge(T obj) { if(!(obj instanceof Identifiable)) throw new IllegalArgumentException("The object is not instance of Identifiable and cannot be updated!"); Identifiable idable = (Identifiable)obj; if (idable.getId()==null) { if (!(obj instanceof Creatable)) throw new IllegalArgumentException("The object is not instance of Creatable and cannot be inserted!"); Creatable creatable = (Creatable) obj; creatable.setCreationDate(new Date()); mapper.insert(obj); } else { if (!(obj instanceof Updatable)) throw new IllegalArgumentException("The object is not instance of Updatable and cannot be updated!"); Updatable updtable = (Updatable) obj; updtable.setUpdateDate(new Date()); mapper.updateByPrimaryKey(obj); } return obj; }
I need to cast the T object to be able to access to the related method.
When it is done for all the CRUD method, I have to use it in my service layer, the problem remains as I want to avoid the duplication of code.
It means that my service must be also
public interface Service<t> { List<t> findAll(); T find(Integer id); T merge(T t); void delete(T t); void setDao(Dao<t> dao); Dao<t> getDao(); }
The service implementation looks like:
public class ServiceImpl<t> implements Service<t>{ private Dao<t> dao; @Override public List<t> findAll() { List<t> objects = dao.findAll(); return objects; } @Override @Transactional public T find(Integer id) { T user = dao.find(id); return user; } @Override @Transactional public T merge(T object) { dao.merge(object); return object; } [...] @Override public void setDao(Dao<t> dao) { this.dao = dao; } @Override public Dao<t> getDao() { return dao; }
And the service declaration, in the Spring configuration:
<bean id="userService" class="net.classnotfound.ServiceImpl"> <property name="dao" ref="userDao"/> </bean>
In the same way as the Dao, my service in now Dao agnostic, I can create different services just using the Spring configuration, I will now have the time drink a coffee instead of repeating the same code in several classes 🙂
Done!