1.接口 StudentMapper
package com.tty.mybatis.dao;
import com.tty.mybatis.pojo.Student;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.Map;
public interface StudentMapper {
// 还可以这样写节省时间
@Select("select `id`,`name`,`student_sex` from student where `id` = #{id}")
//查询 id 查询学生
public Student retrieveStudentById(Integer id);
//增加
public void addStudent(Student student);
//更新
public void updateStudentName(Map map);
// 普通写法 :public void updateStudentName(@Param("id") Integer id, @Param("newName") String newName);
// 删除
public void deleteStudent(Integer id);
}
2.学生映射配置文件 StudentMapper.xml
3.测试类 TestStudent
import com.tty.mybatis.dao.StudentMapper;
import com.tty.mybatis.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 org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
import org.junit.Test;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class TestStudent {
@Test
public void test() {
SqlSession sqlSession=getSqlSession();
try {
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
//查询
Student student = mapper.retrieveStudentById(1);
System.out.println(student);
//增加
mapper.addStudent(new Student(null,"怀怀","女"));
//更新
//可使用的参数 are [0, 1, param1, param2]
//原理:会封装成一个hashmap,所以 map.put("parm1",8) map.put("parm2","钟佳文说我来啦~~")
// mapper.updateStudentName(8,"钟佳文说我是大胖胖~~");
// Map方法
Map params = new HashMap<>();
params.put("id",8);
params.put("newName","我getlog4j.xml~");
mapper.updateStudentName(params);
sqlSession.commit();
//删除
mapper.deleteStudent(8);
sqlSession.commit();
}finally {
sqlSession.close();
}
}
public SqlSession getSqlSession(){
String mybatisConfigFile = "mybatis-config.xml";
try {
InputStream inputStream = Resources.getResourceAsStream(mybatisConfigFile);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
return sqlSessionFactory.openSession();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}



