Mybatis

2019-11-15  本文已影响0人  朴炯文

基本的增删改查

以下演示是在springboot上做得

application.yml

spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.168.5.19:3306/vr_resource?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
    username: root
    password: asdfasdf
    hikari:
      minimum-idle: 5
      idle-timeout: 180000
      maximum-pool-size: 10
      auto-commit: true
      pool-name: MyHikariCP
      max-lifetime: 1800000
      connection-timeout: 30000

server:
  port: 9090
mybatis:
  config-location: classpath:mybatis-config.xml
  mapper-locations: classpath:mapper/*.xml
  #type-aliases-package: com.example.demo.entity

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>

ResourceMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--与某一个mapper接口关联,写全限定名称-->
<mapper namespace="com.example.demo.mapper.VrResourceMapper">

    <!--id对应mapper接口里的方法名字-->
    <!--resultType对应的是返回类型-->
    <!--parameterType对应的是参数类型-->
        <!-- 可以是实体类,也可以是Map,String,Integer...-->

    <select id="selectAll" resultType="com.example.demo.entity.VrResource">
        select * from japan_resource;
    </select>

    <select id="selectSome" resultType="com.example.demo.entity.VrResource" parameterType="String">
        select * from japan_resource where id= #{str};
    </select>

    <insert id="insertOne" parameterType="com.example.demo.entity.VrResource">
        insert into wholeview_resource (title,extra) values (#{vrResource.title},#{vrResource.extra});
    </insert>

</mapper>

entity

package com.example.demo.entity;

import lombok.Data;

import java.util.Date;
@Data
public class VrResource {
    private Integer id;
    private String title;
    private Date updateTime;
    private String extra;
    public VrResource(){

    }
    public VrResource( String title, String extra){
        this.title=title;
        this.extra=extra;
    }
}

controller

package com.example.demo.controller;

import com.example.demo.entity.VrResource;
import com.example.demo.service.VrResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
public class VrResourceController {
    @Autowired
    private VrResourceService vrResourceService;

    @ResponseBody
    @RequestMapping("selectall")
    public List<VrResource> selectAll(){
        return vrResourceService.selectAll();
    }

    @ResponseBody
    @RequestMapping("selectsome/{str}")
    public List<VrResource> selectSome(@PathVariable(value = "str") String str){
        return vrResourceService.selectSome(str);
    }

    @ResponseBody
    @RequestMapping("insertone")
    public void insertOne(){

        VrResource vrResource=new VrResource("s","s");

        vrResourceService.insertOne(vrResource);
    }
}

service

package com.example.demo.service;


import com.example.demo.entity.VrResource;
import com.example.demo.mapper.VrResourceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class VrResourceService {
    @Autowired
    VrResourceMapper vrResourceMapper;

    public List<VrResource> selectAll(){
        return vrResourceMapper.selectAll();
    }
    public List<VrResource> selectSome(String str){
        return vrResourceMapper.selectSome(str);
    }

    public void insertOne(VrResource vrResource){
        vrResourceMapper.insertOne(vrResource);
    }
}

mapper(dao)

package com.example.demo.mapper;

import com.example.demo.entity.VrResource;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
public interface VrResourceMapper {
    List<VrResource> selectAll();
    List<VrResource> selectSome(@Param("str") String str);
    void insertOne(@Param("vrResource") VrResource vrResource);
}

程序入口

package com.example.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

like模糊查询

--Mysql: 
select * from t_user where name like concat('%', #{name}, '%')
--Oracle: 
select * from t_user where name like '%' || #{name} || '%'
--SQLServer: 
select * from t_user where name like '%' + #{name} + '%' 

resultMap

当数据库里的字段和实体类字段名不一样的时候使用,可以映射

简单使用

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.dao.UserMapper">
  <resultMap id="UserMap" type="User">
    <!-- column数据库中的字段,property实体类中的属性-->
    <result colum="id" property="id"/>
    <result colum="name" property="name"/>
    <result colum="pwd" property="password"/>
  </resultMap>
  
  <select id="xxx" resultMap="UserMap" >
    select * from mybatis.user where id = #{id}
  </select>
</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>
  这里面些下面的environments,properties等等
</configuration>

环境配置(environnments)

mybatis可以配置成使用多种环境
不过要记住:尽管可以配置多个环境,但每个sqlsessionfactory实例只能选择一种环境。
学会使用配置多套运行环境
mybatis默认的食物管理器就是jdbc,连接池:pooled

属性(properties)

我们可以通过properties属性来实现引用配置文件
这些属性都是可外部配置且可动态替换的,既可以在典型的java属性文件中配置,亦可通过propreties元素的子元素来传递
如果a引用了b(外部),有相同属性的时候优先使用b里面的

类型别名(typeAliases)

类型别名是为java类型设置一个短的名字
存在的意义仅在于用来减少类完全限定名的冗余

   <typeAliases>
        <typeAlias alias="User" type="com.kuang.pojo.User" />
    </typeAliases>

也可以指定一个包名,mybatis会在包名下面搜索需要的java bean,比如:扫描实体类的包,它的默认别名为这个类的类名,首字母小写!如果非要改,name在实体类上增加注解

   <typeAliases>
        <package name="com.kuang.pojo" />
    </typeAliases>
@Alias("myUser")
public class User{}

设置(settings)

这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为

类型处理器(typeHandlers)

对象工厂(objectFactory)

插件(plugins)

映射器(mapper)

生命周期和作用域

使用注解写sql

动态sql

if

动态 SQL 通常要做的事情是根据条件包含 where 子句的一部分。比如:

<select id="findActiveBlogWithTitleLike"
     resultType="Blog">
  SELECT * FROM BLOG
  WHERE state = ‘ACTIVE’
  <if test="title != null">
    AND title like #{title}
  </if>
</select>

这条语句提供了一种可选的查找文本功能。如果没有传入“title”,那么所有处于“ACTIVE”状态的BLOG都会返回;反之若传入了“title”,那么就会对“title”一列进行模糊查找并返回 BLOG 结果(细心的读者可能会发现,“title”参数值是可以包含一些掩码或通配符的)。

如果希望通过“title”和“author”两个参数进行可选搜索该怎么办呢?首先,改变语句的名称让它更具实际意义;然后只要加入另一个条件即可。

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <if test="title != null">
    AND title like #{title}
  </if>
  <if test="author != null and author.name != null">
    AND author_name like #{author.name}
  </if>
</select>

choose (when, otherwise)

有时我们不想应用到所有的条件语句,而只想从中择其一项。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

还是上面的例子,但是这次变为提供了“title”就按“title”查找,提供了“author”就按“author”查找的情形,若两者都没有提供,就返回所有符合条件的 BLOG(实际情况可能是由管理员按一定策略选出 BLOG 列表,而不是返回大量无意义的随机结果)。

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * 
  FROM BLOG 
  WHERE state = ‘ACTIVE’
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND featured = 1
    </otherwise>
  </choose>
</select>

where

where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入“WHERE”子句。而且,若语句的开头为“AND”或“OR”,where 元素也会将它们去除。

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG
  <where>
    <if test="state != null">
         state = #{state}
    </if>
    <if test="title != null">
        AND title like #{title}
    </if>
    <if test="author != null and author.name != null">
        AND author_name like #{author.name}
    </if>
  </where>
</select>

set

set 元素会动态前置 SET 关键字,同时也会删掉无关的逗号,因为用了条件语句之后很可能就会在生成的 SQL 语句的后面留下这些逗号。(因为用的是“if”元素,若最后一个“if”没有匹配上而前面的匹配上,SQL 语句的最后就会有一个逗号遗留)

<update id="updateAuthorIfNecessary">
  update Author
    <set>
      <if test="username != null">username=#{username},</if>
      <if test="password != null">password=#{password},</if>
      <if test="email != null">email=#{email},</if>
      <if test="bio != null">bio=#{bio}</if>
    </set>
  where id=#{id}
</update>

trim

一句话描述trim的功能:子句首尾的删除与添加。它就是一个字符串处理工具,类似于replace()
<trim prefixOverrides="" prefix="" suffixOverrides="" suffix=""></trim>

sql片段

有的时候,我们可能会将一些功能的部分出后去出来,方便服用。

  1. 阿斯蒂芬

foreach

上一篇 下一篇

猜你喜欢

热点阅读