Mybatis(二)mybatis实现增删改查(静态代理)

1、mybatis中的核心对象

  • Resources对象

  Mybatis中的一个类,用于读取mybatis的主配置文件。

InputStream in = Resources.getResourceAsStream("mybatis.xml");
  • SqlSessionFactoryBuilder对象

  用于创建SqlSessionFactory对象。

SqlSessionFactoryBuilder builder  = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);  
  • SqlSessionFactory对象

  是一个接口,用于获取Sqlession对象,由于程序创建一个对象耗时比较长,使用资源比较多,所以在整个项目中,有一个就够用了。

SqlSession sqlSession = factory.openSession();
//openSession()方法括号中参数值为true、false
//默认为false表示获取非自动提交事务的SqlSession
//true表示获取非自动提交事务的SqlSession
  • SqlSession对象

  该对象是一个接口,定义了操作数据的方法 例如 selectOne() , selectList(), insert(), update(), delete(), commit(), rollback()

  在执行完SQL语句之后,需要关闭,sqlSession.close();

2、使用mybatis实现增删改查(此处使用实现接口的方法)

  • 数据库表
  • 接口文件
package cn.krain.dao;

import cn.krain.domain.Student;
import java.util.List;

public interface StudentDao {
   

    List<Student> selectStudents();

    int insertStudent(Student student);

    int updateStudent(Student student);

    int deleteStudent(Student student);
}
  • SQL映射文件

  id值为接口文件中的方法名,用来映射对应方法 resultType为查询结果的类型。一个SQL映射文件对应一个接口文件,同时也对应这数据库中的一张表。

<?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="cn.krain.dao.StudentDao">

    <select id="selectStudents" resultType="cn.krain.domain.Student">
        select * from student order by id
    </select>

    <insert id="insertStudent">
        insert into student values (#{id},#{name},#{email},#{age})
    </insert>

    <update id="updateStudent">
        update student set age=#{age} where id = #{id}
    </update>

    <delete id="deleteStudent">
        delete from student where id = #{id}
    </delete>

</mapper>
  • Mybatis主配置文件
<?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>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <!--指定所使用的数据库-->
    <environments default="dbTest">

        <!--一个environment代表一个数据库-->
        <environment id="dbTest">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/user_test"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>

    </environments>

    <!--指定Sql映射文件(SQL Mapper)-->
    <mappers>
        <mapper resource="cn\krain\dao\StudentDao.xml"/>
    </mappers>
</configuration>
  • 实现接口的类

sqlSqssion通过sqlId,在映射文件中查找对应的sql语句并执行。

sqlId由接口全名与方法名的拼接而组成。

package cn.krain.dao.impl;

import cn.krain.dao.StudentDao;
import cn.krain.domain.Student;
import cn.krain.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import java.util.List;

public class StudentDaoImpl implements StudentDao {
   

    @Override
    public List<Student> selectStudents() {
   
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        //sql
        String sqlId = "cn.krain.dao.StudentDao"+"."+"selectStudents";
        
        List<Student> students = sqlSession.selectList(sqlId);
        sqlSession.close();
        return students;
    }

    @Override
    public int insertStudent(Student student) {
   
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        String sqlId = "cn.krain.dao.StudentDao.insertStudent";
        int num = sqlSession.insert(sqlId,student);
        sqlSession.commit();
        sqlSession.close();
        return num;
    }

    @Override
    public int updateStudent(Student student) {
   
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        String sqlId = "cn.krain.dao.StudentDao.updateStudent";
        int num = sqlSession.insert(sqlId,student);
        sqlSession.commit();
        sqlSession.close();
        return num;
    }

    @Override
    public int deleteStudent(Student student) {
   
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        String sqlId = "cn.krain.dao.StudentDao.deleteStudent";
        int num = sqlSession.insert(sqlId,student);
        sqlSession.commit();
        sqlSession.close();
        return num;
    }
}
  • Student数据类型
package cn.krain.domain;

public class Student {
   

    private Integer id;
    private String name;
    private String email;
    private Integer 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 String getEmail() {
   
        return email;
    }

    public void setEmail(String email) {
   
        this.email = email;
    }

    public Integer getAge() {
   
        return age;
    }

    public void setAge(Integer age) {
   
        this.age = age;
    }

    @Override
    public String toString() {
   
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}
  • MybatisUtil工具类

该类用于封装获取sqlSession的代码。

package cn.krain.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 MybatisUtil {
   
    private static SqlSessionFactory factory = null;
    static {
   
        String config = "mybatis.xml";
        try {
   
            //读取主配置文件
            InputStream in = Resources.getResourceAsStream(config);
            //为factory赋值
            factory = new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
   
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){
   

        SqlSession sqlSession = null;

        if (factory!=null){
   
            sqlSession = factory.openSession();     //非自动提交事务
        }
        return sqlSession;
    }
}
  • TestMybatis
package cn.krain;

import cn.krain.dao.StudentDao;
import cn.krain.dao.impl.StudentDaoImpl;
import cn.krain.domain.Student;
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.Test;

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

public class TestMybatis {
   
    @Test
    public void testSelectStudents(){
   
        StudentDao studentDao = new StudentDaoImpl();
        List<Student> studentList = studentDao.selectStudents();
        for (Student stu:studentList ) {
   
            System.out.println(stu);
        }
    }

    @Test
    public void testInsertStudent(){
   
        StudentDao dao = new StudentDaoImpl();
        Student student = new Student();
        student.setId(6);
        student.setName("花花");
        student.setEmail("8654@qq.com");
        student.setAge(21);
        int n = dao.insertStudent(student);
        System.out.println(n);
    }

    @Test
    public void testUpdateStudent(){
   
        StudentDao dao = new StudentDaoImpl();
        Student student = new Student();
        student.setId(4);
        student.setAge(10);
        int n = dao.updateStudent(student);
        System.out.println(n);
    }

    @Test
    public void testDeleteStudent(){
   
        StudentDao dao = new StudentDaoImpl();
        Student student = new Student();
        student.setId(2);
        int n = dao.deleteStudent(student);
        System.out.println(n);
    }
}
全部评论

相关推荐

10-15 16:27
门头沟学院 C++
LeoMoon:建议问一下是不是你给他付钱😅😅
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务