美文网首页
09 mybatis中SqlSession的使用

09 mybatis中SqlSession的使用

作者: 张力的程序园 | 来源:发表于2020-08-22 18:26 被阅读0次

本文将阐述SqlSession的使用。

1、环境约束

  • win10 64位操作系统
  • idea2018.1.5
  • jdk-8u162-windows-x64
  • mybatis3.2.8
  • mysql 6.5

2、前提约束

3、操作步骤

  • 创建一个t_student
create table t_student(id int,name varchar(20));
insert into t_student(id,name) values(1,'ali');
insert into t_student(id,name) values(2,'xiaoli');
insert into t_student(id,name) values(3,'zhangli');
  • 确保包括net.wanho.entity.Student.java:
public class Student{
  private int id;
  private String name;
  ...
}
  • 确保UserMapper.java中包含以下内容:
Student getStudentById(int id);
List<Student> queryStudents(String name);
void updateStudent(Student student);
  • 确保UserMapper.xml中包含以下内容:
  <select id="getStudentById" resultType="net.wanho.pojo.Student">
    select * from t_student where id=#{id} and name=#{name}
  </select>

  <select id="queryStudents" resultType="net.wanho.pojo.Student">
    select * from t_student where name=#{name}
  </select>
  
  <update id="updateStudent" >
    update t_student set name=#{name} where id=#{id}
  </update >
  • 提供测试类TestSqlSession.java:
import net.wanho.pojo.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 java.io.Reader;
import java.util.List;

public class TestMybatis2 {
    public static void main(String[] args)throws Exception {
        String resource ="mybatis-config.xml";
        //获取到了上述配置文件的输入流
        Reader reader = Resources.getResourceAsReader(resource);
        SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        Student student = sqlSession.selectOne("net.wanho.mapper.StudentMapper.getStudentById",new Student(2,"xiaoli"));

        List<Student> list = sqlSession.selectList("net.wanho.mapper.StudentMapper.getStudentById",new Student(2,"xiaoli"));

        List<Student> list = sqlSession.selectList("net.wanho.mapper.StudentMapper.queryStudents","xiaoli");
        
       sqlSession.update("net.wanho.mapper.StudentMapper.updateStudent",new Student(2,"zhangli"))
       sqlSession.commit();
  }
}

以上就是mybatis中Sqlsession的使用过程。

相关文章

网友评论

      本文标题:09 mybatis中SqlSession的使用

      本文链接:https://www.haomeiwen.com/subject/ndgvjktx.html