Mybatis的第一个程序
Mybatis
环境
- JDK
- MySQL
- Maven
- IDEA
需要的基础
- JDBC
- JavaSE基础
- SQL语句
- Maven
- Junit
SSM框架:配置文件。
看官方文档:
mybatis:https://mybatis.org/mybatis-3/zh/index.html
简介
什么是Mybatis?
- MyBatis 是一款优秀的持久层框架
- 它支持自定义 SQL、存储过程以及高级映射。
- MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。- - MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
- 2013年,迁移到GitHub
如何获取Mybatis?
- Maven仓库
- GitHub
持久层
数据持久化:
- 持久化:将程序的数据由瞬时状态转化为持久状态的过程
- 内存:断电即失
- 实现持久化:数据库JDBC,IO文件存储
为什么需要持久化?
- 有些对象不允许丢失
- 内存太贵
持久层:
Dao层,Service层,Controller层
- 完成持久化工作的代码块
- 层的界限十分明显
为什么需要Mybatis?
- 方便
- 传统的JDBC代码太复杂
- 简化操作流程,框架
- 帮助程序员将数据存入数据库中
- 可以不使用Mybatis(可以自己写一个框架)
Mybatis特点
- 简单易学:安装只要两个jar文件+配置几个sql映射文件
- 灵活: sql写在xml里,便于统一管理和优化
- 解除sql与程序代码的耦合:更易维护,更易单元测试
- 提供映射标签,支持对象与数据库的orm字段关系映射
- 提供对象关系映射标签,支持对象关系组建维护
- 提供xml标签,支持编写动态sql。(SQL语句写在xml文件中)
第一个Mybatis程序
思路:搭建环境-->导入Mybatis依赖-->编写代码-->测试
- 搭建环境
1.创建一个maven项目
2.在数据库中创建一个表user
CREATE DATABASE `mybatis`;
USE `mybatis`;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(20) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`password` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `user`(`id`,`name`,`password`) values (1,'xiaoming','123433'),(2,'daxiong','659888');
- 导入Mybatis依赖
可能会出现问题,需要在pom.xml文件中配置静态资源过滤
1.maven
(maven仓库中找)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>Mybatis_Study</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>Mybatis_Study01</artifactId>
<!--导入依赖-->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<!--配置Maven静态资源过滤-->
<build>
<resources>
<resource>
<directory>src/main/java</directory><!--所在目录-->
<includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<!-- 扫描resources下的.xml和.properties配置文件 -->
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
- 编写代码
1.实体类-UserPojo.class
package com.test.pojo;
public class UserPojo {
private int id;
private String name;
private String password;
public UserPojo(){}
public UserPojo(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getPassword() {
return password;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "UserPojo{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
2.mapper层UserMapper.class UserMapper.xml
(可查看Mybatis官方文档)
package com.test.mapper;
import com.test.pojo.UserPojo;
import java.util.List;
public interface UserMapper {
public List<UserPojo> getListUser();
}
<?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相当于(UserMapperImpl)实现dao层接口-->
<mapper namespace="com.test.mapper.UserMapper">
<select id="getListUser" resultType="com.test.pojo.UserPojo">
select * from user
</select>
</mapper>
3.工具类MybaisUtil.class用于获取SQLSession
(可查看Mybatis官方文档)
package com.test.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.IOException;
import java.io.InputStream;
public class MybatisUtil {
// 获取SQLSession
public static SqlSession getSQLSession() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
return sqlSessionFactory.openSession();
}
}
4.配置Mybatis配置文件mybatis-config.xml
(可查看Mybatis官方文档)
<?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>
<!--default="development"默认的配置环境,根据ID选取-->
<environments default="development">
<!--可以配置多个环境-->
<!--开发环境-->
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!--&相当于&连接符
还可以在配置一个SQL时区
-->
<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="123456"/>
</dataSource>
</environment>
<!--测试环境-->
<environment id="test">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--注册Mapper-->
<mappers>
<mapper resource="com/test/mapper/UserMapper.xml"/>
</mappers>
</configuration>
- 编写测试类进行测试:
1.UserMapperTest.class
package com.test.mappertest;
import com.test.mapper.UserMapper;
import com.test.pojo.UserPojo;
import com.test.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
public class UserMapperTest {
@Test
public void getUserList() throws IOException {
SqlSession sqlsession = MybatisUtil.getSQLSession();
UserMapper mapper = sqlsession.getMapper(UserMapper.class);
List<UserPojo> listUser = mapper.getListUser();
for(UserPojo user:listUser){
System.out.println(user);
}
}
}
2.运行结果图