登陆代码的优化案例

原代码:

@Mapper // 声明该接口为Mapper接口
public interface EmployeeMapper {

    /**
     * 根据用户名查询员工
     * @param username 用户名
     * @return 员工对象
     */
    @Select("select * from employee where username = #{username}") // 使用SQL语句查询数据库中的员工记录
    Employee getByUsername(String username); // 根据用户名查询员工信息

}

问题:
1.  在接口方法中,SQL语句直接写在注解中,不利于维护和复用。
2.  没有对SQL语句进行参数校验和防止SQL注入的处理。
3.  缺少对查询结果的处理,可能返回的是null值。

优化方案:
1.  使用XML配置文件来管理SQL语句。
2.  对SQL参数进行校验和处理,使用预编译语句来防止SQL注入。
3.  对查询结果进行是否为空的判断,并进行相应的处理。

优化后的代码:

@Mapper
public  interface  EmployeeMapper  {

        /**
          *  根据用户名查询员工
          *  @param  username  用户名
          *  @return  员工对象
          */
        Employee  getByUsername(String  username);
        
}

EmployeeMapper.xml中的代码:

<?xml  version="1.0"  encoding="UTF-8"?>
<!DOCTYPE  mapper  PUBLIC  "-//mybatis.org//DTD  Mapper  3.0//EN"
                "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper  namespace="com.example.mapper.EmployeeMapper">

        <select  id="getByUsername"  resultType="com.example.model.Employee">
                <![CDATA[
                select  *  from  employee  where  username  =  #{username}
                ]]>
        </select>

</mapper>

猜你喜欢

转载自blog.csdn.net/m0_62600503/article/details/131882521