具体的业务实现类
package com.yan.biz;
public class UserServImpl implements IUserServ{
}
业务工厂类
- 简化版的静态工厂方法模式
package com.yan.util;
import com.yan.biz.IUserServ;
import com.yan.biz.UserServImpl;
public class ServiceFactory {
public static IUserServ getUserService(){
return new UserServImpl();
}
}
5、尝试添加一个登录操作
在业务接口中添加登录方法声明
public interface IUserServ {
boolean login(UserBean user);
}
在业务实现类中添加方法的实现
public class UserServImpl implements IUserServ{
public boolean login(UserBean user) {
boolean res=false;
//业务数据验证
if(user==null || user.getUsername()==null || user.getPassword()==null)
throw new IllegalArgumentException("参数不合法!");
// TODO 调用DAO完成数据库的访问,不允许跨层访问
return res;
}
}
在DAO中新增按照用户名和口令的查询
- 参考JDBC编程中的动态SQL语句编程,传递的参数是一个UserBean,这个对象中的非空数据就是查询条件
public interface UserMapper {
List<UserBean> selectByExample(UserBean user);
}
MyBatis中针对动态SQL提供支持
<select id="selectByExample" parameterType="User" resultMap="userResultMapper">
select <include refid="columns"/> from t_users where 1=1
<if test="username!=null">
and username = #{username}
</if>
<if test="password!=null">
and password=#{password}
</if>
</select>
在MyBatis框架中UserMapper接口没有实现类,是由框架提供代理实现
针对动态SQL进行单元测试
添加依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
编写测试类
public class UserMapperTest {
private static SqlSessionFactory factory;
@BeforeClass
public static void bb() throws Exception{
Reader r= Resources.getResourceAsReader("mybatis-config.xml");
factory=new SqlSessionFactoryBuilder().build(r);
}
@AfterClass
public static void aa()throws Exception{
factory=null;
}
@Test
public void testSelectByExample(){
SqlSession session=factory.openSession();
UserMapper userMapper=session.getMapper(UserMapper.class);
UserBean user=new UserBean();
// user.setUsername("zhangsan");
// user.setPassword("123456");
List<UserBean> userList=userMapper.selectByExample(null);
userList.forEach(System.out::println);
session.close();
}
}
- 传递参数user时如果username或者password中一个属性非空,则出现一个查询条件
- 传递参数user时如果username和password都为空,则不会出现查询条件
- 如果参数为null,则不会出现查询条件
- 传递参数user时如果username或者password属性值为"",则出现查询条件,只是按照空字符串进行查询
本文介绍了一个简单的用户登录模块的设计与实现过程,包括业务接口定义、实现类编写、DAO层增改及MyBatis动态SQL应用,并通过单元测试验证功能正确性。
1645

被折叠的 条评论
为什么被折叠?



