Mybatis学习

studentDao.addStudent(student);

student类代表着一行数据,也就是一个对象。studentDao则对应着底层的数据库定义如下

package com.yogurt.dao;

import com.yogurt.po.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.IOException;
import java.io.InputStream;
import java.util.List;

public class StudentDao {

    private SqlSessionFactory sqlSessionFactory;

    public StudentDao(String configPath) throws IOException {
        InputStream inputStream = Resources.getResourceAsStream(configPath);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    public List<Student> findAll() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<Student> studentList = sqlSession.selectList("findAll");
        sqlSession.close();
        return studentList;
    }

    public int addStudent(Student student) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        int rowsAffected = sqlSession.insert("insert", student);
        sqlSession.commit();
        sqlSession.close();
        return rowsAffected;
    }

    public int deleteStudent(int id) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        int rowsAffected = sqlSession.delete("delete",id);
        sqlSession.commit();
        sqlSession.close();
        return rowsAffected;
    }
}

mapper映射文件定义了操作数据库的方法。

全局配置文件沟通了数据库和mapper,而studentDao又沟通了上层的Java代码(student)和mapper。使得操作数据库就可以直接用studentDao了.

在mapper里的sql语句的where限制中,如果判断条件是string,那么就只能向下面这样的写法


 select * from `user` where user_name like '%${value}%';

 

posted @ 2021-07-06 15:03  ligyfalcon  阅读(34)  评论(0)    收藏  举报