MyBatis 是一款优秀的持久层框架;
它支持自定义 SQL、存储过程以及高级映射。
MyBatis 免除了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。
MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java的POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
Mybatis本是apache的一个开源项目iBatis,2010年这个项目由apache software foundation迁移到了google code,并改名为Mybatis。
2013年11月迁移到Github
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.7version>
dependency>
Github:Releases · mybatis/mybatis-3 (github.com)
中文文档地址:mybatis – MyBatis 3 | 简介
持久化就是将程序的数据在持久状态和瞬时状态转化的过程
内存特性:断电即失
数据库(Jdbc),io文件持久化。
有一些对象,不能让他丢掉
内存太贵了
Dao层、Service层、Controller层
持久层:完成持久化工作的代码块
层界限十分明显
帮助程序员将数据存入到数据库中
方便
传统的JDBC代码太复杂了。为了简化,出现框架,实现自动化。
不用MyBatis也可以,技术没有高低之分。学习框架更容易上手。
简单易学
灵活
sql和代码的分离,提高了可维护性。
提供映射标签,支持对象与数据库的orm字段关系映射
提供对象关系映射标签,支持对象关系组建维护
提供xml标签,支持编写动态sql
使用的人多
CREATE DATABASE `mybatis`;
USE `mybatis`;
CREATE TABLE `user`(
`id` INT(20) NOT NULL PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE = INNODB DEFAULT CHARSET= utf8;
INSERT INTO `user`(`id`,`name`,`pwd`) VALUES
(1,'张三','123456'),
(2,'李四','123456'),
(3,'王五','123456'),
(4,'赵六','123456'),
(5,'冯七','123456'),
(6,'陈八','123456'),
(7,'楚九','123456');
新建普通的maven项目
删除src目录:将此工程当作父工程,然后创建子工程
导入maven依赖
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.21version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.7version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
dependency>
dependencies>
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/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/zmt/dao/UserMapper.xml"/>
mappers>
configuration>
//sqlSessionFactory ---> sqlSession
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static{
try{
//使用Mybatis第一步:获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (IOException e){
e.printStackTrace();
}
}
// 既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
public static SqlSession getSqlSession(){
SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}
}
//实体类
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
//Dao等价之后创建的Mapper,为了方便理解,现在先叫Dao
public interface UserDao {
List<User> getUserList();
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zmt.dao.UserDao">
<select id="getUserList" resultType="com.zmt.pojo.User">
select * from mybatis.user
select>
mapper>
MapperRegistry是什么?
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
public class UserDaoTest {
@Test
public void test(){
//第一步:获取SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:getMapper
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
//方式二:不常用了,不推荐
List<User> userList = sqlSession.selectList("com.zmt.dao.UserDao.getUserList");
for (User user : userList) {
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
}
}
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
sqlSession.close();
指的是UserMapper.xml中的mapper namespace:
namespace中的包名,要和Dao/mapper 接口的包名一致
<select id="getUserById" resultType="com.zmt.pojo.User" parameterType="int">
select>
id:对应的namespace中的方法名
resultType:sql语句执行的返回值!
parameterType:参数类型
按Id查询,测试
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userById = mapper.getUserById(1);
System.out.println(userById);
sqlSession.close();
}
<select id="getUserById" resultType="com.zmt.pojo.User" parameterType="int">
select * from mybatis.user where id = #{id}
select>
//根据ID查询用户
User getUserById(int id);
sqlSession.commit();
//增删改需要提交事务
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(8,"卫十","123456"));
//提交事务
sqlSession.commit();
sqlSession.close();
}
<insert id="addUser" parameterType="com.zmt.pojo.User" >
insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd})
insert>
//插入一个用户
int addUser(User user);
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(8,"卫十十","123456"));
// 提交事务
sqlSession.commit();
sqlSession.close();
}
<update id="updateUser" parameterType="com.zmt.pojo.User" >
update mybatis.user set name = #{name},pwd = #{pwd} where id = #{id}
update>
//修改用户
int updateUser(User user);
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(8);
// 提交事务
sqlSession.commit();
sqlSession.close();
}
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id};
delete>
//删除一个用户
int deleteUser(int id);
//万能的Map,不需要知道数据库中有什么,只需要查询对应字段
int addUser2(Map<String,Object> map);
<insert id="addUser2" parameterType="map" >
insert into mybatis.user (id,name,pwd) values (#{userId},#{userName},#{password})
insert>
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String,Object>();
map.put("userId",8);
map.put("userName","卫十");
map.put("password","123456");
mapper.addUser2(map);
// 提交事务
sqlSession.commit();
sqlSession.close();
}
Map传递参数,直接在sql中取出key即可【parameter=“map”】
对象传递参数,直接在sql中取出对象的属性即可【parameter=“Object”】
只有一个基本类型参数的情况下,可以直接在sql中取到
多个参数用Map , 或者注解
// 模糊查询
List<User> getUserLike(String value);
<select id="getUserLike" resultType="com.zmt.pojo.User">
select * from user where name like "%"#{value}"%"
select>
@Test
public void getUserLike(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserLike("%李%");
for (User user : userList) {
System.out.println(user);
}
// 提交事务
sqlSession.commit();
sqlSession.close();
}
List
select * from user where name like "%"#{value}"%"