结果集映射:

resultMap解决数据库字段名和属性名不一致的问题

id	name	pwd
id name password
column 是数据库的字段名 property 是实体类的属性名
<?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.kuang.dao.UserMapper">
<!--结果集映射 -->
<resultMap id="UserMap" type="User">
<result column="id" property="id"></result>
<result column="name" property="name"></result>
<result column="pwd" property="password"></result>
</resultMap>
<select id="getUserByID" resultMap="UserMap" parameterType="int">
select * from user WHERE id = #{id}
</select>
</mapper>

动态SQL

  1. 什么是动态SQL?

    根据不同的条件生成不同的SQL语句

官网描述:
MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其它类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句的痛苦。例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。
虽然在以前使用动态 SQL 并非一件易事,但正是 MyBatis 提供了可以被用在任意 SQL 映射语句中的强大的动态 SQL 语言得以改进这种情形。
动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。
-------------------------------
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
-------------------------------

MybatisUtils工具类

package com.kuang.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException;
import java.io.InputStream; public class MybatisUtils {
//从SqlSessionFactory中获得SqlSession的实例,SqlSession完全包含了SQL命令的执行方法
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
//SqlSessionFactoryBuilder去创建sqlSessionFactory 创建完就不再需要它了
//sqlSessionFactory 可以理解为数据库连接池
//sqlSessionFactory 创建 sqlSession
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//获取SqlSession连接
public static SqlSession getSession(){
return sqlSessionFactory.openSession();
}
}

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.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="000429"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--<mapper resource="com/kuang/dao/userMapper.xml"/>-->
<!--
使用映射器接口实现类的完全限定类名
需要配置文件名称和接口名称一致,并且位于同一目录下
-->
<!--<mapper class="com.kuang.dao.UserMapper"/>-->
<!--
将包内的映射器接口实现全部注册为映射器
但是需要配置文件名称和接口名称一致,并且位于同一目录下
-->
<package name="com.kuang.dao"/>
</mappers>
</configuration>

测试类

@Test
public void test(){
//sqlSession对象相当于是一个JDBC的PreparedStatement对象,这个对象可以执行sql语句
//我们现在做的事情就是:获取数据库连接,得到sqlSession对象,通过这个对象去实现我们定义的数据操作接口
//UserMapper,这个接口再通过解析我们定义的userMapper.xml文件去执行带有SQL语句的特定方法。
SqlSession sqlSession = MybatisUtils.getSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//根据ID取
User user=mapper.getUserByID(2);
System.out.println(user);
sqlSession.close();
//更新一条数据 id为1
// updateUser();
//删除一个用户
// deleteUser();
}

目录结构

db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8
username=root
password=000429

在mybatis-config.xml中

<!--导入properties文件-->
<properties resource="db.properties"/>

log4j.properties

#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file
#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/kuang.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

在mybatis-config.xml中

<!--日志-->
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>

多对一

<?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.StudentMapper">
<select id="getStudent" resultMap="studentTeacher">
select * from mybatis.student
</select>
<resultMap id="studentTeacher" type="student">
<result property="id" column="id"></result>
<result property="name" column="name"></result>
<!--
对象用association 多对一
集合用collection 一对多
-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id=#{id};
</select>
<!--
按照结果嵌套处理
-->
<select id="getStudent2" resultMap="StudentTeacher2" >
select s.id sid, s.name sname , t.name tname
from student s,teacher t
where s.tid = t.id
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<!--关联对象property 关联对象在Student实体类中的属性-->
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
</mapper>

一对多

<?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.kuang.dao.TeacherMapper">
<select id="getTeacher1" resultType="Teacher">
select * from mybatis.teacher
</select>
<!--
思路:
1. 从学生表和老师表中查出学生id,学生姓名,老师姓名
2. 对查询出来的操作做结果集映射
1. 集合的话,使用collection!
JavaType和ofType都是用来指定对象类型的
JavaType是用来指定pojo中属性的类型
ofType指定的是映射到list集合属性中pojo的类型。
-->
<select id="getTeacher2" resultMap="TeacherStudent">
select s.id sid, s.name sname , t.name tname, t.id tid
from student s,teacher t
where s.tid = t.id and t.id=#{id}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"></result>
<result property="name" column="tname"/>
<collection property="students" ofType="Student">
<result property="id" column="sid" />
<result property="name" column="sname" />
<result property="tid" column="tid" />
</collection>
</resultMap>
</mapper>

标准mapper.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.kuang.mapper.BlogMapper"> </mapper>

标准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> </configuration>

mybatis学习笔记(可复用的相关配置信息)的更多相关文章

  1. mybatis学习笔记(三)-- 优化数据库连接配置

    原来直接把数据库连接配置信息写在conf.xml配置中,如下 <?xml version="1.0" encoding="UTF-8"?> < ...

  2. ElasticSearch学习笔记--2、ES相关配置

    1.配置文件 ES的配置文件位置:config/elasticsearch.yml可以直接搜索elasticsearch.yml 2.配置远程api访问 network.host: 192.168.1 ...

  3. Struts2学习笔记(1)---相关配置

    Struts 2是Struts的下一代产品,是在 struts 1和WebWork的技术基础上进行了合并的全新的Struts 2框架. 1创建action对象(三种) 1 创建普通的类,不继承任何类, ...

  4. Mybatis学习笔记(二) 之实现数据库的增删改查

    开发环境搭建 mybatis 的开发环境搭建,选择: eclipse j2ee 版本,mysql 5.1 ,jdk 1.7,mybatis3.2.0.jar包.这些软件工具均可以到各自的官方网站上下载 ...

  5. mybatis学习笔记(五):mybatis 逆向工程

    mybatis学习笔记(五):mybatis 逆向工程 在日常开发中,如果数据库中存在多张表,自己手动创建 多个pojo 类和编写 SQL 语法配置文件,未免太过繁琐,mybatis 也提供了一键式生 ...

  6. mybatis 学习笔记(一):mybatis 初认识

    mybatis 学习笔记(一):mybatis 初认识 简介 MyBatis是一个Java持久层框架,它通过XML描述符或注解把对象与存储过程或SQL语句关联起来.mybatis 可以将 prepar ...

  7. Mybatis学习笔记导航

    Mybatis小白快速入门 简介 本人是一个Java学习者,最近才开始在博客园上分享自己的学习经验,同时帮助那些想要学习的uu们,相关学习视频在小破站的狂神说,狂神真的是我学习到现在觉得最GAN的老师 ...

  8. 【MyBatis学习笔记】

    [MyBatis学习笔记]系列之预备篇一:ant的下载与安装 [MyBatis学习笔记]系列之预备篇二:ant入门示例 [MyBatis学习笔记]系列之一:MyBatis入门示例 [MyBatis学习 ...

  9. MyBatis:学习笔记(1)——基础知识

    MyBatis:学习笔记(1)--基础知识 引入MyBatis JDBC编程的问题及解决设想 ☐ 数据库连接使用时创建,不使用时就释放,频繁开启和关闭,造成数据库资源浪费,影响数据库性能. ☐ 使用数 ...

  10. mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

    文章介绍结构一览 一.使用maven创建web项目 1.新建maven项目 2.修改jre版本 3.修改Project Facts,生成WebContent文件夾 4.将WebContent下的两个文 ...

随机推荐

  1. Spring rce CVE-2022-22965

    原理大致是这样:spring框架在传参的时候会与对应实体类自动参数绑定,通过"."还可以访问对应实体类的引用类型变量.使用getClass方法,通过反射机制最终获取tomcat的日 ...

  2. win32 - 使用Safer API创建受限的令牌

    #include <Windows.h> #include <WinSafer.h> #include <stdio.h> #include <sddl.h& ...

  3. 程序员应具备的PS基本技能(一):PS2017基本框架使用

    若该文为原创文章,未经允许不得转载原博主博客地址:https://blog.csdn.net/qq21497936原博主博客导航:https://blog.csdn.net/qq21497936/ar ...

  4. C C++指针面试题零碎整理

    最基础的指针如下: int a; int* p = &a; 答:p指向a的地址,&是取a的地址.*指的是指针中取内容的符号. 2.str[]和str*的区别: char str1[] ...

  5. 【Azure 服务总线】查看Service Bus中消息多次发送的日志信息,消息是否被重复消费

    问题描述 使用Service Bus,发现消息被重复消费.如果要查看某一条消息的具体消费情况,需要那些消息的属性呢? 问题解答 使用Azure Service Bus,当消费发送到服务端后,就会生产相 ...

  6. NebulaGraph is nothing without you | 社区 2023 年度人物合集

    在去年的年度人物 回顾中,我们看到了形形色色的人们,他们当中有帮 NebulaGraph 捉 bug 的小能手,也有通过用回复来解答他人疑惑的启蒙者-在今年(2023 年),我们这个整点不一样的,将镜 ...

  7. .net中最简单的http请求调用(比如调用chatgpt的openAI接口)

    支持.Net Core(2.0及以上)/.Net Framework(4.5及以上),可以部署在Docker, Windows, Linux, Mac. http请求调用是开发中经常会用到的功能,因为 ...

  8. 文心一言 VS 讯飞星火 VS chatgpt (210)-- 算法导论16.1 1题

    一.根据递归式(16.2)为活动选择问题设计一个动态规划算法.算法应该按前文定义计算最大兼容活动集的大小 c[i,j]并生成最大集本身.假定输入的活动已按公式(16.1)排好序.比较你的算法和GREE ...

  9. 协议I2C

    SCL   SDA   同步,半双工 开漏+弱上拉,谁用这跟线,就下拉成低电平 想输出,去拉杆子或放手,操作杆子变化 想输入,直接放手,看电平高低就行 线与,一个低电平,全部低电平,可以利用这个执行多 ...

  10. vscode 自动格式化 好使的配置 setting.json 20210622

    一直用idea,今天有个需求得用vscode,发现格式化不好使了 用 vetur 格式化 结果带分行什么的,eslint 过去不了,更新了个好使的配置,记录一下. { "update.mod ...