MyBatis(2)CRUD操作

1.使用MyBatis对表执行CRUD操作——基于XML的实现

增删改查

Mapper接口本质就是原来的Dao接口,只是为了方便我们的书写。一个mapper接口对应一个mapper映射文件。

将UserMapper更名为UserDao,说明本质

修改对应的mapper映射文件的namespace属性,对应上接口。

创建数据库

CREATE DATABASE /*!32312 IF NOT EXISTS*/`mybatis` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `mybatis`;

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `id` INT(20) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  `pwd` VARCHAR(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT  INTO `user`(`id`,`name`,`pwd`) VALUES (1,'小二','123456'),(2,'张三','abcdef'),(3,'李四','987654');

创建的数据库表

在这里插入图片描述

创建Maven项目

pom.xml


<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.0modelVersion>

    <groupId>com.kscnggroupId>
    <artifactId>ssm-mybatis-studyartifactId>
    <packaging>pompackaging>
    <version>1.0-SNAPSHOTversion>
    
    <modules>
        <module>mybatis01module>
        <module>mybatis02module>//本文所创建的Macen项目
        <module>mybatis03module>
        <module>mybatis04module>
        <module>mybatis05module>

    modules>

    <dependencies>

        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.11version>
        dependency>

        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.1version>
        dependency>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.47version>
        dependency>

        
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.17version>
        dependency>

    dependencies>


    <build>
        
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
            <resource>
                <directory>src/main/resourcesdirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
        resources>

    build>



project>

编写实体类User

package com.kscng.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 + '\'' +
                '}';
    }
}

编写mybatis配置文件mybatis-config.xml



<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=true&useUnicode=true&characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            dataSource>
        environment>
    environments>

    <mappers>
        <mapper resource="com/kscng/dao/userMapper.xml"/>
    mappers>

configuration>

工具类MyBatisUtils

package com.kscng.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

//mybatis的工具类,重复的代码的提纯
public class MyBatisUtils {
//类变量不需要设置默认值;
private static SqlSessionFactory sqlSessionFactory;

static {

    //在maven中,所有的资源文件一般都放在resourc目录下,我们可以直接拿到。
    try{
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
//设置SqlSessionFactroy公共的方法
public static SqlSessionFactory getSqlSessionFactory(){
    return sqlSessionFactory;
}
}

编写接口UserDao

package com.kscng.dao;

import com.kscng.pojo.User;

import java.util.List;

public interface UserDao {
    //获取全部的用户
    List<User> selectUser();

    //根据id查找用户
    User selectUserByID(int id);

    //添加一个用户
    int addUser(User user);

    //删除用户
    int deletUserById(int id);

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

对应的userMapper.xml






<mapper namespace="com.kscng.dao.UserDao">
    
    <select id="selectUser" resultType="com.kscng.pojo.User">
            select * from user
    select>
<select id="selectUserById" resultType="com.kscng.pojo.User">
    select *from user where id = #{id}
select>

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

<delete id="deleteUserBYID" parameterType="int">
    delete from user where id = #{id}
delete>

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

测试

package com.kscng.dao;

import com.kscng.pojo.User;
import com.kscng.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;

import java.util.List;

public class UserMapperTest {
//(1)获取全部的用户
    @Test
    public void selectUser(){

        //1.拿到sqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = MyBatisUtils.getSqlSessionFactory();
        //2.通过sqlSessionFactory对象openSession()创建一个sqlSession。
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.通过sqlSession获得mapper对象,参数为映射文件对应的接口类的class对象
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        //4.通过mapper对象来执行操作;
        List<User> users = mapper.selectUser();

        //获得结果集
        for (User user : users){
            System.out.println(user);
        }
        sqlSession.close();//关闭sqlSession
    }
    //(2)根据id查找用户
    @Test
    public void selectUserById(){
        SqlSessionFactory sqlSessionFactory = MyBatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        //接口  对象名  = new  接口实现类
        User user = mapper.selectUserByID(2);
        System.out.println(user);

        sqlSession.close(); //关闭sqlSession
    }
    //(3)添加一个用户
    @Test
    public void addUser(){
        User user = new User(4,"卡卡","kaka");
        SqlSessionFactory sqlSessionFactory = MyBatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);

        int i = mapper.addUser(user);

        //没有插入成功的原因:没有提交事务;
        sqlSession.commit(); //提交事务
        sqlSession.close(); //关闭sqlSession

        if (i>0){
            System.out.println("插入成功!");
        }
    }
      //(4)修改用户信息
    @Test
    public void updateUser(){
        SqlSession sqlSession = MyBatisUtils.getSqlSessionFactory().openSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        User user = new User(1,"阿狗","dog");
        mapper.updateUser(user);
        System.out.println(i);
        sqlSession.commit();//提交事务
        sqlSession.close();//关闭sqlSession
          if (i>0){
            
            System.out.println("修改成功!");
        }
    }
        }
    //(5)删除用户
    @Test
    public void deleteUserById(){
        SqlSession sqlSession = MyBatisUtils.getSqlSessionFactory().openSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        int i = mapper.deletUserById(2);
       System.out.println(i);
        //记得提交事务,否则删除不成功!
        sqlSession.commit();//提交事务
        sqlSession.close();//关闭sqlSession

        if (i>0){
            
            System.out.println("删除成功!");
        }
    }
}

结果展示

(1)获取全部的用户

MyBatis(2)CRUD操作_第1张图片

(2)根据id查找用户

MyBatis(2)CRUD操作_第2张图片

(3)添加一个用户

MyBatis(2)CRUD操作_第3张图片

在获取一次全部用户查看成果

MyBatis(2)CRUD操作_第4张图片

(4)修改用户信息

MyBatis(2)CRUD操作_第5张图片

(5)删除用户

MyBatis(2)CRUD操作_第6张图片

在获取一次全部用户查看成果

MyBatis(2)CRUD操作_第7张图片

项目结构

MyBatis(2)CRUD操作_第8张图片

2.CRUD注意点

1、事务

增,改,删需要提交事务!

增,改,删需要提交事务!

增,改,删需要提交事务!

重要的事说三遍!

2、乱码

如果出现乱码,先在sql中进行测试,sql没问题,就检查配置文件

jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf-8"

3、参数问题

如果是基本数据类型,可以省略,但建议写上

引用类型必须写指定的 包名+类名。

你可能感兴趣的:(MyBatis(2)CRUD操作)