简介 什么是 MyBatis?
MyBatis 是一款优秀的==持久层框架==,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
准备工作
<dependencies > <dependency > <groupId > org.mybatis</groupId > <artifactId > mybatis</artifactId > <version > 3.5.13</version > </dependency > <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > <version > 8.0.33</version > </dependency > <dependency > <groupId > com.microsoft.sqlserver</groupId > <artifactId > mssql-jdbc</artifactId > <version > 12.2.0.jre8</version > </dependency > <dependency > <groupId > org.junit.jupiter</groupId > <artifactId > junit-jupiter</artifactId > <version > 5.9.3</version > </dependency > </dependencies >
核心配置文件
配置标签顺序(核心配置文件中的==标签顺序必须符合下面顺序==)
核心配置文件mybatis-config.xml
示例
<?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 > <properties resource ="db.properties" /> <settings > <setting name ="logImpl" value ="STDOUT_LOGGING" /> </settings > <typeAliases > <package name ="com.clb.pojo" /> </typeAliases > <environments default ="sqlserver" > <environment id ="mysql" > <transactionManager type ="JDBC" /> <dataSource type ="POOLED" > <property name ="driver" value ="${mysql.driver}" /> <property name ="url" value ="${mysql.url}" /> <property name ="username" value ="${mysql.username}" /> <property name ="password" value ="${mysql.password}" /> </dataSource > </environment > <environment id ="sqlserver" > <transactionManager type ="JDBC" /> <dataSource type ="POOLED" > <property name ="driver" value ="${ms.driver}" /> <property name ="url" value ="${ms.url}" /> <property name ="username" value ="${ms.username}" /> <property name ="password" value ="${ms.password}" /> </dataSource > </environment > </environments > <mappers > <mapper resource ="com/clb/dao/EmpMapper.xml" /> </mappers > </configuration >
数据源配置文件示例
mysql.driver =com.mysql.cj.jdbc.Driver mysql.url =jdbc:mysql://localhost:3306/clb mysql.username =root mysql.password =123456 ms.driver =com.microsoft.sqlserver.jdbc.SQLServerDriver ms.url =jdbc:sqlserver://192.168.0.88:1433;trustServerCertificate=true ms.username =sa ms.password =123456
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.clb.dao.UserMapper" > <resultMap id ="UserMap" type ="user" > <result column ="pwd" property ="password" /> </resultMap > <select id ="getUserList" resultType ="com.clb.pojo.User" > select * from mybatis.user </select > <select id ="selectById" resultType ="com.clb.pojo.User" parameterType ="int" > select * from user where id = #{id} </select > <select id ="getUserLike" resultType ="com.clb.pojo.User" > select * from user where name like concat('', #{name}, ''); </select > <insert id ="addUser" parameterType ="com.clb.pojo.User" > insert into user(id, name, pwd) value (#{id}, #{name}, #{pwd}) </insert > </mapper >
MybatisUtils
要使用mybatis执行sql语句,要使用SqlSession
对象,可以直接在测试类中获取
@Test public void test () throws IOException { String resource = "mybatis-config.xml" ; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder ().build(inputStream); try (SqlSession session = sqlSessionFactory.openSession()) { EmpMapper mapper = session.getMapper(EmpMapper.class); List<Emp> emps = mapper.selectBySalary(5000 ); emps.forEach(System.out::println); } }
但是每次使用都要写这一串代码,有点麻烦 ,前面获取SqlSession对象的代码是固定代码,将这段固定代码提取到工具类MybatisUtils
,使用工具类的静态方法获取SqlSession对象
MybatisUtils工具类示例
public class MybatisUtils { private MybatisUtils () {} private static final SqlSessionFactory sqlSessionFactory; static { try { String resource = "mybatis-config.xml" ; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder ().build(inputStream); } catch (IOException e) { throw new RuntimeException (e); } } public static SqlSession getSqlSession () { return sqlSessionFactory.openSession(); } }
@Test public void testMybatisUtils () { SqlSession sqlSession = MybatisUtils.getSqlSession(); EmpMapper mapper = sqlSession.getMapper(EmpMapper.class); List<Emp> emps = mapper.selectBySalary(1000 ); emps.forEach(System.out::println); sqlSession.close(); }
注解开发
使用注解直接写sql语句代替xml映射文件
public interface UserMapper { @Select("select id, name, pwd password from user") List<User> selectAll () ; @Select("select id, name, pwd password " + "from user " + "where id = #{id} and name=#{name} and pwd=#{password}") User selectById (@Param("id") int i, @Param("name") String n, @Param("password") String p) ; @Insert("insert into user(id, name, pwd) VALUE (#{id},#{name},#{password})") int addUser (User user) ; @Update("update user set name=#{name},pwd=#{password} where id=#{id}") int updateUser (User user) ; @Delete("delete from user where id = #{id}") int deleteUserById (@Param("id") int id) ; }
使用@Result
注解可以定义结果映射,使用@ResultMap
可以引用xml文件中定义的ResultMap结果映射
@Select("select * from emp where first_name = #{name};") @Results({ @Result(column = "first_name", property = "firstName") }) Emp getByFirstNameEmp (String name) ;
@Select("select * from emp where first_name = #{name};") @ResultMap("EmpMap") Emp getByFirstNameEmp (String name) ;
总结:简单的sql语句使用注解比配置文件来的更方便且更快,但是复杂的sql语句使用注解反而不方便或难以实现,所以==简单的sql使用注解,复杂的使用xml,搭配使用==
==动态查询==
<select id ="pageQuery" resultType ="com.sky.entity.Category" > select * from category <where > <if test ="name != null and name != ''" > and name like concat('%',#{name},'%') </if > <if test ="type != null" > and type = #{type} </if > </where > order by sort asc , create_time desc</select >
==动态更新==
<update id ="update" parameterType ="Category" > update category <set > <if test ="type != null" > type = #{type}, </if > <if test ="name != null" > name = #{name}, </if > <if test ="sort != null" > sort = #{sort}, </if > <if test ="status != null" > status = #{status}, </if > <if test ="updateTime != null" > update_time = #{updateTime}, </if > <if test ="updateUser != null" > update_user = #{updateUser} </if > </set > where id = #{id}</update >
==批量插入,传入参数是一个集合类型,删除同理==
<insert id ="insertBatch" > insert into dish_flavor (dish_id, name, value)values <foreach collection ="flavors" item ="f" separator ="," > (#{f.dishId},#{f.name},#{f.value}) </foreach > </insert >
更多动态SQL用法见官网
接下来,了解进阶框架==mybatis-plus==