Mybatis笔记--简单的CRUD操作

Mybatis笔记–简单的CRUD操作

一些概念

数据持久层与数据持久化
  • 持久化是将程序数据由瞬时状态和持久状态之间的转化,也就是把数据保存起来,存在库中
  • 完成持久化的代码层–DAO层(Data Access Object)数据访问对象),为了操作数据库而存在
Maven
  • 管理jar包的工具,使用pom.xml文件来控制包的导入和删除等等,非常非常方便
Mybatis架构图

Mybatis CRUD的实现

导入jar包
<?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-study</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>Mybatis-01</module>
    </modules>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <!--  Mybatis的jar包      -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
         <!--  junit测试的包     -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
         <!--  mysql数据库连接的包     -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
    </dependencies>
</project>
  • 注意这里的编码问题,默认的写的是encoding="UTF-8",但是这样不能使用中文,要改为encoding="utf-8"
编写核心配置文件
<?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://127.0.0.1:3306/mybatis?useSSL=true&amp;useUnicode&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="rootroot"/>
            </dataSource>
        </environment>
    </environments>
<!--    dao层映射文件-->
    <mappers>
        <mapper resource="com/test/dao/TeacherMapper.xml"/>
    </mappers>
</configuration>
构建MyBatis工具类
package com.test.utils;

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.InputStream;
import java.io.IOException;

/**
 * @program: Mybatis-study
 * @description:
 * @author: Morii
 * @create: 2022-09-21 21:45
 **/
//sqlsessionFactory -->sqlSession
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory ;
    static
    {
        try {
            //使用Mybatis第一步:获取sqlSessionFactory对象,字如其名,工厂
            String resource = "mybatis-config.xml";
            //读取数据流
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    //SqlSession里有sql执行的所有方法,返回一个对象来对数据库进行操作
    public static SqlSession getSqlSession()
    {
        return sqlSessionFactory.openSession();
    }
}

创建实体类
  • 这里就举个例子,get和set,toString方法都写好
package com.test.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @program: Mybatis-study
 * @description: 实体类
 * @author: Morii
 * @create: 2022-09-23 10:38
 **/
//@Data
//@AllArgsConstructor
//@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public User(int id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}
编写Mapper接口类
  • 写在DAO层里
package com.test.dao;

import com.test.pojo.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
import java.util.Map;

/**
 * @program: Mybatis-study
 * @description: Dao接口
 * @author: Morii
 * @create: 2022-09-23 10:43
 **/
public interface UserMapper {
    List<User> getUserList();
    //根据id查询
    User getUserById(int id);
    //参数比较少的时候用@Param注解标注来传递即可,多了就用Map
    User selectUserByNP(@Param("username") String username,@Param("pwd") String pwd);
    int addUser(User user);
    int updateUser(User user);
    int deleteUser(int id);
    int addUser2(Map<String,Object> map);
    List<User> getUserByLimit(Map<String,Object> map);

//    //查
//    @Select("select * from user where id=#{id}")
//    User getUserByID(@Param("id")int id);
//
//    //增
//    @Select("insert into user(id,name,pwd) values (#{id},#{name},#{password})")
//    Integer  addUsers(User user);
//
//    //删
//    @Delete("Delete from user where id=#{id}")
//    Integer deleteUsers(@Param("id")int id);
//
//    //改
//    @Update("Update user set name=#{name},pwd=#{password} where id=#{id}")
//    Integer updateUsers(User user);
}
编写Mapper.xml配置文件
  • 此配置文件里写sql语句,数据返回格式等等,也就取代了实现接口的Impl
  • 写到资源文件resources的下面,包的格式和java包里的的一样
  • 注意增删改要提交事务
<?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,这里一定不能写错-->
<mapper namespace="com.test.dao.UserMapper">

    <!--select id=接口名 resultType=返回格式"-->
    <select id="getUserList" resultType="com.test.pojo.User">
        select * from mybatis.user
    </select>

    <resultMap id="UserMap" type="com.test.pojo.User">
        <result column="id" property="id" />
        <result column="name" property="name" />
        <result column="pwd" property="password" />
    </resultMap>

    <!--parameterType参数返回类型 返回格式,这里应用定义好了的Map-->
    <select id="getUserById" parameterType="int" resultMap="UserMap">
        select * from mybatis.user where id=#{id}
    </select>
 	<!--模糊搜索:select * from mybatis.user where name like "%"#{value}"%"-->
    
    <insert id="addUser" parameterType="com.test.pojo.User">
        insert into mybatis.user (id ,name ,pwd) values (#{id},#{name},#{pwd})
    </insert>
    <!--map版本-->
    <insert id="addUser2" parameterType="map">
        insert into mybatis.user (id,name,pwd) values (#{userid},#{username},#{userpwd})
    </insert>

    <update id="updateUser" parameterType="com.test.pojo.User">
        update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id}
    </update>

    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where  id=#{id}
    </delete>
 	<!--分页-->
    <select id="getUserByLimit" parameterType="map" resultMap="UserMap">
        select * from  mybatis.user limit #{startIndex},#{pageSize}
    </select>
</mapper>

测试
  • 到此位置Mybatis的CURD就差不多了,接下来就是使用的代码了
package com.test.dao;

import com.test.pojo.Student;
import com.test.pojo.Teacher;
import com.test.pojo.User;
import com.test.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.Test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: Mybatis-study
 * @description:
 * @author: Morii
 * @create: 2022-09-23 11:00
 **/
public class UserMapperTest {
    static Logger logger=Logger.getLogger(UserMapperTest.class);
    //查询全部
    @Test
    public void test1()
    {
        //获得SqlSession对象
        SqlSession sqlSession= MybatisUtils.getSqlSession();
        //getMapper
        //拿到通过xml获取的实例,使用了反射
        UserMapper userMapper =sqlSession.getMapper(UserMapper.class);
        //拿到的数据放进List里
        List<User> userList= userMapper.getUserList();
        //输出
        for(User user:userList)
        {
            System.out.println(user);
        }
        //关闭
        sqlSession.close();
    }
    
    //根据id查
    @Test
    public void test2()
    {
        SqlSession sqlSession=MybatisUtils.getSqlSession();
        UserMapper userMapper =sqlSession.getMapper(UserMapper.class);
        User user= userMapper.getUserById(1);
        System.out.println(user);
    }
    //插入用户
    @Test
    public void test3()
    {
        SqlSession sqlSession=MybatisUtils.getSqlSession();
        UserMapper mapper=sqlSession.getMapper(UserMapper.class);
        //插入信息
        int res=mapper.addUser(new User(2,"曾书书","haohaohao"));
        if(res>0)
        {
            System.out.println("插入成功");
        }
        
        //提交事务
        sqlSession.commit();
        sqlSession.close();

    }
    //插入用户 Map版本
    @Test
    public void test33()
    {
        SqlSession sqlSession=MybatisUtils.getSqlSession();
        UserMapper mapper=sqlSession.getMapper(UserMapper.class);
        Map<String,Object> map=new HashMap<>();
        //插入信息
        map.put("userid",5);
        map.put("username","齐昊");
        map.put("userpwd","ahahhaha");
        int res=mapper.addUser2(map);
        if(res>0)
        {
            System.out.println("插入成功");
        }
        //提交事务
        sqlSession.commit();
        sqlSession.close();

    }
    //更新信息
    @Test
    public void test4()
    {
        SqlSession sqlSession=MybatisUtils.getSqlSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        int res= userMapper.updateUser(new User(3,"陆雪琪","woaizhang"));
        if(res>0)
        {
            System.out.println("更新成功");
        }
        sqlSession.commit();
        sqlSession.close();
    }
    //删除用户
    @Test
    public void test5()
    {
        SqlSession sqlSession=MybatisUtils.getSqlSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        int res=userMapper.deleteUser(2);
        if(res>0)
        {
            System.out.println("删除成功");
        }
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    //分页查询
    public void test6()
    {
        SqlSession sqlSession=MybatisUtils.getSqlSession();
        UserMapper mapper=sqlSession.getMapper(UserMapper.class);
        Map<String,Object> map=new HashMap<>();
        map.put("startIndex",0);
        map.put("pageSize",2);
        List<User> userList=mapper.getUserByLimit(map);
        for (User user:userList)
        {
            System.out.println(user);
        }
        sqlSession.close();
    }

//      子查询思路:
//      1.先查学生,再查老师
//      2.然后将学生表里的tid绑定到Teacher对象,再使用getTeacher来查询老师表里的信息
    @Test
    public void test12()
    {
        SqlSession session=MybatisUtils.getSqlSession();
        StudentMapper mapper=session.getMapper(StudentMapper.class);
        List<Student> students=mapper.getStudents();
        for (Student student:students)
        {
            System.out.println("name:"+student.getName()+"\tTeacher_Name:"+student.getTeacher().getName());
        }
        session.close();
    }

//    嵌套查询思路:
//    1.sql语句正常写-->
//    2.Map里单独分出association 然后将对象对应的表要查出的属性做映射
    @Test
    public void test13()
    {
        SqlSession session=MybatisUtils.getSqlSession();
        StudentMapper mapper=session.getMapper(StudentMapper.class);
        List<Student> students=mapper.getStudents2();
        for (Student student:students)
        {
            System.out.println(student);
        }
        session.close();
    }

}

Maven静态资源过滤配置
  • pom文件里加上配置
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
    </build>
目录结构
   <include>**/*.xml</include>
                <include>**/*.properties</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <filtering>true</filtering>
            <includes>
                <include>**/*.xml</include>
                <include>**/*.properties</include>
            </includes>
        </resource>
    </resources>
</build>

> #### 目录结构

![](https://img-blog.csdnimg.cn/img_convert/9c5f6870d0239090fc4f93f71bdec6b1.png)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值