09 mybatis中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的使用过程。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值