MyBatis增删改查配置和使用
0.表结构,目录结构
1.配置pom.xml
代码语言:javascript复制<?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>cn.qkongtao</groupId>
<artifactId>MyBatis_crud</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</project>
2. mybatis的主配置文件 SqlMapConfig.xml
代码语言:javascript复制<?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">
<!-- mybatis的主配置文件 -->
<configuration>
<!-- 配置环境 -->
<environments default="mysql">
<!-- 配置mysql的环境-->
<environment id="mysql">
<!-- 配置事务的类型-->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置数据源(连接池) -->
<dataSource type="POOLED">
<!-- 配置连接数据库的4个基本信息 -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/eesy"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
<mappers>
<mapper resource="dao/IUserDao.xml"/>
</mappers>
<!--起别名,可以不用谢写全限定类名-->
<typeAliases>
<typeAlias type="domain.User" alias="user"></typeAlias>
</typeAliases>
</configuration>
3. 用到的javaBean封装类
User.java
代码语言:javascript复制package domain;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable{
private Integer id;
private String name;
private Date birthday;
private String sex;
private int age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{"
"id=" id
", name='" name '''
", birthday=" birthday
", sex='" sex '''
", age=" age
'}';
}
}
QueryVo.java
代码语言:javascript复制package domain;/*
*Created by tao on 2020-03-26.
*/
import java.util.List;
public class QueryVo {
private User user;
private List<Integer> ids;
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
4. 用户的持久层接口 dao
IUserDao.java
代码语言:javascript复制package dao;
import domain.QueryVo;
import domain.User;
import java.util.List;
/**
* 用户的持久层接口
*/
public interface IUserDao {
/**
* 查询所有操作
*
* @return
*/
List<User> findAll();
/**
* 保存用户
*
* @param user
*/
void saveUser(User user);
/**
* 更新用户
*
* @param user
*/
void updateUser(User user);
/**
* 根据Id删除用户
*
* @param userId
*/
void deleteUser(Integer userId);
/**
* 根据id查询用户信息
*
* @param userId
* @return
*/
User findById(Integer userId);
/**
* 根据名称模糊查询用户信息
*
* @param username
* @return
*/
List<User> findByName(String username);
/**
* 查询总用户数
*
* @return
*/
int findTotal();
/**
* 根据queryVo中的条件查询用户
*
* @param
* @return
*/
List<User> findUserByVo(QueryVo vo);
/**
* 查询总记录数
*
* @param num
* @return
*/
List<User> findByLimit(Integer num);
/**
* 根据传入参数名称
*
* @param user 查询条件:有可能有用户名,有可能有性别,也有可可能有年龄,有可能都有,有可能都没有
* @return
*/
List<User> findUserByCondition(User user);
/**
* 根据QueryVo中的提供的Id集合查询用户信息
*
* @param vo
* @return
*/
List<User> findUserInIds(QueryVo vo);
}
5. 持久层 Dao 映射配置 IUserDao.xml
代码语言:javascript复制<?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="dao.IUserDao">
<!-- 配置 查询结果的列名和实体类的属性名的对应关系 -->
<resultMap id="userMap" type="user">
<!-- 主键字段的对应 -->
<id property="id" column="id"></id>
<!--非主键字段的对应-->
<result property="name" column="name"></result>
<result property="birthday" column="birthday"></result>
<result property="sex" column="sex"></result>
<result property="age" column="age"></result>
</resultMap>
<!-- 查询所有 -->
<select id="findAll" resultType="user">
<!--select id as userId,username as userName,address as userAddress,sex as userSex,birthday as userBirthday from user;-->
select * from user;
</select>
<!-- 保存用户 -->
<insert id="saveUser" parameterType="domain.User">
<!-- 配置插入操作后,获取插入数据的id -->
<!-- SELECT LAST_INSERT_ID() 即为获取最后插入的ID值 -->
<selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
select last_insert_id();
</selectKey>
insert into user(name,age,sex,birthday)values(#{name},#{age},#{sex},#{birthday});
</insert>
<!-- 更新用户 -->
<update id="updateUser" parameterType="domain.User">
update user set name=#{name},age=#{age},sex=#{sex},birthday=#{birthday} where id=#{id}
</update>
<!-- 删除用户-->
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from user where id = #{uid}
</delete>
<!-- 根据id查询用户 -->
<select id="findById" parameterType="INT" resultMap="userMap">
select * from user where id = #{uid}
</select>
<!-- 根据名称模糊查询 -->
<select id="findByName" parameterType="string" resultMap="userMap">
select * from user where name like #{name}
<!-- select * from user where username like '%${value}%'-->
</select>
<!-- 获取用户的总记录条数 -->
<select id="findTotal" resultType="int">
select count(id) from user;
</select>
<!-- 根据queryVo的条件查询用户 -->
<select id="findUserByVo" parameterType="domain.QueryVo" resultMap="userMap">
select * from user where name like #{user.name}
</select>
<!-- 获取用户的前几条数据 -->
<select id="findByLimit" parameterType="int" resultMap="userMap">
select * from user limit #{num}
</select>
<!--根据条件查询-->
<!--if语句-->
<!--<select id="findUserByCondition" resultMap="userMap" resultType="domain.User">
select * from user where 1 =1
<if test="name != null">
and name = #{name}
</if>
<if test="sex != null">
and sex = #{sex}
</if>
</select>-->
<!--where语句-->
<select id="findUserByCondition" resultMap="userMap" resultType="domain.User">
select * from user
<where>
<if test="name != null">
and name = #{name}
</if>
<if test="sex != null">
and sex = #{sex}
</if>
</where>
</select>
<!--根据QueryVo中的Id集合查询用户列表-->
<select id="findUserInIds" resultMap="userMap" parameterType="domain.QueryVo">
select * from user
<where>
<if test="ids != null and ids.size()>0">
<foreach collection="ids" open="and id in (" close=")" item="uid" separator=",">
#{uid}
</foreach>
</if>
</where>
</select>
</mapper>
6.测试类 MyBatisTest.java
代码语言:javascript复制package test;
import dao.IUserDao;
import domain.QueryVo;
import domain.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 org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author tao
* <p>
* 测试mybatis的crud操作
*/
public class MybatisTest {
private InputStream in;
private SqlSession sqlSession;
private IUserDao userDao;
@Before//用于在测试方法执行之前执行
public void init() throws Exception {
//1.读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.获取SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.获取SqlSession对象
sqlSession = factory.openSession();
//4.获取dao的代理对象
userDao = sqlSession.getMapper(IUserDao.class);
}
@After//用于在测试方法执行之后执行
public void destroy() throws Exception {
//提交事务
sqlSession.commit();
//6.释放资源
sqlSession.close();
in.close();
}
/**
* 测试查询所有
*/
@Test
public void testFindAll() {
//执行查询所有方法
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println(user);
}
}
/**
* 测试保存操作
*/
@Test
public void testSave() {
User user = new User();
user.setName("modify User property");
user.setAge(20);
user.setSex("男");
user.setBirthday(new Date());
System.out.println("保存操作之前:" user);
//5.执行保存方法
userDao.saveUser(user);
System.out.println("保存操作之后:" user);
}
/**
* 测试更新操作
*/
@Test
public void testUpdate() {
User user = new User();
user.setId(8);
user.setName("娜美");
user.setSex("女");
user.setAge(22);
user.setBirthday(new Date());
//5.执行保存方法
userDao.updateUser(user);
}
/**
* 测试删除操作
*/
@Test
public void testDelete() {
//5.执行删除方法
userDao.deleteUser(9);
}
/**
* 测试条件查询
*/
@Test
public void testFindOne() {
//5.执行查询一个方法
User user = userDao.findById(8);
System.out.println(user);
}
/**
* 测试模糊查询操作
*/
@Test
public void testFindByName() {
//5.执行查询一个方法
List<User> users = userDao.findByName("%罗%");
// List<User> users = userDao.findByName("王");
for (User user : users) {
System.out.println(user);
}
}
/**
* 测试查询总记录条数
*/
@Test
public void testFindTotal() {
//5.执行查询一个方法
int count = userDao.findTotal();
System.out.println(count);
}
/**
* 查询limit的数据
*/
@Test
public void findByLimit() {
//5.执行查询一个方法
List<User> users = userDao.findByLimit(3);
for (User user : users) {
System.out.println(user);
}
}
/**
* 测试使用QueryVo作为查询条件
*/
@Test
public void testFindByVo(){
QueryVo vo = new QueryVo();
User user = new User();
user.setName("%罗%");
vo.setUser(user);
//5.执行查询一个方法
List<User> users = userDao.findUserByVo(vo);
for(User u : users){
System.out.println(u);
}
}
/**
* 测试不确定条件查询
*/
@Test
public void testfindUserByCondition(){
User user = new User();
user.setName("KT");
user.setSex("boy");
List<User> users = userDao.findUserByCondition(user);
for(User u : users){
System.out.println(u);
}
}
/**
* 测试foreach标签的使用
*/
@Test
public void testfindInIds(){
QueryVo vo = new QueryVo();
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(4);
list.add(7);
vo.setIds(list);
List<User> users = userDao.findUserInIds(vo);
for(User u : users){
System.out.println(u);
}
}
}
7.总结
*该案例中演示了以下的操作 1. 查询所有 2. 保存用户 3. 更新用户 4. 删除用户 5. 根据id查询用户 6. 根据名称模糊查询 7. 获取用户的总记录条数 8. 根据queryVo的条件查询用户 9. 获取用户的前几条数据 10. 根据多条件查询 11. 根据QueryVo中的Id集合查询用户列表