create database db_mybatis;
use db_mybatis;
drop table if exists person;
create table if not exists person
(
id int primary key auto_increment,
name varchar(10) not null comment '姓名',
age tinyint not null comment '年龄',
sex char(1) default '男' comment '性别',
id_card char(18) not null unique comment '身份证'
);
insert into person(name, sex, age, id_card)
values ('陆小凤', '男', 23, '100001'),
('上官飞燕', '女', 18, '100002'),
('西门吹雪', '男', 25, '100003'),
('沙曼', '女', 21, '100004'),
('花满楼', '男', 21, '100005');
select *
from person;
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.6version>
dependency>
<dependency>
<groupId>com.mysqlgroupId>
<artifactId>mysql-connector-jartifactId>
<version>8.0.33version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13.2version>
<scope>testscope>
dependency>
dependencies>
Person
public class Person {
private int id;
private String name;
private String sex;
private Integer age;
private String idCard;
// 忽略了 构造方法和get、set方法
}
以后在这个接口里面,添加增删改查的方法
package com.test.mapper;
/**
* 接口代理
*/
public interface PersonMapper {
/**
* ====== 查找
*/
List<Person> selectAll();
}
这个需要在
resources
资源文件下,并且需要跟上面的那个PersonMapper
接口保持一样的包名,所以需要先在资源文件下创建同级目录
注意
在资源文件下创建多级文件夹,不能使用`.`了,需要使用`/`才能创建成功
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.test.mapper.PersonMapper">
<resultMap id="personResultMap" type="Person">
<result column="id_card" property="idCard"/>
resultMap>
mapper>
mybatis-config.xml
配置文件在 resources 文件夹下创建 mybatis-config.xml
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias type="com.test.pojo.Person" alias="Person"/>
typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///db_mybatis?useServerPrepStmts=true"/>
<property name="username" value="root"/>
<property name="password" value="root1234"/>
dataSource>
environment>
environments>
<mappers>
<package name="com.test.mapper"/>
mappers>
configuration>
// 测试查询所有
@Test
public void testSelectAll() throws IOException {
SqlSession sqlSession = getSqlSession();
PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
List<Person> list = personMapper.selectAll();
System.out.println(list);
// 释放资源
sqlSession.close();
}
getSqlSession()的代码如下
public SqlSession getSqlSession() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
return sqlSessionFactory.openSession(true);
}
PersonMapper.java
中添加如下代码Person selectById(int id);
PersonMapper.xml
中添加如下代码<mapper namespace="com.test.mapper.PersonMapper">
...
<select id="selectById" resultMap="personResultMap">
select *
from person
where id = #{id}
select>
mapper>
@Test
public void testSelectById() throws IOException {
SqlSession sqlSession = getSqlSession();
PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
// 这里的id,后续是从外面传过来的
int id = 4;
Person p = personMapper.selectById(id);
System.out.println(p.toString());
// 释放资源
sqlSession.close();
}
主要是练习 mybatis的动态sql里的
where
和if
标签
PersonMapper.java
中添加如下代码// 方式1 多个参数,使用@Param注解
// List selectByCondition(@Param("name") String name, @Param("age") int age, @Param("idCard") String idCard);
// 方式2:通过map传参
// List selectByCondition(Map map);
// 方式3:通过对象传参
List<Person> selectByCondition(Person person);
PersonMapper.xml
中添加如下代码<mapper namespace="com.test.mapper.PersonMapper">
...
<select id="selectByCondition" resultMap="personResultMap">
select *
from person
<where>
<if test="name !=null and name != ''">
and name = #{name}
if>
<if test="age !=null">
and age = #{age}
if>
<if test="idCard !=null and idCard != ''">
and id_card = #{idCard}
if>
where>
select>
mapper>
@Test
public void testSelectByCondition() throws IOException {
SqlSession sqlSession = getSqlSession();
PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
// 方式1
// List list = personMapper.selectByCondition("陆小凤", 23, "100001");
// System.out.println(list);
// 方式2
// Map map = new HashMap<>();
// map.put("name", "陆小凤");
// map.put("age", 23);
// map.put("idCard", "100001");
// List list = personMapper.selectByCondition(map);
// System.out.println(list);
// 方式3
Person person = new Person();
// person.setName("陆小凤");
person.setAge(23);
// person.setIdCard("100001");
List<Person> list = personMapper.selectByCondition(person);
System.out.println(list);
sqlSession.close();
}
主要是练习 mybatis的动态sql里的
when
和choose
标签
PersonMapper.java
中添加如下代码// 这里传参方式跟selectByCondition一样也有三种
List<Person> selectByConditionSingle(Person person);
PersonMapper.xml
中添加如下代码<mapper namespace="com.test.mapper.PersonMapper">
...
<select id="selectByConditionSingle" resultMap="personResultMap">
select *
from person
<where>
<choose>
<when test="name != null and name != ''">
name = #{name}
when>
<when test="age != null">
age = #{age}
when>
<when test="idCard !=null and idCard != ''">
id_card = #{idCard}
when>
choose>
where>
select>
mapper>
@Test
public void testSelectByConditionSingle() throws IOException {
SqlSession sqlSession = getSqlSession();
PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
Person person = new Person();
person.setIdCard("100004");
// person.setAge(23);
// person.setName("花满楼");
List<Person> list = personMapper.selectByConditionSingle(person);
System.out.println(list);
sqlSession.close();
}
PersonMapper.java
中添加如下代码void add(Person p);
PersonMapper.xml
中添加如下代码<mapper namespace="com.test.mapper.PersonMapper">
...
<insert id="add" useGeneratedKeys="true" keyProperty="id">
insert into person(name, age, sex, id_card)
values (#{name}, #{age}, #{sex}, #{idCard})
insert>
mapper>
@Test
public void testAdd() throws IOException {
SqlSession sqlSession = getSqlSession();
PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
Person person = new Person("王五", "女", 32, "300010");
personMapper.add(person);
System.out.println("id:" + person.getId());
sqlSession.close();
}
主要是练习 mybatis的动态sql里的
set
标签
PersonMapper.java
中添加如下代码int updateById(Person p);
PersonMapper.xml
中添加如下代码<mapper namespace="com.test.mapper.PersonMapper">
...
<update id="updateById">
update person
<set>
<if test="name != null and name != ''">
name = #{name},
if>
<if test="age != null">
age = #{age},
if>
<if test="idCard != null and idCard != ''">
id_card = #{idCard},
if>
set>
where id = #{id}
update>
mapper>
@Test
public void testUpdateById() throws IOException {
SqlSession sqlSession = getSqlSession();
PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
Person person = new Person();
person.setId(12);
person.setAge(88);
person.setIdCard("aaaaaa");
personMapper.updateById(person);
sqlSession.close();
}
PersonMapper.java
中添加如下代码void deleteById(int id);
PersonMapper.xml
中添加如下代码<mapper namespace="com.test.mapper.PersonMapper">
...
<delete id="deleteById">
delete
from person
where id = #{id}
delete>
mapper>
@Test
public void testDeleteById() throws IOException {
SqlSession sqlSession = getSqlSession();
PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
personMapper.deleteById(10);
sqlSession.close();
}
主要是为了练习mybatis 的动态sql里的
foreach
标签
PersonMapper.java
中添加如下代码// void deleteByIds(int[] ids);
void deleteByIds(@Param("ids") int[] ids);;
PersonMapper.xml
中添加如下代码<mapper namespace="com.test.mapper.PersonMapper">
...
<delete id="deleteByIds">
delete
from person
where id in
<foreach collection="ids" item="id" open="(" close=")" separator=",">
#{id}
foreach>
delete>
mapper>
@Test
public void testDeleteByIds() throws IOException {
SqlSession sqlSession = getSqlSession();
PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
personMapper.deleteByIds(new int[]{6, 7});
sqlSession.close();
}
1. 黑马程序员JavaWeb基础教程
2. MyBatis官网