分析:
这是一个典型的应用服务,涉及到业务层(Business Objects Layer)、数据库访问层(DB Access)和存储层(EIS)。
采用典型的架构:BO+DAO
DAO采用Spring提供的JdbcTemplate来进行封装。
二,具体实现
1)用户类User
public class User{
private String username;
private String email;
private Date birthday;
public User(){}
…
相应的setter/getter方法。
}
这是一个简单的bean类,记录用户的信息。
2)数据库访问类:UserDao
public interface UserDao {
public void save(User user);
public void remove(String username);
public User searchByName(String username);
}
这是数据库访问的接口类,定义了对用户的数据库操作,其实现类是UserDaoJdbc
UserDaoJdbc类
public class UserDaoJdbc extends JdbcDaoSupport implements UserDao {
public UserDaoJdbc() {
super();
}
public void save(User user) {
getJdbcTemplate().update(
"insert into SAMPLE_USER values (?,?,?)",
new Object[] { user.getUsername(), user.getEmail(),
user.getBirthday() });
}
...
}
3)业务类UserManageService
public interface UserManageService {
public void saveUser(User user);
public void removeUser(String username);
public User getUserByName(String username);
}
这是用户的业务类接口,定义了和用户相关的一些业务操作,其实现类UserManageServiceImpl
实现类UserManageServiceImpl
public class UserManageServiceImpl implements UserManageService {
private UserDao udao;
public UserManageServiceImpl() {
super();
}
public void saveUser(User user) {
udao.save(user);
}
public UserDao getUdao() {
return udao;
}
public void setUdao(UserDao udao) {
this.udao = udao;
}
}
4)Spring bean描述文件配置
5)数据中存储用户的表SAMPLE_USER
username varchar2(30) not null,
email varchar2(50) not null,
birthday date
6)通过单元测试来验证UserManageService中的操作:
public class UserManageServiceTest extends TestCase {
private UserManageService service;
private static Log logger = LogFactory.getLog(UserManageServiceTest.class);
protected void setUp() throws Exception {
super.setUp();
service = (UserManageService) SpringContextUtil
.getBean("userManageService");
}
public void testSaveAndSearchAndRemoveUser() throws Exception {
User user = new User();
user.setUsername("zhangsan");
user.setEmail("[email protected]");
user.setBirthday(new Date());
service.saveUser(user);
logger.debug("存入一个新用户:" + user);
User userFromDb = service.getUserByName("zhangsan");
assertNotNull(userFromDb);
assertEquals(userFromDb.getEmail(), "[email protected]");
logger.debug("从数据库中查到用户:" + userFromDb);
service.removeUser("zhangsan");
logger.debug("从数据库删除用户:" + userFromDb);
}
protected void tearDown() throws Exception {
super.tearDown();
}
}