I’m building a SpringMVC project for the first time and just wanted some feedback on my design.
At the moment I have the following UserDao
package org.myproj.com.dao;
import org.myproj.com.entity.User;
public interface UserDao {
public User getById(Long id);
}
This is implemented by the UserDaoImpl
package org.myproj.com.dao;
import org.myproj.com.entity.User;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository("userDao")
public class UserDaoImpl implements UserDao{
@Autowired
private SessionFactory sessionFactory;
public User getById(Long id) {
return (User) sessionFactory.getCurrentSession().get(User.class, id);
}
}
I then have a service layer, UserService
package org.myproj.com.service;
import org.myproj.com.entity.User;
public interface UserService {
public User getById(Long id);
}
With an impl, UserServiceImpl
package org.myproj.com.service;
import org.myproj.com.dao.UserDao;
import org.myproj.com.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
public UserServiceImpl() {
}
@Transactional
public User getById(Long id) {
return userDao.getById(id);
}
}
This is then accessed by my servlet with…
@Autowired
private UserService userService;
User user = userService.getById(1L);
I can’t help but feel that my Dao and my Service are replicating a lot. I’m considering using the service layer to add stuff like roles etc and the Dao do the business logic.
What do you think of this design? Is it acceptable?
IMHO it’s best to put the semantics of the business transactions into the service layer, and the data-side building blocks into the dao layer. The dao layer is then the data API used by the services. So, while the dao layer might have
UserDaowith afindByName(String username)method, the service layer wouldn’t. Instead, the service layer would have aSecurityServicewith aauthenticateUser(String username)and that would, among other things, calluserDao.findByName(username). And if you have aUserDetailServicewith aaddEmailAddressToUser(String username), well, that would call the same dao method.