Mybatis使用配置(已完成curd):
项目结构(maven工程):
一、配置相关
pom文件
提示:引入的模块
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>mybatis-crud</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<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>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
mybatis-config.xml:
提示:数据库链接配置及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>
<!--这个配置使得UserMapper.xml的resultType可以直接写类名Brand-->
<package name="com.niujl.pojo"/>
</typeAliases>
<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="admin"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 加载sql的映射文件-->
<!-- <mapper resource="com/niujl/mapper/UserMapper.xml"/>-->
<package name="com.niujl.mapper"/>
</mappers>
</configuration>
logback.xml:
提示:控制台输出
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!--
CONSOLE :表示当前的日志信息是可以输出到控制台的。
-->
<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>
</encoder>
</appender>
<logger name="com.itheima" level="DEBUG" additivity="false">
<appender-ref ref="Console"/>
</logger>
<!--
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF
, 默认debug
<root>可以包含零个或多个<appender-ref>元素,标识这个输出位置将会被本日志级别控制。
-->
<root level="DEBUG">
<appender-ref ref="Console"/>
</root>
</configuration>
二、业务逻辑
定义实体类(Brand)
package com.niujl.pojo;
public class Brand {
// id 主键
private Integer id;
// 品牌名称
private String brandName;
// 企业名称
private String companyName;
// 排序字段
private Integer ordered;
// 描述信息
private String description;
// 状态:0:禁用 1:启用
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 Integer getOrdered() {
return ordered;
}
public void setOrdered(Integer 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 +
'}';
}
}
定义接口方法(BrandMapper.java)
package com.niujl.mapper;
import com.niujl.pojo.Brand;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface BrandMapper {
/**
* 查询所有
* @return
*/
List<Brand> selectAll();
/**
* 查看详情:根据id
*/
List<Brand> selectById(int id);
/**
* 根据条件查找
* 1、散装参数:
* 2、对象参数:
* 3、map集合参数:
*/
// @Param()注解是给xml(写sql语句的文件代码看的),因为sql语句有多个参数占位符,所以需要指定参数占位符与值的对应关系
// List<Brand> selectByCondition(@Param("status") int status, @Param("companyName") String companyName, @Param("brandName")String brandName);
// 如果传的是对象的话
// List<Brand> selectByCondition(Brand brand);
// 如果传的是Map集合的话
List<Brand> selectByCondition(Map map);
/**
* 单条件动态查询
*/
List<Brand> selectByConditionSingle(Brand brand);
/**
* 添加记录
*/
void add(Brand brand);
/**
* 修改功能
*/
int update(Brand brand);
/**
* 根据id删除功能
*/
void deleteById(int id);
/**
* 批量删除
* 数组需要注解改变一下传递的名称
* mybatis会将数组封装成一个map集合
* key:array , value:数组
* 使用@Param注解改变map集合的默认key的名称
*/
void deleteByIds(@Param("ids") int[] ids );
}
定义对应的实现接口的sql语句(BrandMapper.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="com.niujl.mapper.UserMapper":名称空间地址要与定义sql语句的接口UserMapper一致
id="selectAll":相当于实现UserMapper接口的方法
-->
<mapper namespace="com.niujl.mapper.BrandMapper">
<resultMap id="brandResultMap" type="brand">
<result column="brand_name" property="brandName"/>
<result column="company_name" property="companyName"/>
</resultMap>
<!-- 查询所有-->
<select id="selectAll" resultMap="brandResultMap">
select *
from tb_brand;
</select>
<!-- 根据id查询所有信息-->
<select id="selectById" resultMap="brandResultMap">
# 不用${id} 是因为防止sql注入(直接拼接显示);#{id}这种方式拼接的是'?',然后参数占位符'?' 替换 为值
select *
from tb_brand where id = #{id};
</select>
<!-- 动态多条件条件查询-->
<select id="selectByCondition" resultMap="brandResultMap">
select *
from tb_brand
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>
</select>
<!-- 单条件动态查询-->
<select id="selectByConditionSingle" resultMap="brandResultMap">
select *
from tb_brand
<!--where、if 是mybatis提供的动态标签来拼接sql语句-->
<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>
<!-- 完整添加一条记录 设置useGeneratedKeys="true" keyProperty="id",测试类才可以拿到返回值id-->
<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>
<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>
<!-- 根据id删除一条记录-->
<delete id="deleteById">
delete
from tb_brand
where id=#{id};
</delete>
<!-- 删除多个id对应的记录-->
<delete id="deleteByIds">
delete
from tb_brand
where id
in (
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
);
</delete>
</mapper>
三、测试类
package com.niujl.test;
import com.niujl.mapper.BrandMapper;
import com.niujl.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 {
//1、加载核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2、获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3、执行sql
// List<User> users = sqlSession.selectList("test.selectAll");
// System.out.println(users);
// 3、1获取UserMapper接口代理的对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
List<Brand> brands = brandMapper.selectAll();
System.out.println(brands);
// 4、释放资源
sqlSession.close();
}
@Test
public void testSelectById() throws IOException {
//设置参数
int id=1;
//1、加载核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2、获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3、1获取UserMapper接口代理的对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
// 3、2执行方法
List<Brand> brands = brandMapper.selectById(id);
System.out.println(brands);
// 4、释放资源
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.setCompanyName(companyName);
// brand.setBrandName(brandName);
//封装成Map
Map map = new HashMap();
// map.put("status", status);
map.put("companyName", companyName);
// map.put("brandName", brandName);
//1、加载核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2、获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3、1获取UserMapper接口代理的对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
// 3、2执行方法(封装成对象或map来执行最好)(mybatis会解析map或brand对象)
// List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName);
// List<Brand> brands = brandMapper.selectByCondition(brand);
List<Brand> brands = brandMapper.selectByCondition(map);
System.out.println(brands);
// 4、释放资源
sqlSession.close();
}
@Test
public void testSelectByConditionSingle() throws IOException {
//设置参数
// int status=1;
String companyName="小米";
// String brandName="小米";
//处理参数
companyName = "%" + companyName + "%";
// brandName = "%" + brandName + "%";
//封装对象
Brand brand = new Brand();
// brand.setStatus(status);
brand.setCompanyName(companyName);
// brand.setBrandName(brandName);
//封装Map对象
// Map map = new HashMap();
// map.put("status", status);
// map.put("companyName", companyName);
// map.put("brandName", brandName);
//1、加载核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2、获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3、1获取UserMapper接口代理的对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
// 3、2执行方法
// List<Brand> brands = brandMapper.selectByConditionSingle(status, companyName, brandName);
List<Brand> brands = brandMapper.selectByConditionSingle(brand);
System.out.println(brands);
// 4、释放资源
sqlSession.close();
}
@Test
public void testAdd() throws IOException {
//设置参数
int status=1;
String companyName="波导手机";
String brandName="波导002";
String description = "手机中的战斗机!";
int ordered = 100;
//封装对象
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);
brand.setDescription(description);
brand.setOrdered(ordered);
//封装Map对象
// Map map = new HashMap();
// map.put("status", status);
// map.put("companyName", companyName);
// map.put("brandName", brandName);
//1、加载核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2、获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
// 2、1是否开启事务(不填则为false-开启事物,需要commit)(flase,则需要commit提交;true,则自动提交)
// SqlSession sqlSession = sqlSessionFactory.openSession(true);
// 3、1获取UserMapper接口代理的对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
// 3、2执行方法,添加记录没有返回值
brandMapper.add(brand);
// 3、3提交事务才能保存在数据库中(若开启了事务,必须执行commit);XML里设置useGeneratedKeys="true" keyProperty="id",才可以拿到返回值id
sqlSession.commit();
Integer id = brand.getId();
System.out.println(id);
// 4、释放资源
sqlSession.close();
}
@Test
public void testUpdate() throws IOException {
//设置参数
int status=0;
// String companyName="波导手机";
// String brandName="波导1";
// String description = "波导手机,手机中的战斗机";
int ordered = 400;
int id = 9;
//封装测试的参数对象
Brand brand = new Brand();
brand.setStatus(status);
// brand.setCompanyName(companyName);
// brand.setBrandName(brandName);
// brand.setDescription(description);
brand.setOrdered(ordered);
brand.setId(id);
//封装Map对象
// Map map = new HashMap();
// map.put("status", status);
// map.put("companyName", companyName);
// map.put("brandName", brandName);
//1、加载核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2、获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3、1获取UserMapper接口代理的对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
// 3、2执行方法,添加记录没有返回值
int count = brandMapper.update(brand);
// 3、3提交事务才能保存在数据库中(若开启了事务,必须执行commit)
sqlSession.commit();
System.out.println(count);
// 4、释放资源
sqlSession.close();
}
@Test
public void testDeleteById() throws IOException {
//设置参数
int id = 10;
//1、加载核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2、获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3、1获取UserMapper接口代理的对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
// 3、2执行方法,删除没有返回值
brandMapper.deleteById(id);
// 3、3提交事务才能保存在数据库中(若开启了事务,必须执行commit)
sqlSession.commit();
// System.out.println(count);
// 4、释放资源
sqlSession.close();
}
@Test
public void testDeleteByIds() throws IOException {
//接受参数
int[] ids = {11,12};
//1、加载核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2、获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3、1获取UserMapper接口代理的对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
// 3、2执行方法,删除没有返回值
brandMapper.deleteByIds(ids);
// 3、3提交事务才能保存在数据库中(若开启了事务,必须执行commit)
sqlSession.commit();
// System.out.println(count);
// 4、释放资源
sqlSession.close();
}
}