mybits_基础
1.框架:一款半成品软件,我们可以基于框架继续开发,从而完成一些个性化的需求
2.ORM:对象关系映射,数据和实体对象的映射
3.MyBatis:是一个优秀的基于Java的持久层框架,它内部封装了JDBC
4.入门步骤:
导入jar包
编写映射配置文件
编写核心配置文件
使用相应的API来完成编码
5.映射配置文件:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="userMapper"> <select id="selectAll" resultType="org.example.Bean.userBean"> select *from user </select> <insert id="insert" parameterType="org.example.Bean.userBean"> insert into user values(#{username},#{password},#{leixing},#{ids}) </insert> </mapper>
6.核心文件配置
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "https://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> //事务管理 type属性,采用jdbc默认的事务 <transactionManager type="JDBC"></transactionManager> //数据源信息 type属性 连接池 <dataSource type="POOLED"> //获取数据库连接的配置信息 <property name="driver" value="com.mysql.jdbc.Driver"></property> <property name="username" value="root"/> <property name="password" value="123456"/> <property name="url" value="jdbc:mysql://localhost:3306/test"/> </dataSource> </environment> </environments> <mappers> //引入指定的映射配置文件 resource属性指定映射配置文件 <mapper resource="userMapper.xml"></mapper> </mappers> </configuration>
7.mybatis 接口代理方式实现Dao层
实现规则:
1.映射配置文件中的名称空间必须和Dao层接口的全类名相同
2.映射配置文件中的增删改查标签的id属性必须和Dao层接口的方法名相同
3.映射配置文件中的增删改查的parameterType属性必须和Dao层接口方法的参数相同
4.映射文件中的增删改查标签的resultType属性必须和Dao方法的返回值相同
获取动态代理对象:
SqlSession.getMapper方法获取
8.动态sql
查询中的where if标签(多条件查询)
<select id="selectCondition" resultType="org.example.Bean.userBean" parameterType="org.example.Bean.userBean"> select *from user <where> <if test="ids!=null"> ids=#{ids} </if> <if test="username!=null"> and username=#{username} </if> <if test="password!=null"> and password=#{password} </if> </where> </select>
查询中的where in标签(多个id查询)
</select> <select id="selectById" resultType="org.example.Bean.userBean" parameterType="list"> select *from user <where> <!-- collection 参数容器类型 open:开始 close:结束 item:参数变量名 separator:分隔符--> <foreach collection="list" open="ids in(" close=")" item="ids" separator=","> #{ids} </foreach> </where> </select>
sql:片段抽取
<sql id="select">select *from user</sql> <select id="selectAll" resultType="org.example.Bean.userBean"> <include refid="select"></include> </select>
将select *from user 这个语句抽取出来 id设为select为唯一标识
用<include>标签来调用
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署