之前学习了mybatis,为了随时随地的补缺补漏,现在把笔记梳理了一下。
首先我们得先了解一下JDBC存在的问题: 1、重复代码太多,让开发效率降低(比较繁琐,有一些代码是没有必要的重复) 2、在JDBC中的SQL语句是写在Java源代码的,SQL语句不支持配置,SQL语句后期可能需要调优,需要重新修改Java代码
MyBatis的核心配置文件
项目目录: mybatis-config.xml文件: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/bjpower/mybatis/SqlMapper.xml"/> </mappers> </configuration> SqlMapper.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="321312"> <!-- 注意:由于在该程序中没有使用到namespace所以,namespace可以不写 1、在select标签的中的id具有唯一性,与Java程序中session.selectList("getAll")对应 2、resultType返回值类型是实例类的全限定名(即:包名+类名的方式) --> <select id="getAll" resultType="com.bjpower.entity.Student"> select *from student </select> </mapper> java测试代码: public static void main(String[] args) { /*mybatis-config.xml文件是存放在类路径 * Eclipse中的可以看到的src可以等同看作类路径 * */ String resource = "mybatis-config.xml"; InputStream inputStream=null; SqlSession session=null; try { inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); /*开启事务 * */ session = sqlSessionFactory.openSession(); List<Student> student=session.selectList("getAll"); for(Student s: student) { System.out.println("text:"+s.getName()+","+s.getBirth()); } /*没有出现异常提交事务 * */ session.commit(); } catch (IOException e) { /*遇到异常开始回滚 * */ if(session!=null) { session.rollback(); } e.printStackTrace(); }finally { /*关闭资源 * */ if(session!=null) { session.close(); } } }MyBatis外部引入连接数据库配置文件
项目目录: mybatis-config.xml文件: <configuration> <!--引入外部连接数据库信息--> <properties resource="db.properties"></properties> <environments default="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${mysql.dirver}"/> <property name="url" value="${mysql.url}"/> <property name="username" value="${mysql.username}"/> <property name="password" value="${mysql.password}"/> </dataSource> </environments> </configuration>注意:mybatis-config.xml文件中的配置标签要要严格按顺序来
MyBatis别名机制
方式一: <typeAliases> <typeAlias type="com.bjpower.entity.Student" alias="Student"/> </typeAliases> 方式二: <typeAliases> <package name="com.bjpower.entity"/> </typeAliases>使用Map集合来给SQL语句传值
Java代码: /**使用map给SQL语句传值 */ Map<String,String> studentMap=new HashMap<>(); studentMap.put("id","123"); studentMap.put("name","sz"); studentMap.put("birth","1999-10-1"); int count=session.insert("save",studentMap); System.out.println("影响数据的条数:"+count); 对应的Mapper: <!--注意的是:在insert标签内部的parameType的数据类型是Map,其中#{}中的数据是Map的key--> <inset id="save" parameterType="Map"> insert into student(id,name,birth) values(#{id},#{name},#{birth}) </insert>当JavaBean不够用的时候就要使用到Map给SQL语句传值,当查询数据库的时候如果出现跨表查询的时候会出现JavaBean不够用的时候所以就要使用Map给SQL语句传值
使用log4j组件打印MyBatis的SQL语句
目录结构: log4j.properties文件: # Global logging configuration log4j.rootLogger=DEBUG, stdout # 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 mybatis-config.xml文件: <settings> <setting name="logImpl" value="LOG4J"></setting> <setting name="autoMappingBehavior" value="FULL"></setting> </settings>注意:<settings>标签一定要在<properties>和<environment>
MyBatis动态SQL语句
Mybatis参数使用数组: /**处理多个servlet - */ @WebServlet(urlPatterns= {"/student/save.do","/student/del.do","saves.do"}) <delete id="doDel" parameterType="String"> delete from student where id in <!-- 由于传过来的参数是String[]所以在 collection中需要填array,open的是参数是起始标志 close的是结束标志,separator是起始标志和结束标志的分隔符 Item是数组遍历的每一项 --> <foreach collection="array" open="(" close=")" separator="," item="StudentID"> #{StudentID} </foreach> </delete> Mybatis参数使用list: <insert id="studentSaves" parameterType="Student"> insert into Student(id,name,birth) values <foreach collection="list" separator="," item="StudentInfo"> (#{StudentInfo.id},#{StudentInfo.name},#{StudentInfo.birth}) </foreach> </insert>Mybatis使用where和if来实现分页查询
<select id="getTotile" parameterType="Map" resultType="int"> select count(*) from student s <where> <if test="name!=null and name!=''"> and s.name like '%' #{name} '%' </if> <if test="birth!=null and birth!=''"> and s.birth = #{birth} </if> </where> </select> <!--Mybaties的SQL语句无法支持数学运算 --> <select id="getDataList" parameterType="Map" resultType="Student"> select s.* from student s <where> <!-- 注意的是:if标签中的test是map的key 由于原SQL语句为: select *from student where 条件1 and 条件2所以需要在if标签中 添加and --> <if test="name!=null and name!=''"> <!-- 在mybatis中的#{}两边需要有空格,不然mybatis无法识别占位符 --> and s.name like '%' #{name} '%' </if> <if test="birth!=null and birth!=''"> and s.birth = #{birth} </if> </where> order by birth desc limit #{pageNo} , #{pageSize} </select>后端服务对外提过的开发文档需要描述的信息: 1、接口地址: http://localhost:8080/MybatisWeb/student/savesPage.do 2、接口参数: name:查询的用户名信息 birth:查询用户的出生地址 pageno:每页展示的条数 pageSize:展示的总条数 3、返回的数据: { “dataList”: [{ “id”: "c32c5b0ccb6848d89505a90a61f7b224, “name”: “zhangsanneg”, “birth”: “2000-10-4” }], “totile”: 3 } { “dataList”: [{ “id”: "c32c5b0ccb6848d89505a90a61f7b224, “name”: “zhangsanneg”, “birth”: “2000-10-4” }], “totile”: 3 } { “id”: “123131”, “name”: “jtc”, “birth”: “1999-10-14” }
MyBatis中的#{}和${}的区别
#{}对应的JDBC中的:PreparedStatement,#{}占位符主要是用来完成SQL语句的传值操作 ${}对应JDBC中的:Statement,${}占位符主要是用来完成SQL语句的拼接的