mybatis-基于xml的crud

创建maven工程

mybatis-xml/
	|-src/
	|		|-main/
	|		|		|-java/
	|		|		|-resources/		
	|		|-test/
	|-pom.xml
  • mybatis-xml/:项目目录
  • mybatis-xml/src/:java类路径
  • mybatis-xml/src/main/:此处就是java代码,如pojo,mapper
  • mybatis-xml/src/resources/:此处存放mybatis-config.xml(mybatis主配置文件)和(jdbcConfig.properties数据库连接文件)...
  • mybatis-xml/src/test/:测试

添加依赖

在pom.xml文件中,添加需要的依赖

<?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-xml</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>9</maven.compiler.source>
        <maven.compiler.target>9</maven.compiler.target>
    </properties>

    <dependencies>
<!--    mybatis 核心依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
<!--		mysql8驱动依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
<!--		junit4测试依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

创建pojo类

在main/java/中创建com/mybatis_xml/pojo/User类

main/java/com/mybatis_xml/pojo/User.class
package com.mybatis_xml.pojo;

public class User implements Serializable{//对应user表
    private Integer uid; //对应uid
    private String uname;//对应uname
    private String usex;//对应usex
    private Integer uage;//对应age

    public User() {
    }

    public User(Integer uid, String uname, String usex, Integer uage) {
        this.uid = uid;
        this.uname = uname;
        this.usex = usex;
        this.uage = uage;
    }

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public String getUsex() {
        return usex;
    }

    public void setUsex(String usex) {
        this.usex = usex;
    }

    public Integer getUage() {
        return uage;
    }

    public void setUage(Integer uage) {
        this.uage = uage;
    }

    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", uname='" + uname + '\'' +
                ", usex='" + usex + '\'' +
                ", uage=" + uage +
                '}';
    }
}

创建mapper接口

在main/java/中创建com/mybatis_xml/mapper/IUserMapper接口

main/java/com/mybatis_xml/mapper/IUserMapper.class
package com.mybatis_xml.mapper;

import com.mybatis_xml.pojo.User;

import java.util.List;

public interface IUserMapper {

    //查询所有
    List<User> findUserAll();
    //通过id查询
    User findUserById(Integer userId);
    //通过name查询
    List<User> findUserByName(String userName);
    //保存
    int saveUser(User user);
    //更新
    int updateUser(User user);
    //删除
    int deleteUser(Integer userId);
    //查询所有记录条数
    int findUserAllTotal();
}

创建映射配置文件

在main/resources中创建com/mybatis_xml/mapper/IUserMapper.xml,注意此文件需要与mapper接口同一级目录

main/resources/com/mybatis_xml/mapper/IUserMapper.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="com.mybatis_xml.mapper.IUserMapper">

    <select id="findUserAll" resultType="user">
        select * from user
    </select>

    <select id="findUserById" parameterType="int" resultType="user">
        select * from user where uid=#{uid}
    </select>

    <select id="findUserByName" parameterType="String" resultType="user">
        select * from user where uname like #{uname}
    </select>

    <insert id="saveUser" parameterType="user" >
        insert into user(uname,usex,uage) value (#{uname},#{usex},#{uage})
    </insert>

    <update id="updateUser" parameterType="user">
        update user set uname=#{uname},usex=#{usex},uage=#{uage} where uid=#{uid}
    </update>

    <delete id="deleteUser" parameterType="Integer">
        delete from user where uid=#{uid}
    </delete>

    <select id="findUserAllTotal" resultType="Integer">
        select count(*) from user
    </select>
</mapper>
  • 标签:namespace命名空间为mapper的全限定类名。
  • 标签:进行增删改查的声明。
  • id属性:mapper接口中对应的函数名。
  • parameterType:mapper接口中对应函数的参数类型。如果配置了别名,就可以不用写全限定类名,只需要写类名的小写。对于java.lang包下的String,Integer可以写全限定类名也可以写类名。
  • resultType:mapper接口中对应函数的返回值类型。如果是集合,那么就是泛型的类型。
  • uid=#{uid}:左边的是数据库中的字段名称,右边的是bean/User.class下的成员变量名称。并且定义pojo时,必须成员变量名称和数据库字段名称一一对应,如数据库字段为user_id,那么成员变量名称就是userId。
  • 当我们需要对数据库进行增删改时,必须要提交事物(session.comit())

创建主配置文件

在resources中创建mybatis-config.xml和jdbcConfig.properties

resources/mybatis-config.xml
resources/jdbcConfig.properties
<?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>
<!--    配置数据库连接-->
    <properties resource="jdbcConfig.properties"></properties>
<!--    配置别名-->
    <typeAliases>
        <package name="com.mybatis_xml.pojo"/>
    </typeAliases>
<!--    配置环境-->
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
<!--    配置映射文件-->
    <mappers>
        <package name="com.mybatis_xml.mapper"/>
    </mappers>
</configuration>
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
jdbc.username=root
jdbc.password=root

创建测试类

在test/java中创建TestDemo.class

test/java/TestDemo.class
import com.mybatis_xml.mapper.IUserMapper;
import com.mybatis_xml.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 org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestDemo {
    private InputStream is;
    private SqlSession session;
    private SqlSessionFactoryBuilder sqlSessionFactoryBuilder;
    private SqlSessionFactory factory;
    private IUserMapper userMapper;

    @Before //测试方法执行前执行
    public void init() throws IOException{
        String resource = "mybatis-config.xml";
        // 读取mybatis配置文件
        is = Resources.getResourceAsStream(resource);
        // 创建构造者对象
        sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        // 创建工厂对象
        factory = sqlSessionFactoryBuilder.build(is);
        // 创建SqlSession对象
        session = factory.openSession();
        // 创建IUserMapper对象
        userMapper = session.getMapper(IUserMapper.class);
    }
    @After //测试方法执行完成后执行
    public void destory() throws IOException {
      	// 当进行增删改时提交事物
        session.commit();
      	// 关闭SqlSession对象
        session.close();
      	// 关闭InputStream对象
        is.close();
    }

    //测试查询所有
    @Test
    public void testFindUserAll() throws IOException {
       List<User> users = userMapper.findUserAll();
        for (User u:users) {
            System.out.println(u);
        }
    }
    //测试通过id查询
    @Test
    public void testFindUserById(){
        User user = userMapper.findUserById(3);
        System.out.println(user);
    }

    //测试通过name进行模糊查询
    @Test
    public void testFindUserByName(){
        List<User> users = userMapper.findUserByName("%x%");
        for (User u:users) {
            System.out.println(u);
        }
    }

    //保存
    @Test
    public void testSaveUser(){
        User user = new User();
        user.setUname("Java");
        user.setUsex("nan");
        user.setUage(23);
        userMapper.saveUser(user);
    }

    //更新
    @Test
    public void testUpdateUser(){
        User user = new User();
        user.setUid(3);
        user.setUname("python");
        user.setUsex("nx");
        user.setUage(23);
       userMapper.updateUser(user);
    }

    //删除
    @Test
    public void testDeleteUser(){
        userMapper.deleteUser(13);
    }

    //所有记录条数
    @Test
    public void testFindUserAllTotal(){
        int total = userMapper.findUserTotal();
        System.out.println(total);
    }
}

上一篇:别再抱怨缺乏算法实践场景,不妨来挑战这场百万奖池的比赛!


下一篇:个人简介