[JAVA]Mybatis-Mapper动态代理
基于[[Mybatis增删改查]]这篇文章基础上进行更改,详细步骤请先了解后在看本文。
1,新建一个工具类MyBatisUtils.java用于获取sqlSessionFactory对象
package xyz.xioaxin12.utils;
/**
* @author 小信
*/
public class MyBatisUtils {
private static SqlSessionFactory sqlSessionFactory;
public static SqlSession getSqlsession(){
try {
InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
if(sqlSessionFactory == null){
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
return sqlSessionFactory.openSession();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
2,删除StudentDaoImpl的接口实现类。
3,修改测试类
package xyz.xioaxin12.test;
/**
* @author 小信
*/
public class TestMybatis {
private static StudentDao dao;
private static SqlSession sqlSession;
static{
//获取配置接口
sqlSession = MyBatisUtils.getSqlsession();
dao = sqlSession.getMapper(StudentDao.class);
}
public static void main(String[] args) {
//增
addStu();
//删
// deleteStu();
//改
// updateStu();
//查
// selectStu();
}
public static void addStu(){
Student student = new Student("小信",19);
dao.insertStudent(student);
sqlSession.commit();
closeSqlsession();
}
public static void deleteStu(){
dao.deleteStudent(1);
sqlSession.commit();
closeSqlsession();
}
public static void updateStu(){
Student student = new Student("阿六",20);
student.setId(2);
dao.updateStudent(student);
sqlSession.commit();
closeSqlsession();
}
public static void selectStu(){
List<Student> students = dao.selectStudent();
for (Student student: students) {
System.out.println(student.getId()+"-"+student.getName()+"-"+student.getAge());
}
closeSqlsession();
}
/**
* 关闭资源
*/
public static void closeSqlsession(){
if(sqlSession!=null){
sqlSession.close();
}
}
}
注意
- mapper映射文件namespace为接口的全类名;
- 接口中的每个方法名分别与mapper映射文件每个处理数据的id一致。
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 xiaoxin1218@qq.com
文章标题:[JAVA]Mybatis-Mapper动态代理
文章字数:281
本文作者:周信
发布时间:2019-10-21, 18:54:33
最后更新:2023-05-03, 10:25:35
原始链接:http://zx21.xyz/2019/10/21/JAVA-Mybatis-Mapper动态代理/版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。