@[TOC]
一、Mybatis简介
1.Mybatis是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。
2.Mybatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。
3.Mybatis可以使用简单的XML或注解来配置和映射原生信息,将接口和Java的POJO映射成数据库中的记录。
4.特点:小巧简单易学,没有任何第三方依赖。MyBatis相当灵活,不会对应用程序或者数据库的现有设计强加
任何影响。SQL写在XML里,从程序代码中彻底分离,降低耦合度,便于统一管理和优化,更易单元测试,并可重用。
5.不足:SQL语句的编写工作量较大,尤其是字段多、关联表多时,更是如此,对开发人员编写SQL语句的功底有一定要求,SQL语句依赖于数据库,导致数据库移植性差,不能随意更换数据库。
二、Mybatis体系结构
在这里插入图片描述
三、Mybatis编程方法1:基于XML的实现
在这里插入图片描述
步骤1、创建好MySQL数据库
create database testdb; use testdb; create table users( id int auto_increment not null, username varchar(20) not null, password varchar(20), primary key(id) );
步骤2、在pom.xml中添加mysql-connector-java和Mybatis依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.18</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency>
步骤3、创建实体类User(pojo)
在src/main/java下新建entity包,并创建User类:
package entity; public class User { int id; String username; String password; //getter和setter省略 @Override public String toString() { return "User [id=" + id + ", username=" + username + ", password=" + password + "]"; } }
步骤4、添加Mybatis全局配置文件
在src/main/resources下新建mybatis包,并新建mybatis-config.xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/testdb?serverTimezone=UTC" /> <property name="username" value="root" /> <property name="password" value="zz@mysql" /> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/userMapper.xml"/> </mappers> </configuration>
步骤5、创建sql映射文件userMapper.xml
在src/main/resources下新建mapper包,创建userMapper.xml :
<?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="mapper.userMapper"> <select id="getUserById" resultType="entity.User" parameterType="int"> select * from users where id= #{id} </select> </mapper>
步骤6、主程序测试
public class Test { public static void main(String[] args) throws IOException { String resource = "mybatis/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); String statement = "mapper.userMapper.getUserById"; // namespace+id找到映射sql串 User user = sqlSession.selectOne(statement, 1); sqlSession.close(); System.out.println(user); } }
三、Mybatis编程方法2:基于注解的实现
步骤1、定义sql映射接口(在src/main/java下创建mapper包)
package mapper; public interface IUserMapper { @Insert("insert into users(username,password) values(#{username},#{password})") public int addUser(User user); @Delete("delete from users where id=#{id}") public int deleteUser(int id); @Update("update users set username=#{username},password=#{password} where id=#{id}") public int updateUser(User user); @Select("select * from users where id=#{id}") public User getUserById(int id); @Select("select * from users") public List<User> getAllUsers(); }
步骤2、将sql映射接口添加到Mybatis配置文件
<mappers> <mapper class="mapper.IUserMapper"/> </mappers>
步骤3、CRUD代码
static SqlSession sqlSession; // 定义类成员变量 static IUserMapper mapper; // 定义类成员变量 public static SqlSession getSqlSession() throws IOException { String resource = "mybatis/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); return sqlSessionFactory.openSession(); } public static List<User> getAllUsers() throws IOException { sqlSession = getSqlSession(); mapper = sqlSession.getMapper(IUserMapper.class); List<User> list = mapper.getAllUsers(); sqlSession.close(); return list; } public static void main(String[] args) throws IOException { List<User> users = getAllUsers(); for (User user : users) { System.out.println(user); } }
五、资源下载与学习
联系作者
如需要本资源下载也可以直接添加作者QQ,并可以获取资源预览、软件安装、工程导入、协助运行、算法解释、报告协助撰写等售后服务
欢迎交流
QQ:402501817(心源易码 佩奇)
QQ:2215991436(心源易码 派大星)