[MyBatis]MyBatis基础
MyBatis
1、简介
1.1MyBatis优势
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。
MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
1.2如何获得Mybatis
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency>
- Maven仓库:https://mvnrepository.com/artifact/org.mybatis/mybatis
- 中文文档:https://mybatis.org/mybatis-3/zh/getting-started.html
1.3持久化
数据持久化
- 持久化就是数据在持久状态和瞬时状态转换的过程
- 内存:断电既失
- 数据库(jdbc)io文件持久化
为什么需要持久化?
- 有一些对象不能丢弃
- 内存价格昂贵
1.4持久层
Dao层、Service层、Controller层
- 完成持久化的层
- 层界限十分明显
1.5为什么使用Mybatis
- 传统的JDBC代码太复杂,进行简化
- 自动化,作为框架简化操作
- 帮助程序数据写入到数据库
- 不用Mybatis也可以,但使用更便捷操作
2、第一个Mybatis程序
搭建环境---导入Mybatis---编写代码
创建数据库
CREATE DATABASE `mybatis';
USE `mybatis`;
CREATE TABLE `user`(
`id` INT(20) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY(`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user` (`id`,`name`,`pwd`) VALUES
(1,'张三','123456'),
(2,'李四','123897'),
(3,'王五','123567')
- 新建一个普通的maven项目MyBatis-study
- 目录结构
- 在resources下创建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核心配置文件--> <configuration> <environments default="development"> <environment id="development"> <!--数据库--> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="364624"/> </dataSource> </environment> </environments> <!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册--> <mappers> <mapper resource="com/zlc/dao/UserMapper.xml"/> </mappers> </configuration>
- 配置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"> <!--namespace=绑定一个对应的Dao/Mapper接口--> <mapper namespace="com.zlc.dao.UserDao"> <!--select查询语句--> <select id="getUserList" resultType="com.zlc.pojo.User"> select * from mybatis.user </select> </mapper>
- 编写代码
package com.zlc.pojo; //实体类 public class User { private int id; private String name; private String pwd; public User(int id, String name, String pwd) { this.id = id; this.name = name; this.pwd = pwd; } public User() { } 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 + '\'' + '}'; } }
package com.zlc.utils; 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.IOException; import java.io.InputStream; //sqlSessionFactory-->sqlSession public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static{ try { //第一步:获取sqlSessionFactory对象 String resource="mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } //SqlSession完全包含了面向数据库执行SQL命令的所有方法 public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
package com.zlc.dao; import com.zlc.pojo.User; import java.util.List; public interface UserDao { List<User> getUserList(); }
- 测试
package com.zlc.dao; import com.zlc.pojo.User; import com.zlc.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.List; public class UserDaoTest { @Test public void test(){ //获取SqlSession SqlSession sqlSession= MybatisUtils.getSqlSession(); //执行SQL UserDao userDao =sqlSession.getMapper(UserDao.class); List<User> userList=userDao.getUserList(); for(User user:userList){ System.out.println(user); } //关闭 sqlSession.close(); } }
此处会报错,maven约定大于配置,在pox.xml中添加
<build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>