mybatis框架
快速入门
示例:查询user表所有的数据
步骤:
1,创建user表,添加数据
2,创建模块,导入坐标
3,编写Mybatis核心配置文件,替换连接信息,解决硬编码问题
4,编写SQL映射文件,统一管理sql语句,解决编码问题
5,编码
流程:定义POJO类 --->加载核心配置文件,获取SqlSessionFactory对象 --->获取SqlSession对象,执行sql语句 ---> 释放资源
示例代码:
package com.mybatis; 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 pojo.User; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Objects; public class MybatisDemo { public static void main(String[] args) throws IOException { //第一步,获取sqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //第二步,获取sqlsession对象执行sql SqlSession sqlSession = sqlSessionFactory.openSession(); //第三步,执行sql语句 List<User> users = sqlSession.selectList("test.selectAll"); System.out.println(users); sqlSession.close(); } }
mapper代理开发
使用mapper开发可以避免硬编码,而且开发更便捷,并且不需要频繁配置xml文件,使整体结构也更加规范
代码示例:
package com.art; import com.art.mapper.UserMapper; import com.art.pojo.User; 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.jupiter.api.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; public class DemoTest { public static void main(String[] args) throws IOException { // String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<User> users = userMapper.selectAll(); System.out.println(users); sqlSession.close(); } }
配置核心文件xml
<!--
environments配置数据库连接信息可以根据default配置多个数据库连接信息
typeAliases配置别名,配置完成后returnType就可以不用添加包路径
-->
mybatis的增删改查