MyBatis简介
myBatis是一个持久层框架,主要作用就是在java中操作数据库,其实就是在jdbc的基础上进行了封装,使用mybatis之后,开发者不用再花费精力去处理诸如注册驱动、创建Connection、配置Statement等繁琐过程。与spring mvc要运行在web容器不同,mybatis不需要web容器,在c/s架构和b/s架构下均可运行。
官网:http://www.mybatis.org/mybatis-3/
搭建MyBatis项目
- 首先使用Idae建立一个maven-archetype-quickstart项目,向pom.xml文件中添加MyBatis依赖的包,如下:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
这里可以看到,使用的是8.0的MySql数据库,同时还添加了log4j方便查看输出的sql语句。
- 接下来建立一个测试用的数据库,名字就叫mybatis,创建测试表ibatis_user,如下:
create database mybatis;
use mybaits;
CREATE TABLE `ibatis_user` (
`id` int(11) NOT NULL,
`person_name` varchar(50) NOT NULL,
`person_age` int(11) DEFAULT NULL,
`person_account` varchar(10) NOT NULL,
`person_pwd` varchar(16) NOT NULL,
`person_addr` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ;
//插入一条测试数据
insert into ibatis_user value(1,'jerry',24,'kons333','123456',null);
- 然后配置MyBatis的项目配置文件mybatis.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>
<!--数据库-->
<properties resource="db-config.properties"/>
<typeAliases>
<package name="com.kons.dao"/>
</typeAliases>
<environments default="development">
<environment id="development">
<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>
<mappers>
<mapper resource="mapper/user.xml"/>
</mappers>
</configuration>
db-config.properties文件:
#--MySql 6.0以后版本的配置--
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
username=***
password=******
这里需要注意的是8.0版本的MySql的url和dirver和MySql 5.0版本的区别,链接MySql5.0版本的配置如下:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis
如果url直接配置到mybatis的配置文件中,需要将'&'换成转义字符'&';
- 接着创建实体类User和对应的mapper文件user.xml:
package com.kons.dao;
public class User {
private int id;
private int person_age;
private String person_name;
private String person_account;
private String person_pwd;
private String person_addr;
//省略getter和setter
}
<?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="kons">
<select id="findUserById" parameterType="int" resultType="User">
select * from ibatis_user where id=#{id}
</select>
</mapper>
- 配置日志
mybatis支持下面的日志处理:
SLF4J
Apache Commons Logging
Log4j 2
Log4j
JDK logging
项目中使用的是log4j,配置文件如下:
#查看kons的namespace下的sql语句
log4j.logger.kons=debug,console
#控制台附加器
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern= [%-5p][%d{yyyy-MM-dd HH:mm:ss}]%m%n
- 最后,编写启动类App.java:
package com.kons;
import com.kons.dao.User;
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 org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import java.io.Reader;
public class App
{
public static void main( String[] args ) throws Exception {
//加载日志配置
BasicConfigurator.configure();
String resource= "mybatis-config.xml";
Reader config= Resources.getResourceAsReader(resource);
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(config);
try(SqlSession session=sqlSessionFactory.openSession()){
User user=session.selectOne("findUserById",1);
session.commit();
System.out.println("This is Sql result--->"+user.getPerson_name());
}
catch (Exception ex){
System.out.println(ex.getMessage());
}
}
}
运行结果如下:
项目github地址:https://github.com/Jerry-bg/Java