Mybatis学习资料
环境:
-
JDK 1.8
-
Mysql 5.7
-
Maven 3.6.1
-
IDEA
技术栈:
-
JDBC
-
Mysql
-
Java基础
-
Maven
-
Junit
简介
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
mybatis依赖:
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.16</version> </dependency>
mybatis的优点:
-
简化了JDBC的代码。
-
sql与代码分离,提高了可维护性
-
提供xml标签,支持动态编写sql
-
提供关系映射标签,支持对象关系组件维护
mybatis中文网:MyBatis中文网
maven仓库:https://mvnrepository.com
第一个Mybatis程序
思路:搭建环境==》导入Mybatis依赖==》编写代码==》测试
搭建环境
数据库
CREATE TABLE `channel` ( `ChannelNo` int(2) NOT NULL COMMENT '经络编号', `ChannelName` varchar(10) NOT NULL COMMENT '经络名称', `ChannelLyric` varchar(255) NOT NULL COMMENT '经络歌诀', PRIMARY KEY (`ChannelNo`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8
新建项目
-
新建一个普通的maven项目(MybatisStudy)
-
删除src目录(作为父工程)
-
导入依赖:
<!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.16</version> </dependency> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> </dependency>
创建一个module(mybatis01)
-
编写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.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/traditionaldoctor?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="org/mybatis/example/BlogMapper.xml"/> </mappers> </configuration>
-
编写bybatis工具类
package com.aug.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; //SqlSessionFactory ==> SqlSession public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { //使用Mybatis第一步:获取SqlSessionFactory对象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
编写代码
-
pojo
//实体类 public class Channel { private int ChannelNo; private String ChannelName; private String ChannelLyric; public Channel() { } public Channel(int channelNo, String channelName, String channelLyric) { ChannelNo = channelNo; ChannelName = channelName; ChannelLyric = channelLyric; } public int getChannelNo() { return ChannelNo; } public void setChannelNo(int channelNo) { ChannelNo = channelNo; } public String getChannelName() { return ChannelName; } public void setChannelName(String channelName) { ChannelName = channelName; } public String getChannelLyric() { return ChannelLyric; } public void setChannelLyric(String channelLyric) { ChannelLyric = channelLyric; } }
-
dao
public interface ChannelDao { public List<Channel> getChannelList(); }
-
接口实现类
<?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.aug.dao.ChannelDao"> <select id="getChannelList" resultType="com.aug.pojo.Channel"> select * from channel </select> </mapper>
测试
public class ChannelDaoTest { @Test public void test(){ //获取sqlsession对象 SqlSession sqlSession = MybatisUtils.getSqlSession(); //执行sql(方式一) ChannelDao channelDao = sqlSession.getMapper(ChannelDao.class); List<Channel> channelList = channelDao.getChannelList(); for (Channel channel : channelList) { System.out.println(channel.getChannelNo()+"~"+channel.getChannelName()); } //关闭sqlsession sqlSession.close(); } }
问题总结:
//问题1.Mapper.xml未在Mybatis核心配置文件(mybatis-config.xml)中注册 //报错信息 org.apache.ibatis.binding.BindingException: Type interface com.aug.dao.ChannelDao is not known to the MapperRegistry. //解决方法: <!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册!--> <mappers> <mapper resource="com/aug/dao/ChannelMapper.xml"/> </mappers> ======================================================================= //问题2:资源过滤问题 //报错信息 java.lang.ExceptionInInitializerError Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com.aug.dao.ChannelDao //解决方法:在pom.xml中添加资源过滤 <!-- 资源过滤设置 --> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
增删改查
//查询所有经络信息 public List<Channel> getChannelList(); //根据id查询经络信息 public List<Channel> getChannelById(int ChannelNo); //根据Name模糊查询 public List<Channel> getChannelByName(String ChannelName); //新增 public int insertChannel(Channel channel); //修改 public int updateChannel(Channel channel); public int updateChannel2(HashMap<String,Object> hashMap); //删除 public int deleteChannel(int ChannelNo);
<!--查询所有--> <select id="getChannelList" resultType="com.aug.pojo.Channel"> select * from channel </select> <!--根据编号查询--> <select id="getChannelById" parameterType="int" resultType="com.aug.pojo.Channel"> select * from channel where channelNo = #{channelNo} </select> <!--根据名称模糊查询--> <select id="getChannelByName" parameterType="String" resultType="com.aug.pojo.Channel"> select * from channel where channelName like "%"#{channelName}"%" </select> <!--新增--> <insert id="insertChannel" parameterType="com.aug.pojo.Channel"> insert into channel (channelNo,channelName,channelLyric) values (#{channelNo},#{channelName},#{channelLyric}); </insert> <!--根据编号修改--> <update id="updateChannel" parameterType="com.aug.pojo.Channel"> update channel set channelName = #{channelName} where channelNo = #{channelNo} </update> <update id="updateChannel2" parameterType="map"> update channel set channelName = #{channelName} where channelNo = #{channelNo} </update> <!--根据编号删除--> <delete id="deleteChannel" parameterType="int"> delete from channel where channelNo = #{channelNo} </delete>
注:增删改需要提交事务
配置解析
-
核心配置文件
-
mybatis-config.xml
-
Mybatis的配置文件包含了会深深影响Mybatis行为的设置和属性信息
configuration(配置) properties(属性) settings(设置) typeAliases(类型别名) typeHandlers(类型处理器) objectFactory(对象工厂) plugins(插件) environments(环境配置) environment(环境变量) transactionManager(事务管理器) dataSource(数据源) databaseIdProvider(数据库厂商标识) mappers(映射器)
-
-
环境配置
-
Mybatis可以配置成适应多种环境,但每个SqlSessionFactory实例只能选择一种环境
-
Mybatis默认的事务管理器是JDBC, 连接池:POOLED
-
-
属性
db.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/traditionaldoctor?useSSL=true&useUnicode=true&characterEncoding=UTF-8 username=root password=123456
在核心配置文件中引入外部配置文件
<!--引入外部配置文件--> <properties resource="db.properties"> <!--优先使用外部配置文件db.properties--> <property name="driver" value="jdbc:mysql://localhost:3306"/> <property name="url" value="jdbc:mysql://localhost:3306/traditionaldoctor?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </properties>
-
可以直接引入外部配置文件
-
可以增加一些属性配置
-
如果两个文件有同一个字段,优先使用外部配置文件