本文最后更新于 2024年11月7日 下午
一、配置文件(标签): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 <?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 > <typeAliases > <typeAlias type ="com.entity.News" alias ="News" /> <typeAlias type ="com.entity.Goods" alias ="goods" /> </typeAliases > <environments default ="development" > <environment id ="development" > <transactionManager type ="JDBC" /> <dataSource type ="POOLED" > <property name ="url" value ="jdbc:mysql://127.0.0.1/shop?characterEncoding=utf-8& allowMultiQueries=true" /> <property name ="username" value ="root" /> <property name ="password" value ="2936283" /> <property name ="driver" value ="com.mysql.jdbc.Driver" /> </dataSource > </environment > </environments > <mappers > <mapper resource ="com/mapper/News-mapper.xml" /> <mapper resource ="com/mapper/Goods-mapper.xml" /> </mappers > </configuration >
二、原理图:
SqlMapConfig.xml->MybatisConfig.xml->(应用程序->)configuration->SqlSessionFactory-> SqlSession(->MappedStatement开启注解)->Transaction->正常提交异常回滚
三、功能架构:
接口层:数据增删改查(4点)的接口、获取配置接口 数据处理层: (参数映射)参数映射配置、参数映射解析、参数类型解析 (SQL解析)SQL解析、SQL获取、动态SQL (SQL执行)SimpleExecutor、BatchExecutor、ReuseExcutor (结果映射)结果映射配置、结果类型转换、结果数据拷贝 基础支撑层:连接管理、事务管理、配置加载、缓存处理 配置框架
四、ORM: Mybatis是一种数据持久层(ORM)框架,在实体类跟SQL语句之间建立了映射关系,是半自动化的ORM实现。
五、映射文件(标签): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <?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.etc.dao.GoodsDao" > <resultMap type ="goods" id ="GoodsResult" > <id column ="gid" property ="gid" /> <result column ="gname" property ="gname" /> <result column ="type" property ="type" /> <result column ="price" property ="price" /> <result column ="date" property ="date" /> </resultMap > <select id ="findByDate" resultMap ="GoodsResult" parameterType ="java.lang.String" > select * from goods where date > #{date}</select > <insert id ="insert" parameterType ="goods" > insert into goods (gname,type,price,date) values(#{gname},#{type},#{price},#{date})</insert > </mapper >
六、Mybatis优缺点: 优点: 1,轻量化,小,容易上手 2,灵活,不会对源代码有任何影响,把sql语句统一写在xml文件里方便管理优化 3,解除SQL语句与业务代码的耦合,SQL语句只负责处理数据,业务代码只负责自己的业务逻辑
缺点: 1,编写SQL语句时工作量大,尤其是字段多、关联表多时 2,SQL语句依赖于数据库,导致数据库移植性差 3,框架比较简陋,功能不全面
七、#$取值方式: #{}取值是把它变成?,然后调用PreparedStatement的set方法来赋值 ${}取值是直接把${}替换成变量的值 因而#{}可以更有效地防止SQL注入,有效提高系统安全性