1.什么是Mybatis?(官网)
1-MyBatis 是一款优秀的持久层框架。
2-它支持自定义 SQL、存储过程以及高级映射。
3- MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
4-MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO
(Plain OldJava Objects,普通老式 Java 对象)为数据库中的记录。
2.为什么需要Mybatis?
1-简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件易于学习,易于使用
2-灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
3-解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护。sql和代码的分离,提高了可维护性。
4-提供xml标签,支持编写动态sql
5-提供映射标签,支持对象与数据库的orm字段关系映射
3.第一个Mybatis程序
思路:搭建数据库->导入mybatis->编写代码->测试
1-搭建数据库
2-在pom.xml中导入依赖
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!-- junit -->
<junit.version>4.13</junit.version>
<!-- mybatis -->
<mybatis.version>3.4.5</mybatis.version>
<!-- mysql -->
<mysql.version>5.1.44</mysql.version>
<!-- servlet -->
<servlet.version>4.0.1</servlet.version>
<!-- log4j2 -->
<log4j2.version>2.9.1</log4j2.version>
</properties>
<dependencies>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!--记得修改mybatis.cfg.xml添加如下内容-->
<!--<setting name="logImpl" value="LOG4J2"/>-->
<!--核心log4j2jar包-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j2.version}</version>
</dependency>
<!--web工程需要包含log4j-web,非web工程不需要-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>${log4j2.version}</version>
</dependency>
</dependencies>
3-编写mybatis核心配置文件(myabtis.cfg.xml)-->以及公共的jdbc.properties配置文件
做到连接数据库
<?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>
<!-- 引入外部配置文件 -->
<properties resource="jdbc.properties"/>
<!-- 设置mybatis参数 -->
<settings>
<setting name="logImpl" value="LOG4J2"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!-- 别名 -->
<!-- <typeAliases>-->
<!-- <typeAlias type="com.zking.oa.model.Book" alias="Book"/>-->
<!-- </typeAliases>-->
<!-- 配置mybatis运行环境 -->
<environments default="development">
<environment id="development">
<!-- type="JDBC" 代表使用JDBC的提交和回滚来管理事务 -->
<transactionManager type="jdbc"/>
<!-- mybatis提供了3种数据源类型,分别是:POOLED,UNPOOLED,JNDI -->
<!-- POOLED 表示支持JDBC数据源连接池 -->
<!--
DBHELPER > ...
-->
<!-- UNPOOLED 表示不支持数据源连接池 -->
<!-- JNDI 表示支持外部数据源连接池 -->
<dataSource type="POOLED">
<property name="driver"
value="${jdbc.driver}"/>
<property name="url"
value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/zking/mybatis01/mapper/BookMapper.xml"/>
</mappers>
</configuration>
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/t272?useUnicode=true&characterEncoding=UTF-8&useSSL=false
jdbc.username=root
jdbc.password=123
5.建一个mybatis工具类—MybatisSessionFactoryUtils.java(获取sqlSessionFactory)
/**
* mybatis的辅助类,类似于DBHelper
* 在后面的课程中讲不会siyou
*/
public class MybatisSessionFactoryUtils {
//创建sqlSession连接工厂类
public static SqlSessionFactory sqlSessionFactory;
//状态管理SqlSession
private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
//静态块,有且执行一次
static {
try {
InputStream is = MybatisSessionFactoryUtils.class
.getResourceAsStream("/mybatis.cfg.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private MybatisSessionFactoryUtils() {
}
public static SqlSession openSession() {
SqlSession sqlSession = threadLocal.get();
if (null == sqlSession) {
sqlSession = sqlSessionFactory.openSession();
threadLocal.set(sqlSession);
}
return sqlSession;
}
public static void closeSession() {
SqlSession sqlSession = threadLocal.get();
if (null != sqlSession) {
threadLocal.set(null);
sqlSession.close();
}
}
public static void main(String[] args) {
SqlSession sqlSession = MybatisSessionFactoryUtils.openSession();
System.out.println(sqlSession);
System.out.println(sqlSession.getConnection());
MybatisSessionFactoryUtils.closeSession();
}
}
6-编写基本代码
实体类Book:
public class Book {
private Integer bookId;
private String bookName;
private String bookNamePinyin;
private Float bookPrice;
private String bookType;
@Override
public String toString() {
return "Book{" +
"bookId=" + bookId +
", bookName='" + bookName + '\'' +
", bookNamePinyin='" + bookNamePinyin + '\'' +
", bookPrice=" + bookPrice +
", bookType='" + bookType + '\'' +
'}';
}
public Book(Integer bookId, String bookName, String bookNamePinyin, Float bookPrice, String bookType) {
this.bookId = bookId;
this.bookName = bookName;
this.bookNamePinyin = bookNamePinyin;
this.bookPrice = bookPrice;
this.bookType = bookType;
}
public Book() {
super();
}
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookNamePinyin() {
return bookNamePinyin;
}
public void setBookNamePinyin(String bookNamePinyin) {
this.bookNamePinyin = bookNamePinyin;
}
public Float getBookPrice() {
return bookPrice;
}
public void setBookPrice(Float bookPrice) {
this.bookPrice = bookPrice;
}
public String getBookType() {
return bookType;
}
public void setBookType(String bookType) {
this.bookType = bookType;
}
}
dao类 BookMapper:
public interface BookMapper {
int deleteByPrimaryKey(Integer bookId);
int insert(Book record);
//查询:query,select,find
List<Book> queryBookAll();
int insertSelective(Book record);
Book selectByPrimaryKey(Integer bookId);
int updateByPrimaryKeySelective(Book record);
int updateByPrimaryKey(Book record);
}
以及使用maven自动生成持久层:...残缺部分
7-测试 运行
package com.zking.mybatis01.service.impl;
import com.zking.mybatis01.mapper.BookMapper;
import com.zking.mybatis01.model.Book;
import com.zking.mybatis01.service.IBookService;
import com.zking.mybatis01.util.MybatisSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
public class BookServiceImplTest {
private IBookService bookService;
private Book book;
private SqlSession sqlSession;
@Before
public void setUp() throws Exception {
book=new Book();
sqlSession = MybatisSessionFactoryUtils.openSession();
BookMapper bookmapper = sqlSession.getMapper(BookMapper.class);
BookServiceImpl bookServiceImpl = new BookServiceImpl();
bookServiceImpl.setBookMapper(bookmapper);
bookService = bookServiceImpl;
}
@After
public void tearDown() throws Exception {
sqlSession.commit();
MybatisSessionFactoryUtils.closeSession();
}
@Test
public void insert() {
book.setBookName("吊毛流浪记3");
book.setBookPrice(100f);
book.setBookType("故事");
int insert = bookService.insert(book);
Integer bookId = book.getBookId();
System.out.println("idididiididiidid:::::"+bookId);
}
}