MyBatis快速上手与知识点总结()

  本篇文章为你整理了MyBatis快速上手与知识点总结()的详细内容,包含有 MyBatis快速上手与知识点总结,希望能帮助你了解 MyBatis快速上手与知识点总结。

  INSERT INTO tb_user VALUES (1, zhangsan, 123, 男, 北京);

  INSERT INTO tb_user VALUES (2, 李四, 234, 女, 天津);

  INSERT INTO tb_user VALUES (3, 王五, 11, 男, 西安);

  

 

 

  
在pom.xml中配置文件中添加依赖的坐标

  注意:需要在项目的resources目录下创建logback的配置文件

  

 dependencies 

 

   !--mybatis 依赖--

   dependency

   groupId org.mybatis /groupId

   artifactId mybatis /artifactId

   version 3.5.5 /version

   /dependency

   !--mysql 驱动--

   dependency

   groupId mysql /groupId

   artifactId mysql-connector-java /artifactId

   version 5.1.46 /version

   /dependency

   !--junit 单元测试--

   dependency

   groupId junit /groupId

   artifactId junit /artifactId

   version 4.13 /version

   scope test /scope

   /dependency

   !-- 添加slf4j日志api --

   dependency

   groupId org.slf4j /groupId

   artifactId slf4j-api /artifactId

   version 1.7.20 /version

   /dependency

   !-- 添加logback-classic依赖 --

   dependency

   groupId ch.qos.logback /groupId

   artifactId logback-classic /artifactId

   version 1.2.3 /version

   /dependency

   !-- 添加logback-core依赖 --

   dependency

   groupId ch.qos.logback /groupId

   artifactId logback-core /artifactId

   version 1.2.3 /version

   /dependency

   /dependencies

  

 

  
核心文件用于替换信息,解决硬编码问题

  在模块下的resources目录下创建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"

   !-- 采用JDBC的事务管理方式 --

   transactionManager type="JDBC"/

   !-- 数据库连接信息 --

   dataSource type="POOLED"

   property name="driver" value="com.mysql.jdbc.Driver"/

   property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/

   property name="username" value="root"/

   property name="password" value="123456"/

   /dataSource

   /environment

   /environments

   !-- 加载SQL映射文件 --

   mappers

   mapper resource="UserMapper.xml"/

   /mappers

   /configuration

  

 

  
SQL映射文件用于统一管理SQL语句,解决硬编码问题

  在模块的resources目录下创建映射配置文件UserMaooer.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"

   namespace:命名空间

   mapper namespace="test"

   !-- statement --

   select id="selectAll" resultType="priv.dandelion.entity.User"

   select * from tb_user;

   /select

   /mapper

  

 

  
public User(Integer id, String username, String password, String gender, String address) {

   this.id = id;

   this.username = username;

   this.password = password;

   this.gender = gender;

   this.address = address;

   public Integer getId() {

   return id;

   public void setId(Integer id) {

   this.id = id;

   public String getUsername() {

   return username;

   public void setUsername(String username) {

   this.username = username;

   public String getPassword() {

   return password;

   public void setPassword(String password) {

   this.password = password;

   public String getGender() {

   return gender;

   public void setGender(String gender) {

   this.gender = gender;

   public String getAddress() {

   return address;

   public void setAddress(String address) {

   this.address = address;

   @Override

   public String toString() {

   return "User{" +

   "id=" + id +

   ", username=" + username + \ +

   ", password=" + password + \ +

   ", gender=" + gender + \ +

   ", address=" + address + \ +

   };

  

 

 

  


public static void main(String[] args) throws IOException {

 

   // 加载mybatis的核心配置文件,获取SqlSessionFactory

   String resource = "mybatis-config.xml";

   InputStream inputStream = Resources.getResourceAsStream(resource);

   SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

   // 获取Session对象,执行SQL语句

   SqlSession sqlSession = sqlSessionFactory.openSession();

   // 执行SQL,处理结果

   List User users = sqlSession.selectList("test.selectAll");

   System.out.println(users);

   // 释放资源

   sqlSession.close();

  

 

  
解决形如上述测试类中List User users = sqlSession.selectList("test.selectAll");的硬编码问题

  
定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下

  maven项目开发时要求code和resources分开,可在resources中创建相同包文件来是实现上述效果

  
在Mapper接口中定义方法,方法名就是SQL映射文件中SQL语句的id,并且参数类型和返回值类型一致

  
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

   "http://mybatis.org/dtd/mybatis-3-mapper.dtd"

   namespace:命名空间

   mapper namespace="priv.dandelion.mapper.UserMapper"

   select id="selectAll" resultType="priv.dandelion.entity.User"

   select * from tb_user;

   /select

   /mapper

  

 

 

  


public static void main(String[] args) throws IOException {

 

   // 加载mybatis的核心配置文件,获取SqlSessionFactory

   String resource = "mybatis-config.xml";

   InputStream inputStream = Resources.getResourceAsStream(resource);

   SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

   // 获取Session对象,执行SQL语句

   SqlSession sqlSession = sqlSessionFactory.openSession();

   // 执行SQL,处理结果

   // 获取UserMapper接口的代理对象

   UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

   List User users = userMapper.selectAll();

   System.out.println(users);

   // 释放资源

   sqlSession.close();

  

 

  
如果Mapper接口名称和SQL映射文件名称相同,并在同一目录下,则可以使用包扫描的方式简化SQL映射文件的加载,简化mybatis核心配置文件

  

 mappers 

 

   !--加载sql映射文件--

   !-- mapper resource="priv/dandelion/mapper/UserMapper.xml"/ --

   !--Mapper代理方式--

   package name="priv.dandelion.mapper"/

   /mappers

  

 

  
在核心配置文件的 environments 标签中其实是可以配置多个 environment ,使用 id 给每段环境起名,在 environments 中使用 default=环境id 来指定使用哪儿段配置。我们一般就配置一个 environment 即可

  

 ?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

   package name="priv.dandelion.entity"/

   /typeAliases

   environments default="development"

   environment id="development"

   !-- 采用JDBC的事务管理方式 --

   transactionManager type="JDBC"/

   !-- 数据库连接信息 --

   dataSource type="POOLED"

   property name="driver" value="com.mysql.jdbc.Driver"/

   !-- JDBC连接数据库,SSL,Unicode字符集,UTF-8编码 --

   property name="url" value="jdbc:mysql:///mybatis?useSSL=false amp;useUnicode=true amp;characterEncoding=UTF-8"/

   property name="username" value="root"/

   property name="password" value="123456"/

   /dataSource

   /environment

   environment id="test"

   transactionManager type="JDBC"/

   !-- 数据库连接信息 --

   dataSource type="POOLED"

   property name="driver" value="com.mysql.jdbc.Driver"/

   property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/

   property name="username" value="root"/

   property name="password" value="123456"/

   /dataSource

   /environment

   /environments

   !-- 加载SQL映射文件 --

   mappers

   !-- mapper resource="priv/dandelion/mapper/UserMapper.xml"/ --

   package name="priv.dandelion.mapper"/

   /mappers

   /configuration

  

 

  4.2 类型别名

  映射配置文件中的resultType属性需要配置数据封装的类型(类的全限定名),繁琐

  Mybatis 提供了 类型别名(typeAliases) 可以简化这部分的书写

  

 configuration 

 

   !-- name属性未实体类所在的包 --

   typeAliases

   package name="priv.dandelion.entity"/

   /typeAliases

   /configuration

  

 

  

 mapper namespace="priv.dandelion.mapper.UserMapper" 

 

   !-- resultType的值不区分大小写 --

   select id="selectAll" resultType="user"

   select * from tb_user;

   /select

   /mapper

  

 

  5、配置文件实现CRUD

  5.1 环境准备

  
-- 添加数据

  insert into tb_brand (brand_name, company_name, ordered, description, status)

  values (三只松鼠, 三只松鼠股份有限公司, 5, 好吃不上火, 0),

   (华为, 华为技术有限公司, 100, 华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界, 1),

   (小米, 小米科技有限公司, 50, are you ok, 1);

  
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

   "http://mybatis.org/dtd/mybatis-3-mapper.dtd"

   namespace:命名空间

   mapper namespace="priv.dandelion.mapper.BrandMapper"

   !-- 起别名解决数据库和实体类字段名不同问题

   sql id="brand_column"

   id, brand_name as brandName, company_name as companyName, ordered, description, status

   /sql

   select id="selectAll" resultType="priv.dandelion.entity.Brand"

   select * from tb_brand;

   select

   include refid="brand_column"/

   from tb_brand;

   /select

   !-- resultMap解决数据库和实体类字段不同问题 --

   resultMap id="brandResultMap" type="brand"

   result column="brand_name" property="brandName" /

   result column="company_name" property="companyName" /

   /resultMap

   !-- 不使用resultType, 使用resultMap --

   select id="selectAll" resultMap="brandResultMap"

   select *

   from tb_brand;

   /select

   /mapper

  

 

 

  
String resource = "mybatis-config.xml";

   InputStream inputStream = Resources.getResourceAsStream(resource);

   SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

   // 获取sqlSession对象

   SqlSession sqlSession = sqlSessionFactory.openSession();

   // 获取mapper接口的代理对象

   BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

   // 执行方法

   List Brand brands = brandMapper.selectAll();

   System.out.println(brands);

   // 释放资源

   sqlSession.close();

  

 

 

  
#{占位符名}:会替换为?,防止SQL注入,一般用于替换字段值

  ${占位符名}:存在SQL注入问题,一般用于执行动态SQL语句,如表名列名不固定的情况(见)

  


 resultMap id="brandResultMap" type="brand" 

 

   result column="brand_name" property="brandName" /

   result column="company_name" property="companyName" /

   /resultMap

   select id="selectById" resultMap="brandResultMap"

   select *

   from tb_brand where id = #{id};

   /select

  

 

  
String resource = "mybatis-config.xml";

   InputStream inputStream = Resources.getResourceAsStream(resource);

   SqlSessionFactory sqlSessionFactory =

   new SqlSessionFactoryBuilder().build(inputStream);

   // 获取sqlSession对象

   SqlSession sqlSession = sqlSessionFactory.openSession();

   // 获取mapper接口的代理对象

   BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

   // 执行方法

   companyName = "%" + companyName + "%";

   brandName = "%" + brandName + "%";

   List Brand brands = brandMapper.selectByCondition(status, companyName, brandName);

   System.out.println(brands);

   // 释放资源

   sqlSession.close();

  

 

 

  
多条件查询:如果有多个参数,需要使用@Paran("SQL参数占位符名称")注解

  多条件的动态条件查询:对象属性名称要和参数占位符名称一致
 

  (详见5-2解决数据库字段和实体类字段名不同的问题)

  单条件的动态条件查询:保证key要和参数占位符名称一致

  


 !-- resultMap解决数据库和实体类字段不同问题 -- 

 

   resultMap id="brandResultMap" type="brand"

   result column="brand_name" property="brandName"/

   result column="company_name" property="companyName"/

   /resultMap

   !-- 条件查询 --

   select id="selectByCondition" resultMap="brandResultMap"

   select *

   from tb_brand

   where status = #{status}

   and company_name like #{companyName}

   and brand_name like #{brandName}

   /select

  

 

  
String resource = "mybatis-config.xml";

   InputStream inputStream = Resources.getResourceAsStream(resource);

   SqlSessionFactory sqlSessionFactory =

   new SqlSessionFactoryBuilder().build(inputStream);

   // 获取sqlSession对象

   SqlSession sqlSession = sqlSessionFactory.openSession();

   // 获取mapper接口的代理对象

   BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

   // 执行方法

   companyName = "%" + companyName + "%";

   brandName = "%" + brandName + "%";

   List Brand brands = brandMapper.selectByCondition(

   status, companyName, brandName);

   System.out.println(brands);

   // 释放资源

   sqlSession.close();

  

 

 

  
brand.setCompanyName("%" + companyName + "%");

  brand.setBrandName("%" + brandName + "%");

  List Brand brands = brandMapper.selectByCondition(brand);

  System.out.println(brands);

  

 

 

  
map.put("companyName", "%" + companyName + "%");

  map.put("brandName", "%" + brandName + "%");

  List Brand brands = brandMapper.selectByCondition(map);

  System.out.println(brands);

  

 

 

  
优化条件查询,如页面上表单存在多个条件选项,但实际填写表单仅使用部分条件筛选的情况

  


 !-- resultMap解决数据库和实体类字段不同问题 -- 

 

   resultMap id="brandResultMap" type="brand"

   result column="brand_name" property="brandName"/

   result column="company_name" property="companyName"/

   /resultMap

   !-- 动态条件查询 --

   select id="selectByCondition" resultMap="brandResultMap"

   select *

   from tb_brand

   where

   if test="status != null"

   status = #{status}

   /if

   if test="companyName != null"

   and company_name like #{companyName}

   /if

   if test="brandName != null"

   and brand_name like #{brandName}

   /if

   /where

   /select

  

 

  注:

  
对所有的条件前都加AND,并在WHERE后加任意真判断,即WHERE 1=1 AND ... AND ...

  加入 if /if 判断标签造轮子,自行决定添加AND的条件

  使用 where /where 标签替换原SQL中的WHERE关键字,MyBatis将自动进行语法修正,如示例所示

  


 !-- resultMap解决数据库和实体类字段不同问题 -- 

 

   resultMap id="brandResultMap" type="brand"

   result column="brand_name" property="brandName"/

   result column="company_name" property="companyName"/

   /resultMap

   !-- 单条件动态查询 --

   select id="selectByConditionSingle" resultMap="brandResultMap"

   select *

   from tb_brand

   where

   choose

   when test="status != null"

   status = #{status}

   /when

   when test="companyName != null and companyName != "

   company_name like #{companyName}

   /when

   when test="brandName != null and brandName != "

   brand_name like #{brandName}

   /when

   /choose

   /where

   /select

  

 

  


 insert id="add" 

 

   insert into tb_brand (brand_name, company_name, ordered, description, status)

   values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});

   /insert

  

 

  
String resource = "mybatis-config.xml";

   InputStream inputStream = Resources.getResourceAsStream(resource);

   SqlSessionFactory sqlSessionFactory =

   new SqlSessionFactoryBuilder().build(inputStream);

   // 获取sqlSession对象

   // SqlSession sqlSession = sqlSessionFactory.openSession();

   SqlSession sqlSession = sqlSessionFactory.openSession(true);

   // 获取mapper接口的代理对象

   BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

   // 执行方法

   Brand brand = new Brand();

   brand.setStatus(1);

   brand.setBrandName(brandName);

   brand.setCompanyName(companyName);

   brand.setDescription(description);

   brand.setOrdered(ordered);

   brandMapper.add(brand);

   System.out.println("添加成功");

   // 提交事务

   // sqlSession.commit();

   // 释放资源

   sqlSession.close();

  

 

 

  
MyBayis事务处理的方法

  

// 方法一:在获取sqlSession对象时设置参数,开启自动事务

 

  SqlSession sqlSession = sqlSessionFactory.openSession(true);

  sqlSession.close();

  // 方法二:手动提交事务

  SqlSession sqlSession = sqlSessionFactory.openSession();

  sqlSession.commit();

  sqlSession.close();

  

 

  


 insert id="add" useGeneratedKeys="true" keyProperty="id" 

 

   insert into tb_brand (brand_name, company_name, ordered, description, status)

   values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});

   /insert

  

 

  
优化上述代码应对仅修改部分属性导致其他属性数据丢失问题

  使用 set /set 标签替换set关键字列表,区别于 where /where 标签,注意语法

  
String resource = "mybatis-config.xml";

   InputStream inputStream = Resources.getResourceAsStream(resource);

   SqlSessionFactory sqlSessionFactory =

   new SqlSessionFactoryBuilder().build(inputStream);

   // 获取sqlSession对象

   SqlSession sqlSession = sqlSessionFactory.openSession(true);

   // 获取mapper接口的代理对象

   BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

   // 执行方法

   Brand brand = new Brand();

   brand.setId(id);

   brand.setStatus(status);

   brand.setBrandName(brandName);

   brand.setCompanyName(companyName);

   brand.setOrdered(ordered);

   brandMapper.update(brand);

   System.out.println("修改成功");

   // 释放资源

   sqlSession.close();

  

 

 

  
String resource = "mybatis-config.xml";

   InputStream inputStream = Resources.getResourceAsStream(resource);

   SqlSessionFactory sqlSessionFactory =

   new SqlSessionFactoryBuilder().build(inputStream);

   // 获取sqlSession对象

   SqlSession sqlSession = sqlSessionFactory.openSession(true);

   // 获取mapper接口的代理对象

   BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

   // 执行方法

   brandMapper.deleteById(id);

   System.out.println("删除成功");

   // 释放资源

   sqlSession.close();

  

 

 

  
MyBatis默认会将数组参数封装为Map集合,其key为array,即 array = ids

  可在接口中对参数数组使用@Param注解,将封装后的key手动命名,则可在映射文件中使用

  
separator属性为分隔符

  open和close属性分别为在 foreach /foreach 前后拼接字符,主要用于代码规范,示例中未展示

  
!-- foreach collection="array" item="id" --

   foreach collection="ids" item="id" separator=","

   #{id}

   /foreach

   /delete

  

 

 

  
String resource = "mybatis-config.xml";

   InputStream inputStream = Resources.getResourceAsStream(resource);

   SqlSessionFactory sqlSessionFactory =

   new SqlSessionFactoryBuilder().build(inputStream);

   // 获取sqlSession对象

   SqlSession sqlSession = sqlSessionFactory.openSession(true);

   // 获取mapper接口的代理对象

   BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

   // 执行方法

   brandMapper.deleteByIds(ids);

   System.out.println("删除成功");

   // 释放资源

   sqlSession.close();

  

 

 

  
设有如下代码:

  

User select(@Param("username") String username,@Param("password") String password);

 

  

 

  MyBatis会将散装的多个参数封装为Map集合

  
Collection集合类型:封装Map集合,可以使用@Param注解替换Map集合中默认arg键名

  

map.put("arg0",collection集合);

 

  map.put("collection",collection集合;

  

 

  
List集合类型:封装为Map集合,可以使用@Param注解,替换Map集合中默认的arg键名

  

map.put("arg0",list集合);

 

  map.put("collection",list集合);

  map.put("list",list集合);

  

 

  
Array类型:封装为Map集合,可以使用@Param注解,替换Map集合中默认的arg键名

  

map.put("arg0",数组);

 

  map.put("array",数组);

  

 

  
用于简化开发,可以对简单的查询使用注解进行操作,以替换xml中的statement

  对于复杂的查询,仍然建议使用xml配置文件,否则代码会十分混乱

  


 !-- resultMap解决数据库和实体类字段不同问题 -- 

 

   resultMap id="brandResultMap" type="brand"

   result column="brand_name" property="brandName"/

   result column="company_name" property="companyName"/

   /resultMap

   select id="selectById" resultMap="brandResultMap"

   select *

   from tb_brand

   where id = #{id};

   /select

  

 

  


@ResultMap("brandResultMap") // 解决数据库和实体类字段名称不同

 

  @Select("select * from tb_brand where id = #{id}") // 查询语句

  Brand selectById(int id);

  

 

  
SQL映射文件:不再需要原先的statement

  

 !-- resultMap解决数据库和实体类字段不同问题 -- 

 

   resultMap id="brandResultMap" type="brand"

   result column="brand_name" property="brandName"/

   result column="company_name" property="companyName"/

   /resultMap

   select id="selectById" resultMap="brandResultMap"

   select *

   from tb_brand

   where id = #{id};

   /select

  

 

  以上就是MyBatis快速上手与知识点总结()的详细内容,想要了解更多 MyBatis快速上手与知识点总结的内容,请持续关注盛行IT软件开发工作室。

郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。

留言与评论(共有 条评论)
   
验证码: