【Mybatis03】mybatis实现CRUD的一些细节

1.Mybatis的中文文档地址:
http://www.mybatis.org/mybatis-3/zh/getting-started.html
2.添加日志记录操作
引入依赖

<dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

引入日志的配置文件:log4j.properties

# Global logging configuration
# developer-->DEBUG  productor-->INFO or ERROR
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

3.查询的时候:
selectList 查询多个对象,返回一个list集合(也能查询一个)
selectOne: 查询单个对象,返回一个对象

4.下面以删除来举例

<!--UserMapper删除操作-->
    <delete id="del" parameterType="java.lang.Integer">
        delete from user where id = #{id}
    </delete>

 	<!--测试类-->   
    @Test
    public void testDel(){
        //获取输入流对象
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("SqlMapConfig.xml");
        //获取SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //获取SqlSession对象
        //获取的sqlsession不能自动提交
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //执行sql语句
        sqlSession.delete("userMapper.del",3);
        //提交:只要修改了数据库必须提交
        sqlSession.commit();

        sqlSession.close();
    }

上面的delete from user where id = #{id}用到了模糊查询:

   4.1   	参数: %a% 
             		配置文件: username like #{username}
             	参数: a
             		配置文件1: username like "%"#{username}"%"
             		配置文件2: username like "%${value}%"
             							如果传的是简单类型必须使用value
             							如果是pojo,属性名引用
        4.2如果参数传入的是简单类型:(基本数据类型和String)
                         如果${ } 大括号内必须使用value引用
                         如果#{ } 大括号内随便写
        如果传入的参数是pojo类型:
                         用属性名引用
        如果传入的参数是包装对象类型:
                         用#{属性.属性名}
        如果传入的参数是Map集合:
                         用#{key}
        如果传入的参数是多个:
           				 用#{param1},#{param2},#{param3}......
    4.3${ }与#{ }的区别
  			${}:直接拼接,不会转换类型, 不能防注入
      		#{}:转换类型后拼接, 相当于占位符?,可以防注入

猜你喜欢

转载自blog.csdn.net/weixin_44212815/article/details/92859135