文章目录
前言
提示:
自古红颜多祸水
1.MyBatis简介
2.快速入门
1. 建表
CREATE DATABASE mybatis;
use mybatis;
drop TABLE if EXISTS tb_user;
CREATE TABLE tb_user(
id int primary key auto_increment,
username VARCHAR(20),
password VARCHAR(20),
gender CHAR(1),
addr VARCHAR(30)
);
INSERT INTO tb_user VALUES(1,'zhangsan','123','男','曲靖');
INSERT INTO tb_user VALUES(2,'李四','234','女','越州');
INSERT INTO tb_user VALUES(3,'王五','456','男','曲靖');
2. 创建maven项目
配置文件logback.xml
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%level] %blue(%d{HH:mm:ss.SSS}) %cyan([%thread]) %boldGreen(%logger{15}) - %msg %n</pattern>
<!-- <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>-->
</encoder>
</appender>
<logger name="com.wei" level="DEBUG" additivity="false">
<appender-ref ref="Console"/>
</logger>
</configuration>
配置文件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:///mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 加载sql映射文件-->
<mapper resource="userMapper.xml"/>
</mappers>
</configuration>
配置文件userMapper.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="test">
<select id="selectAll" resultType="com.wei.pojo.User">
select * from tb_user;
</select>
</mapper>
测试类
package com.wei.pojo;
public class User {
private Integer id;
private String username;
private String password;
private String gender;
private String addr;
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 getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", gender='" + gender + '\'' +
", addr='" + addr + '\'' +
'}';
}
}
package com.wei.pojo.com.wei;
import com.wei.pojo.User;
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;
import java.util.List;
public class MyBatisDemo {
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);
// 获取sqlsession对象,用来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执行sql
List<User> users = sqlSession.selectList("test.selectAll");
System.out.println(users);
}
}
3.解决SQL语句警告提示
4.Mapper代理开发
5.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>
<!-- 配置别名-->
<typeAliases>
<package name="com.wei.pojo"/>
</typeAliases>
<!-- environments:配置数据库环境信息,可以配置多个environment, 通过default属性切换不同的数据源 -->
<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:///mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</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="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 加载sql映射文件-->
<!-- <mapper resource="com/wei/mapper/userMapper.xml"/>-->
<!-- mapper代理方式-->
<package name="com.wei.mapper"/>
</mappers>
</configuration>
6.MyBatis案例-准备环境
CREATE TABLE `tb_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`gender` char(1) DEFAULT NULL,
`addr` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
package com.wei.pojo;
public class Brand {
private Integer id;
private String brandName;
private String companyName;
private String ordered;
private String description;
private Integer status;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getOrdered() {
return ordered;
}
public void setOrdered(String ordered) {
this.ordered = ordered;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
@Override
public String toString() {
return "Brand{" +
"id=" + id +
", brandName='" + brandName + '\'' +
", companyName='" + companyName + '\'' +
", ordered='" + ordered + '\'' +
", description='" + description + '\'' +
", status=" + status +
'}';
}
}
7.查询-查询所有&结果映射
package com.wei.test;
import com.wei.mapper.BrandMapper;
import com.wei.pojo.Brand;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyBatisTest {
@Test
public void testSelectAll() throws IOException {
// 获取SqlSessionFactory
// 加载MyBatis的核心配置文件,获取SqlSessionFactory
String resourse = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resourse);
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();
}
}
<?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.wei.mapper.BrandMapper">
<!-- <select id="selectAll" resultType="brand">-->
<!-- select * from tb_brand;-->
<!-- </select>-->
<!--
数据表字段名称和实体类的属性名称不一样,则不能自动封装数据
*起别名,每次查询都要定义一次别名
-->
<!-- <select id="selectAll" resultType="brand">-->
<!-- select id,brand_name as brandName,company_name as companyName,-->
<!-- ordered,description,status from tb_brand;-->
<!-- </select>-->
<!-- sql片段-->
<!-- <sql id="brand_column">-->
<!-- id-->
<!-- ,brand_name as brandName,company_name as companyName, ordered,description,status-->
<!-- </sql>-->
<!-- <select id="selectAll" resultType="brand">-->
<!-- select-->
<!-- <include refid="brand_column"></include>-->
<!-- from tb_brand;-->
<!-- </select>-->
<!-- resultMap-->
<resultMap id="brandResultMap" type="brand">
<result column="brand_name" property="brandName"></result>
<result column="company_name" property="companyName"></result>
</resultMap>
<select id="selectAll" resultMap="brandResultMap">
select * from tb_brand;
</select>
</mapper>
8.查询-查看详情
9.查询-条件查询
package com.wei.mapper;
import com.wei.pojo.Brand;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface BrandMapper {
/**
* 查询所有
*/
public List<Brand> selectAll();
/**
* 查询单条数据
*
* @param id
*/
public Brand selectById(int id);
/**
* 多条件查询
* 散装参数:如果方法中有多个参数,需要使用@Params("SQL参数占位符名称")
* 对象参数:对象的属性名称要喝参数占位符名称一致
* map集合参数
*/
//List<Brand> selectByCondition(@Param("status") int status,@Param("companyName") String companyName,@Param("brandName") String brandName);
//List<Brand> selectByCondition(Brand brand);
List<Brand> selectByCondition(Map map);
}
<?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.wei.mapper.BrandMapper">
<!-- <select id="selectAll" resultType="brand">-->
<!-- select * from tb_brand;-->
<!-- </select>-->
<!--
数据表字段名称和实体类的属性名称不一样,则不能自动封装数据
*起别名,每次查询都要定义一次别名
-->
<!-- <select id="selectAll" resultType="brand">-->
<!-- select id,brand_name as brandName,company_name as companyName,-->
<!-- ordered,description,status from tb_brand;-->
<!-- </select>-->
<!-- sql片段-->
<!-- <sql id="brand_column">-->
<!-- id-->
<!-- ,brand_name as brandName,company_name as companyName, ordered,description,status-->
<!-- </sql>-->
<!-- <select id="selectAll" resultType="brand">-->
<!-- select-->
<!-- <include refid="brand_column"></include>-->
<!-- from tb_brand;-->
<!-- </select>-->
<!-- resultMap-->
<resultMap id="brandResultMap" type="brand">
<result column="brand_name" property="brandName"></result>
<result column="company_name" property="companyName"></result>
</resultMap>
<select id="selectAll" resultMap="brandResultMap">
select *
from tb_brand;
</select>
<!--
参数占位符
#{} 防止sql注入
${}
-->
<select id="selectById" parameterType="int" resultMap="brandResultMap">
select *
from tb_brand
where id = #{id};
</select>
<!-- 条件查询-->
<select id="selectByCondition" resultMap="brandResultMap">
select *
from tb_brand
where status = #{status}
and company_name like #{companyName}
and brand_name like #{brandName}
</select>
</mapper>
package com.wei.test;
import com.wei.mapper.BrandMapper;
import com.wei.pojo.Brand;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MyBatisTest {
// @Test
// public void testSelectAll() throws IOException {
// // 获取SqlSessionFactory
// // 加载MyBatis的核心配置文件,获取SqlSessionFactory
// String resourse = "mybatis-config.xml";
// InputStream inputStream = Resources.getResourceAsStream(resourse);
// 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);
//
// // 查询单条数据
// Brand data = brandMapper.selectById(3);
// System.out.println(data);
//
// // 释放资源
// sqlSession.close();
// }
@Test
public void testSelectByCondition() throws IOException {
// 接受参数
int status = 1;
String companyName = "愤豆";
String brandName = "豆";
// 处理参数
companyName = "%" + companyName + "%";
brandName = "%" + brandName + "%";
// 封装对象
// Brand brand = new Brand();
// brand.setStatus(status);
// brand.setBrandName(brandName);
// brand.setCompanyName(companyName);
Map map = new HashMap();
map.put("status", status);
map.put("companyName", companyName);
map.put("brandName", brandName);
// 获取SqlSessionFactory
// 加载MyBatis的核心配置文件,获取SqlSessionFactory
String resourse = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resourse);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
// 执行方法
// List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName);
// List<Brand> brands = brandMapper.selectByCondition(brand);
List<Brand> brands = brandMapper.selectByCondition(map);
System.out.println(brands);
// 释放资源
sqlSession.close();
}
}
10 .查询-动态条件查询
<?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.wei.mapper.BrandMapper">
<!-- <select id="selectAll" resultType="brand">-->
<!-- select * from tb_brand;-->
<!-- </select>-->
<!--
数据表字段名称和实体类的属性名称不一样,则不能自动封装数据
*起别名,每次查询都要定义一次别名
-->
<!-- <select id="selectAll" resultType="brand">-->
<!-- select id,brand_name as brandName,company_name as companyName,-->
<!-- ordered,description,status from tb_brand;-->
<!-- </select>-->
<!-- sql片段-->
<!-- <sql id="brand_column">-->
<!-- id-->
<!-- ,brand_name as brandName,company_name as companyName, ordered,description,status-->
<!-- </sql>-->
<!-- <select id="selectAll" resultType="brand">-->
<!-- select-->
<!-- <include refid="brand_column"></include>-->
<!-- from tb_brand;-->
<!-- </select>-->
<!-- resultMap-->
<resultMap id="brandResultMap" type="brand">
<result column="brand_name" property="brandName"></result>
<result column="company_name" property="companyName"></result>
</resultMap>
<select id="selectAll" resultMap="brandResultMap">
select *
from tb_brand;
</select>
<!--
参数占位符
#{} 防止sql注入
${}
-->
<select id="selectById" parameterType="int" resultMap="brandResultMap">
select *
from tb_brand
where id = #{id};
</select>
<!-- 多条件查询-->
<!-- <select id="selectByCondition" resultMap="brandResultMap">-->
<!-- select *-->
<!-- from tb_brand-->
<!-- where status = #{status}-->
<!-- and company_name like #{companyName}-->
<!-- and brand_name like #{brandName}-->
<!-- </select> -->
<!-- 动态多条件查询-->
<select id="selectByCondition" resultMap="brandResultMap">
select *
from tb_brand
/* where 1=1*/
<where>
<if test="status != null">
and status = #{status}
</if>
<if test="companyName != null and companyName != '' ">
and company_name like #{companyName}
</if>
<if test="brandName != null and brandName != ''">
and brand_name like #{brandName}
</if>
</where>
</select>
</mapper>
<?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.wei.mapper.BrandMapper">
<!-- <select id="selectAll" resultType="brand">-->
<!-- select * from tb_brand;-->
<!-- </select>-->
<!--
数据表字段名称和实体类的属性名称不一样,则不能自动封装数据
*起别名,每次查询都要定义一次别名
-->
<!-- <select id="selectAll" resultType="brand">-->
<!-- select id,brand_name as brandName,company_name as companyName,-->
<!-- ordered,description,status from tb_brand;-->
<!-- </select>-->
<!-- sql片段-->
<!-- <sql id="brand_column">-->
<!-- id-->
<!-- ,brand_name as brandName,company_name as companyName, ordered,description,status-->
<!-- </sql>-->
<!-- <select id="selectAll" resultType="brand">-->
<!-- select-->
<!-- <include refid="brand_column"></include>-->
<!-- from tb_brand;-->
<!-- </select>-->
<!-- resultMap-->
<resultMap id="brandResultMap" type="brand">
<result column="brand_name" property="brandName"></result>
<result column="company_name" property="companyName"></result>
</resultMap>
<select id="selectAll" resultMap="brandResultMap">
select *
from tb_brand;
</select>
<!--
参数占位符
#{} 防止sql注入
${}
-->
<select id="selectById" parameterType="int" resultMap="brandResultMap">
select *
from tb_brand
where id = #{id};
</select>
<!-- 多条件查询-->
<!-- <select id="selectByCondition" resultMap="brandResultMap">-->
<!-- select *-->
<!-- from tb_brand-->
<!-- where status = #{status}-->
<!-- and company_name like #{companyName}-->
<!-- and brand_name like #{brandName}-->
<!-- </select> -->
<!-- 动态多条件查询-->
<select id="selectByCondition" resultMap="brandResultMap">
select *
from tb_brand
/* where 1=1*/
<where>
<if test="status != null">
and status = #{status}
</if>
<if test="companyName != null and companyName != '' ">
and company_name like #{companyName}
</if>
<if test="brandName != null and brandName != ''">
and brand_name like #{brandName}
</if>
</where>
</select>
<!-- 动态单条件查询-->
<!-- <select id="selectByConditionSingle" resultType="brand" resultMap="brandResultMap">-->
<!-- select * from tb_brand-->
<!-- where-->
<!-- <choose><!–相当于switch–>-->
<!-- <when test="status != null"> <!–相当于case–>-->
<!-- status = #{status}-->
<!-- </when>-->
<!-- <when test="companyName != null and companyName != '' "> <!–相当于case–>-->
<!-- and company_name like #{companyName}-->
<!-- </when>-->
<!-- <when test="brandName != null and brandName != ''"> <!–相当于case–>-->
<!-- and brand_name like #{brandName}-->
<!-- </when>-->
<!-- <otherwise>-->
<!-- 1=1-->
<!-- </otherwise>-->
<!-- </choose>-->
<!-- </select> -->
<select id="selectByConditionSingle" resultType="brand" resultMap="brandResultMap">
select * from tb_brand
<where>
<choose><!--相当于switch-->
<when test="status != null"> <!--相当于case-->
status = #{status}
</when>
<when test="companyName != null and companyName != '' "> <!--相当于case-->
and company_name like #{companyName}
</when>
<when test="brandName != null and brandName != ''"> <!--相当于case-->
and brand_name like #{brandName}
</when>
<otherwise>
1=1
</otherwise>
</choose>
</where>
</select>
</mapper>
11.添加&修改功能
<insert id="add">
insert into tb_brand(brand_name, company_name, ordered, description, status)
values(#{brandName},#{companyName},#{ordered},#{description},#{status});
</insert>
<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>
<update id="update">
update tb_brand
set brand_name = #{brandName},
company_name = #{companyName},
ordered = #{ordered},
description = #{description},
status = #{status}
where id = #{id};
</update>
<update id="update">
update tb_brand
<set>
<if test="brandName != null and brandName != '' ">
brand_name = #{brandName},
</if>
<if test="companyName != null and companyName != '' ">
company_name = #{companyName},
</if>
<if test="ordered != null">
ordered = #{ordered},
</if>
<if test="description != null and description != '' ">
description = #{description},
</if>
<if test="status != null">
status = #{status}
</if>
</set>
where id = #{id};
</update>
12.删除功能
<delete id="deleteById">
delete from tb_brand where id = #{id};
</delete>
<!-- mybatis会将数组参数封装为一个Map集合
默认格式:array = 数组
使用@Param注解改变map集合的默认key名称
-->
<delete id="deleteByIds">
delete from tb_brand where id
in
<foreach collection="array" item="id" separator="," open="(" close=")">
#{id}
</foreach>
;
</delete>
13.参数传递
14.注解开发
@Select ("select * from tb_brand where id = #{id}")
Brand selectById(int id);
内容整理自黑马程序员