欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

spring整合mybatis

时间:2023-06-10
mybatis-spring

文档链接:http://mybatis.org/spring/zh/index.html
环境准备:
导入依赖:

junit junit 4.13.2 mysql mysql-connector-java 8.0.28 org.mybatis mybatis 3.5.2 org.springframework spring-webmvc 5.3.15 org.springframework spring-jdbc 5.3.15 org.aspectj aspectjweaver 1.9.5 org.mybatis mybatis-spring 2.0.2 org.projectlombok lombok 1.18.22

注意点:

对比

mybtis去创建sqlSessionFactory代码:

package com.mybatis.study.util;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.InputStream;public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (Exception e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(true); }}

mybatis-spring创建sqlSessionFactory代码:

<?xml version="1.0" encoding="UTF-8"?>

实现类

package com.spring.study.dao;import com.spring.study.bean.User;import org.mybatis.spring.SqlSessionTemplate;import org.mybatis.spring.support.SqlSessionDaoSupport;import java.util.List;public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper { //我们的所有操作都使用sqlSession来执行,在原来,现在都使用sqlSessionTemplate; public List selectUser() { User user = new User(11, "校长", "111111", "11111"); UserMapper mapper = getSqlSession().getMapper(UserMapper.class); mapper.addUser(user); mapper.deleteUser(11); return mapper.selectUser(); } public int addUser(User user) { return getSqlSession().getMapper(UserMapper.class).addUser(user); } public int deleteUser(int id) { return getSqlSession().getMapper(UserMapper.class).deleteUser(id); }}

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。