dao层映射接口
package com.mybatis.dao;
import com.mybatis.pojo.Student;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public interface StudentMapper {
public List<Student> queryStudent(Integer id);
public void insertStudent(ArrayList<Student> arrayList);
public void updateStudentById(Map<String,Object> map);
public void deleteStudentById(Integer id);
}
Mybatis映射文件
<?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="com.mybatis.dao.StudentMapper">
<select id="queryStudent" resultType="student">
SELECT `id`, `username`, `password`,`role` FROM `user` WHERE `id` = #{id}
</select>
<insert id="insertStudent" parameterType="java.util.ArrayList">
insert into `user` values
<foreach collection="list" item="item" separator=",">
(#{item.id},#{item.username},#{item.password},#{item.role})
</foreach>
</insert>
<update id="updateStudentById">
update `user` set username=#{newUsername} where id=#{id}
</update>
<delete id="deleteStudentById">
delete from `user` where id=#{id}
</delete>
</mapper>
测试类文件
import com.mybatis.dao.StudentMapper;
import com.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.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StudentTest {
@Test
public void studentTest(){
SqlSession sqlSession=getSqlSession();
try {
List<Student> student=sqlSession.selectList("com.mybatis.dao.StudentMapper.queryStudent",2);
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> student1 = mapper.queryStudent(2);
System.out.println(student1);
ArrayList<Student> arrayList =new ArrayList<>();
arrayList.add(new Student(null,"小梅","555",0));
arrayList.add(new Student(null,"钉钉","587",0));
arrayList.add(new Student(null,"阿臭","123",0));
mapper.insertStudent(arrayList);
sqlSession.commit();
Map<String,Object> map =new HashMap<>();
map.put("id",5);
map.put("newUsername","小钟");
mapper.updateStudentById(map);
sqlSession.commit();
mapper.deleteStudentById(6);
sqlSession.commit();
}finally {
sqlSession.close();
}
}
public SqlSession getSqlSession(){
String mybatisConfigFile = "MybatisConfig.xml";
try {
InputStream inputStream = Resources.getResourceAsStream(mybatisConfigFile);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
return sqlSessionFactory.openSession();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
}