MyBatis3.xIdea搭建
MyBatis 本是apache的一個開源專案iBatis, 2010年這個專案由apache software foundation 遷移到了google code,並且改名為MyBatis 。2013年11月遷移到Github。
MyBatis作為一款優秀的orm框架,經常與Hibernate拿來比較,身為目前較流行的MyBatis 避免了幾乎所有的 JDBC 程式碼和手動設定引數以及獲取結果集。接下來我們來看看如何搭建一個MyBaits專案。
因為idea並不支援mybatis的自動搭建,所以我們需要手動的匯入一些jar包
需要準備的Jar包
mybatis-3.4.6.jar
mybatis的主體mysql-connector-java-5.1.46.jar
連結資料的log4j-1.2.17
用於列印日誌的
關於Mybatis的構建分為兩種,我們先看XML方式
XML方式
1. Mybatis-configuration.xml
mybatis-configuration.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.properties"/>
<!-- 設定列印使用log4j -->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="logImpl" value="LOG4J"/>
</settings>
<!-- 設定執行時環境 -->
<!-- mybatis 允許存在多個執行時環境 -->
<environments default="development">
<environment id="development">
<!-- transactionManager 事務管理者 -->
<!-- 設定本次事務管理方式為JDBC -->
<transactionManager type="JDBC"/>
<!-- 資料來源 連線池 -->
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${user}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- 引入對映檔案 -->
<mappers>
<mapper resource="model/UserMapper.xml"/>
</mappers>
</configuration>
2.User.java以及UserMapper.xml
User.java
package model;
/**
* Created by Administrator on 2018/10/31.
*/
public class User {
private int id;
private String username;
private String nickname;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username=`" + username + ``` +
", nickname=`" + nickname + ``` +
`}`;
}
}
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">
<!-- 名稱空間 對自己取一個名字作為呼叫的唯一識別符號-->
<mapper namespace="model.UserMapper">
<!-- id sql語句的id 呼叫時使用名稱空間+sqlid方式進行呼叫 -->
<!-- parameterType 引數型別 -->
<!-- resultType 返回值型別 -->
<select id="selectUserById" parameterType="int" resultType="model.User">
<!-- 引數注入時使用#或$ -->
<!-- #是佔位符,在預編譯時使用?佔位,可以預防sql注入的問題 -->
<!-- $是連線符,解析sql時直接使用變數替換,可能會引起sql注入的問題 -->
<!-- #和$ 相當於 preparedStatement和statement的區別 -->
<!-- 總的來說,能用#就別用$ -->
select id,username,nickname from user where id = #{id}
</select>
</mapper>
3.db.properties以及log4j.properties
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///test
user=root
password=root
log4j.properties
log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n
#log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.R.File=../logs/service.log
#log4j.appender.R.layout=org.apache.log4j.PatternLayout
#log4j.appender.R.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n
#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
4. 測試一下
Main.java
import model.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 java.io.IOException;
import java.io.Reader;
public class Main {
public static void main(String[] args) throws IOException {
//xml方式
//定義mybatis的配置檔案的路徑
String resource = "mybatis_config.xml";
//將配置檔案轉換為reader
Reader reader = Resources.getResourceAsReader(resource);
//使用sqlsessionfactorybuilder對配置檔案進行載入
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
//獲取sqlsession
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = sqlSession.selectOne("model.UserMapper.selectUserById",1);
System.out.println(user);
}
}
最後看一下控制檯的輸出內容
[service] 2018-10-31 16:59:55,875 - org.apache.ibatis.logging.LogFactory -0 [main] DEBUG org.apache.ibatis.logging.LogFactory - Logging initialized using `class org.apache.ibatis.logging.log4j.Log4jImpl` adapter.
[service] 2018-10-31 16:59:56,047 - org.apache.ibatis.logging.LogFactory -172 [main] DEBUG org.apache.ibatis.logging.LogFactory - Logging initialized using `class org.apache.ibatis.logging.log4j.Log4jImpl` adapter.
[service] 2018-10-31 16:59:56,075 - org.apache.ibatis.datasource.pooled.PooledDataSource -200 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
[service] 2018-10-31 16:59:56,075 - org.apache.ibatis.datasource.pooled.PooledDataSource -200 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
[service] 2018-10-31 16:59:56,075 - org.apache.ibatis.datasource.pooled.PooledDataSource -200 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
[service] 2018-10-31 16:59:56,075 - org.apache.ibatis.datasource.pooled.PooledDataSource -200 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
[service] 2018-10-31 16:59:56,207 - org.apache.ibatis.transaction.jdbc.JdbcTransaction -332 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Opening JDBC Connection
[service] 2018-10-31 16:59:56,541 - org.apache.ibatis.datasource.pooled.PooledDataSource -666 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - Created connection 836514715.
[service] 2018-10-31 16:59:56,541 - org.apache.ibatis.transaction.jdbc.JdbcTransaction -666 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@31dc339b]
[service] 2018-10-31 16:59:56,543 - model.UserMapper.selectUserById -668 [main] DEBUG model.UserMapper.selectUserById - ==> Preparing: select id,username,nickname from user where id = ?
[service] 2018-10-31 16:59:56,607 - model.UserMapper.selectUserById -732 [main] DEBUG model.UserMapper.selectUserById - ==> Parameters: 1(Integer)
[service] 2018-10-31 16:59:56,640 - model.UserMapper.selectUserById -765 [main] DEBUG model.UserMapper.selectUserById - <== Total: 1
User{id=1, username=`趙大鵬`, nickname=`死亡列車`}
可以看到sql語句以及查詢的結果都出來了,mybatis使用xml方式搭建完畢。
相關文章
- 【環境搭建】RocketMQ叢集搭建MQ
- docker搭建Nexus搭建Maven私服DockerMaven
- MySQL叢集搭建(1)-主備搭建MySql
- MVVM框架的搭建(二)——專案搭建MVVM框架
- gradle手工搭建java專案搭建GradleJava
- Inception 搭建
- MYSQL搭建MySql
- Harbor 搭建
- ELK搭建
- elk 搭建
- ldap搭建LDA
- 搭建cacti
- 框架搭建框架
- DataGuard搭建
- lnmp搭建LNMP
- RAC 搭建
- elasticsearch搭建Elasticsearch
- DG搭建
- OJ搭建
- 搭建genieacs
- 精讀《視覺化搭建思考 - 富文字搭建》視覺化
- 從零搭建一個IdentityServer——專案搭建IDEServer
- 【Azkaban搭建】---Azkaban 3.25.0搭建細則 超實用
- Windows下搭建ESP-IDF環境搭建Windows
- Sentry 搭建
- redis cluster 搭建Redis
- docker rancher搭建Docker
- vue 快速搭建Vue
- windows搭建ftpWindowsFTP
- Docker 搭建 MongoDBDockerMongoDB
- 圖床搭建圖床
- chatgpt個人搭建ChatGPT
- LAMP搭建示例LAMP
- 搭建HadoopHadoop
- Redis sentinel搭建Redis
- 叢集搭建
- JDK的搭建JDK
- 【DG】搭建(一)