MyBatis:
MyBatis的前身就是iBatis,iBatis本是apache的一个开源项目,2010年5月这个项目由apahce sofeware foundation 迁移到了google code,并且改名为MyBatis。
MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及结果集的检索。
1、 简化JDBC的开发
2、 能够更好的完成ORM(对象关系映射)
MyBatis的作用:
操作数据库,对数据进行增删改查操作.
<?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">
<!-- 写SQL语句,namespace是这个文件的唯一标识 -->
<mapper namespace="deptm">
<!-- 查询所有, id是SQL语句的唯一标识,resultType是结果类型意思是要把结果封装给谁 -->
<select id="getAll" resultType="cn.tedu.pojo.Dept">
select * from dept
</select>
<!-- 查一条记录 ,resultType是结果类型意思是要把结果封装给谁 -->
<select id="getOne" resultType="cn.tedu.pojo.Dept">
select * from dept where id =1
</select>
<!-- 动态的 查一条记录 ,resultType是结果类型意思是要把结果封装给谁 ,parameterType是SQL需要的参数x的类型-->
<select id="getOne2" resultType="cn.tedu.pojo.Dept" parameterType="int">
<!-- where 字段名=要设置的值 , ${x} 通过${}来获取传递过来的值-->
select * from dept where id =${x}
</select>
<!-- 查询 总记录数 -->
<select id="getSum" resultType="int">
select count(*) from dept
</select>
<!-- 新增记录 $和#的区别就是#会自动拼接字符串,$只会取到值本身-->
<insert id="add" parameterType="cn.tedu.pojo.Dept">
<!-- Cause: java.sql.SQLSyntaxErrorException: Unknown column 'java教研部' in 'field list' -->
<!-- insert into dept(dname,loc) values(${dname},${loc}) -->
<!-- 获取参数的值时,如果参数是String类型,$只取值loc=tony,不会自动拼串.#可以给String的参数拼串loc='tony' -->
insert into dept(dname,loc) values( #{dname},#{loc} )
</insert>
<!-- 修改 -->
<update id="update" parameterType="String">
<!-- $不会自动拼串鸭 dname=哈哈哈哈 -->
<!-- update dept set dname=${x} where deptno=2 -->
update dept set dname=#{x} where id =2
</update>
<!-- 删除 -->
<delete id="del" parameterType="int">
delete from dept where id =${a}
</delete>
</mapper>
Mybatis的参数
别名:alias
在sqlMapConfig.xml配置,在映射文件中直接写对象名称即可
<typeAliases>
<typeAlias type="cn.mybatis.pojo.User" alias="User"/>
</typeAliases>
参数值:paramterType
指定参数类型,通常制定一个对象类型。
返回值:resultType
非常重要的东西,即完成ORM的映射关系所在。这里指定的cd.tedu.mybatis.domain.User代表把结果集转换成一个User对象实例。
返回值:resultMap
resultMap 用于对复杂对象结构时,对应的ResultMap结构名称
集合:List
在MyBatis中,大多默认采用List集合,声明集合参数或者返回值时,都有个奇怪的写法,本应写List<String>,但习惯只写集合元素的类型:String,大家切记。
#和$的区别:
两种方式都可以获取参数的值。区别如下:
(推荐!)#: 使用#{parameterName}引用参数的时候,Mybatis会把这个参数认为是一个字符串,例如传入参数是“Smith”,那么在SQL(Select * from emp where name = #{employeeName})使用的时候就会转换为Select * from emp where name = 'Smith'。
$: 不做字符串拼接,SQL(Select * from emp where name = ${employeeName})使用的时候就会转换为Select * from emp where name = Smith。此时,如果字段是varchar类型直接抛出SQL异常。
动态SQL:
1、<sql><include>
Sql标签用来提取SQL片段,来提高SQL的复用.
使用位置需要通过include引用指定的SQL片段.
<sql id="cols">
id,title,sell_point,price,num,barcode,image,cid,status,created,updated
</sql>
<select id="find" resultType="Item" parameterType="Item">
SELECT <include refid="cols"/> FROM tb_item
</select>
2、<if>
执行SQL时,可以添加一些判断条件.
<select id="find" resultType="Item" parameterType="Item">
SELECT <include refid="cols"/> FROM tb_item where
<if test="title != null"> title like #{title} </if>
<if test="sellPoint != null">and sell_point like #{sellPoint}</if>
</select>
3、<where>
去掉条件中可能多余的and或者or:
<select id="find" resultType="Item" parameterType="Item">
SELECT <include refid="cols"/> FROM tb_item
<where>
<if test="title != null"> title like #{title} </if>
<if test="sellPoint != null">and sell_point like #{sellPoint}</if>
</where>
</select>
4、<set>
去掉最后可能多余的逗号:
<update id="update">
UPDATE teachers
<set>
<if test="tname != null">tname=#{tname},</if>
<if test="tsex != null">tsex=#{tsex},</if>
<if test="tbirthday != null">tbirthday=#{tbirthday},</if>
<if test="prof != null">prof=#{prof},</if>
<if test="depart != null">depart=#{depart}</if>
</set>
WHERE tno=#{tno}
</update>
ResultMap:
见另一篇文章
Spring整合Mybatis
(1)新建一个springboot项目
在选择依赖的时候选择Spring Web,Mysql和Mybatis。
(2)在resources里创建yml文件
#YML默认读取时采用UTF-8
spring:
application:
name: mybatis
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/jt?serverTimezone=Asia/Shanghai&useSSL=false
username: root
password: root
mybatis:
mapper-locations: classpath:mappers/*Mapping.xml
# 用于简化resulttype的写法
type-aliases-package: com.example.springbootandmybatis.pojo
logging:
level:
com.example.springboot_demo3_plus.mapper: debug
创建mappers文件夹和UserMapping.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.example.mapper.UserMapper">
</mapper>
(3)按照这个格式创建目录和文件:
UserController:
package com.example.springbootandmybatis.controller;
import com.example.springbootandmybatis.pojo.User;
import com.example.springbootandmybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("customer")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("getall")
public List<User> getAll(){
return userService.getAll();
}
}
UserMapper:
package com.example.springbootandmybatis.mapper;
import com.example.springbootandmybatis.pojo.User;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserMapper {
List<User> getAll();
}
User:
package com.example.springbootandmybatis.pojo;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.stereotype.Component;
@Data
@Accessors(chain = true)
@Component
public class User {
private Integer id;
private String name;
private Integer age;
private String sex;
}
UserService:
package com.example.springbootandmybatis.service;
import com.example.springbootandmybatis.mapper.UserMapper;
import com.example.springbootandmybatis.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> getAll() {
return userMapper.getAll();
}
}
在启动类中添加包扫描:
@SpringBootApplication
@MapperScan("com.example.springbootandmybatis.mapper")
public class SpringbootAndMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootAndMybatisApplication.class, args);
}
}
只要所有配置正确,应该可以正常的查询。