主要介绍如何搭建Mybatis开发环境,如何与数据库进行交互
Idea中新建一个Maven项目,一路下一步。
在 pom.xml
中添加所需要的依赖
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.15version>
dependency>
<dependency>
<groupId>com.oracle.database.jdbcgroupId>
<artifactId>ojdbc8artifactId>
<version>21.1.0.0version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.24version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.6version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.5version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>5.2.9.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.2.9.RELEASEversion>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13version>
<scope>testscope>
dependency>
dependencies>
如果 jar 包下载不下来可能是 maven 中的配置文件有问题,打开 Maven 安装目录,conf -》 setting.xml
文件,将里面的内容改为下面
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>D:\Work\repositorylocalRepository>
<offline>falseoffline>
<mirrors>
<mirror>
<id>aliyunmavenid>
<mirrorOf>*mirrorOf>
<name>阿里云公共仓库name>
<url>https://maven.aliyun.com/repository/publicurl>
mirror>
mirrors>
settings>
Mybatis 连接数据库需要配置,我们一般把数据库配置信息写在一个单独的文件中,以减少耦合。
在resources
文件夹下新建jdbc.properties 与 mybatis.xml
文件
mysql.url=jdbc:mysql://localhost:3306/snow?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
mysql.driver=com.mysql.cj.jdbc.Driver
mysql.username=root
mysql.password=root
oracle.url=jdbc:oracle:thin:@127.0.0.1:1521:ORCL
oracle.driver=oracle.jdbc.driver.OracleDriver
oracle.username=SNOW_ZY
oracle.password=snow
DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="jdbc.properties"/>
<settings>
<setting name="logImpl" value="LOG4J"/>
settings>
<environments default="oracle_developer">
<environment id="mysql_developer">
<transactionManager type="jdbc"/>
<dataSource type="pooled">
<property name="driver" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
dataSource>
environment>
<environment id="oracle_developer">
<transactionManager type="jdbc"/>
<dataSource type="pooled">
<property name="driver" value="${oracle.driver}"/>
<property name="url" value="${oracle.url}"/>
<property name="username" value="${oracle.username}"/>
<property name="password" value="${oracle.password}"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/snow/xml/SnowMysql.xml"/>
<mapper resource="com/snow/xml/SnowOracle.xml"/>
mappers>
configuration>
另外添加一个log4j.properties
文件,用来打印日志。
log4j.rootLogger=DEBUG,CONSOLE,file
#log4j.rootLogger=ERROR,ROLLING_FILE
log4j.logger.cn.jbit.dao=debug
log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug
log4j.logger.java.sql.ResultSet=debug
log4j.logger.org.tuckey.web.filters.urlrewrite.UrlRewriteFilter=debug
######################################################################################
# Console Appender \u65e5\u5fd7\u5728\u63a7\u5236\u8f93\u51fa\u914d\u7f6e
######################################################################################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=error
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n
######################################################################################
# DailyRolling File \u6bcf\u5929\u4ea7\u751f\u4e00\u4e2a\u65e5\u5fd7\u6587\u4ef6\uff0c\u6587\u4ef6\u540d\u683c\u5f0f:log2009-09-11
######################################################################################
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern=yyyy-MM-dd
log4j.appender.file.File=log.log
log4j.appender.file.Append=true
log4j.appender.file.Threshold=error
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
log4j.logger.com.opensymphony.xwork2=error
到处为止,所有操作数据库所需的配置文件都已经配置好了,下一步就将这些配置信息与Mybatis框架相结合起来使用即可。
这里用oracle数据库举例,如果想用别的数据库,在mybatis.xml
中修改
这个标签的属性值即可。
DBUtil.java
类public class DBUtil {
//创建一个泛型为SqlSession的threadLocal, 用来存放当前线程的SqlSession
private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
private static SqlSessionFactory sqlSessionFactory; //创建工厂类
static {
try {
//新建Reader对象, 将我们配置的 mybatis 文件给加载进来, 然后传给工厂类为我们生产 SqlSession
Reader reader = Resources.getResourceAsReader("mybatis.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
SqlSession sqlSession = threadLocal.get(); //从当前线程取出sqlsession, 如果为空则创建一个新的, 并加入到当前线程
if (sqlSession == null){
sqlSession = sqlSessionFactory.openSession();
threadLocal.set(sqlSession);
}
return sqlSession;
}
public static void closeSqlsession(){
SqlSession sqlSession = threadLocal.get();
if (sqlSession != null){
sqlSession.close();
threadLocal.remove();
}
}
}
//测试连接数据库
@Test
public void test1(){
SqlSession sqlSession = DBUtil.getSqlSession();
System.out.println(sqlSession.getConnection());
sqlSession.close();
}
resources
文件夹下新建com.snow.xml
文件
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.snow.xml.SnowOracle">
<insert id="addByUUID" parameterType="map">
INSERT INTO S_USER(ID, USERNAME, PASSWORD) VALUES (GET_UUID(), #{username}, #{password})
insert>
mapper>
注意:此处的 xml 需要配置到Myvatis.xml
文件中去,不然程序找不到该文件,之前已经配置过了,这里看一下
项目目录结构
Sql 测试
//Oracle 的 UUID 测试
@Test
public void test3(){
Map<String, Object> map = new HashMap<String, Object>();
SqlSession sqlSession = DBUtil.getSqlSession();
try {
map.put("username", "tom");
map.put("password", "123");
sqlSession.insert("com.snow.xml.SnowOracle.addByUUID", map);//Mybatis 里面会自动为我们生成uuid
sqlSession.commit();
}catch (Exception e){
e.printStackTrace();
sqlSession.rollback();
}finally {
sqlSession.close();
}
}
Mybatis的工作流程:
其实实现数据库交互功能的方式有很多,用框架的好处在于能够大大减低代码之间耦合,想起以前大学做设计作业的时候,那时候就是纯生的JDBC调用方式,无比的繁琐,用了框架之后主要要能够学习到其中的设计模式与思维,与之前传统的方式作对比。