初学Mybatis之 CRUD 增删改查

namespace 中的包名要和 Dao/Mapper 接口的包名一致

select:选择,查询语句

同理,还有 insert、update、delete 标签

id:对应的 namespace 中的方法名

resultType:sql 语句执行的返回值

parameterType:参数类型

先在 mysql 建表(id、name、pwd)

配置 Maven 环境(mysql、mybatis、junit)

MybatisUtils.java:

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

public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

        /*
        有了SqlSessionFactory,就可以获得SqlSession的实例
        SqlSession提供了在数据库执行SQL命令所需的所有方法
        可以通过SqlSession实例来执行已映射的SQL语句
         */
        public static SqlSession getSqlSession(){
            return sqlSessionFactory.openSession();
        }
}

mybatis-config.xml:(resources 目录下)

<?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核心配置文件 -->
<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://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 每一个Mapper.xml都需要在Mybatis核心配置文件中注册 -->
    <mappers>
        <mapper resource="com/demo/dao/UserMapper.xml"/>
    </mappers>

</configuration>

 User.java:

package com.demo.pojo;
//实体类
public class User {
    private int id;
    private String name;
    private String pwd;

    //无参构造
    public User() {
    }

    //有参构造
    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    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 getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

UserMapper 接口:

package com.demo.dao;

import com.demo.pojo.User;

import java.util.List;

public interface UserMapper {

    //查询全部用户
    List<User> getUserList();

    //根据ID查询用户
    User getUserById(int id);

    //insert插入用户
    int addUser(User user);

    //update修改用户
    int updateUser(User user);

    //delete删除用户
    int deleteUser(int id);
}

UserMapper.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.demo.dao.UserMapper">

    <!-- select 查询语句 -->
    <select id="getUserList" resultType="com.demo.pojo.User">
        select * from mybatis.user
    </select>

    <select id="getUserById" parameterType="int" resultType="com.demo.pojo.User">
        select * from mybatis.user where id = #{id}
    </select>

    <!-- insert插入数据,对象中的属性可以直接取出来 -->
    <insert id="addUser" parameterType="com.demo.pojo.User">
        insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd});
    </insert>

    <!-- update更新数据 -->
    <update id="updateUser" parameterType="com.demo.pojo.User">
        update mybatis.user set name = #{name}, pwd = #{pwd} where id = #{id};
    </update>

    <!-- delete删除数据 -->
    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id = #{id};
    </delete>

</mapper>

UserDaoTest.java:(test 目录下)

package com.demo.dao;

import com.demo.pojo.User;
import com.demo.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserDaoTest {

    //查询全部
    @Test
    public void test(){

        //获得SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUserList();

        for(User user : userList){
            System.out.println(user);
        }

        //关闭sqlSession
        sqlSession.close();
    }

    //根据id查询
    @Test
    public void getUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = mapper.getUserById(1);

        System.out.println(user);

        sqlSession.close();
    }

    //增删改需要提交事务
    //添加数据
    @Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        mapper.addUser(new User(4, "张三4", "123"));

        //提交事务
        sqlSession.commit();

        sqlSession.close();
    }

    //修改数据
    @Test
    public void updateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        mapper.updateUser(new User(4,"李四","111"));

        sqlSession.commit();

        sqlSession.close();
    }

    //删除数据
    @Test
    public void deleteUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        mapper.deleteUser(4);

        sqlSession.commit();

        sqlSession.close();
    }
}

总结:

1.编写接口

2.编写对应的 Mapper 中的 sql 语句

3.测试

select:

    <select id="getUserById" parameterType="int" resultType="com.demo.pojo.User">
        select * from mybatis.user where id = #{id}
    </select>

 insert:

    <insert id="addUser" parameterType="com.demo.pojo.User">
        insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd});
    </insert>

update:

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

delete:

    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id = #{id};
    </delete>

注意:增删改需要提交事务 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值