一、創建項目(本文以Idea基於Maven構建的項目為例) New——>Project 筆者這裡是選擇自己本地的Maven及配置 最後點擊Finish即可 二、在配置文件中添加依賴包 pom.xml配置文件中添加Mybatis、JDBC驅動、log4j日誌管理的包依賴 完整代碼如下: <?xml v ...
一、創建項目(本文以Idea基於Maven構建的項目為例)
- New——>Project
- 筆者這裡是選擇自己本地的Maven及配置
- 最後點擊Finish即可
二、在配置文件中添加依賴包
- pom.xml配置文件中添加Mybatis、JDBC驅動、log4j日誌管理的包依賴
- 完整代碼如下:
<?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"> <modelVersion>4.0.0</modelVersion> <groupId>com.zhurouwangzi</groupId> <artifactId>MybatisDemo</artifactId> <version>1.0-SNAPSHOT</version> <name>MybatisDemo</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> <!--mybatis版本--> <mybatis.version>3.2.7</mybatis.version> <!--log4j版本--> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mysql驅動包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.29</version> </dependency> <!-- 日誌文件管理包 --> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> </dependencies> <build> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle --> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-jar-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle --> <plugin> <artifactId>maven-site-plugin</artifactId> <version>3.7.1</version> </plugin> <plugin> <artifactId>maven-project-info-reports-plugin</artifactId> <version>3.0.0</version> </plugin> </plugins> </pluginManagement> </build> </project>View Code
- 等依賴包下載完了之後我們在項目這裡可以看到:
- 在src下添加一個resource文件夾,然後滑鼠右鍵Mark Directory As Resources Root
- 在src/resource文件夾下創建SqlMapConfig.xml作為Mybatis的全局配置文件
- 在src/resource然後再創建一個log4j.properties文件用來配置日誌文件的配置
- 在src/resource再創建一個sqlmap文件夾用來存放Mybatis的映射文件
- 創建好的項目結構如下:
三、設置Mybatis相關配置文件
- log4j.properties配置文件的內容如下:
# Global logging configuration log4j.rootLogger=DEBUG, stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
- SqlMapConfig.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> <!-- 和spring整合後 environments配置將廢除--> <environments default="development"> <environment id="development"> <!-- 使用jdbc事務管理--> <transactionManager type="JDBC" /> <!-- 資料庫連接池--> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/web_test3?characterEncoding=utf-8" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> </configuration>
四、創建實體類
package com.zhurouwangzi.entity; public class UserBaseInfo { private int id; private String username; @Override public String toString(){ return "User [id=" + id + ", username=" + username+ "]"; } 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; } }View Code
- 在src/resource/sqlmap文件夾下添加user.xml作為UserBaseInfo的映射文件
<?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是命名空間,作用sql語句的隔離,後面還有重要作用 #{}作用就是占位符,相當於jdbc的“?” parameterType:查詢的參數類型 resultType:查詢結果的數據類型,如果時候pojo應該給全路徑。 --> <mapper namespace="test"> <select id="getUserById" parameterType="int" resultType="com.zhurouwangzi.entity.UserBaseInfo"> select * from user_baseinfo where id = #{id} </select> </mapper>View Code
- 在SqlMapConfig.xml配置文件中添加<Mappers>配置:
五、用測試方法區測試
- 代碼如下:
package com.zhurouwangzi.service; import com.zhurouwangzi.entity.UserBaseInfo; 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.junit.jupiter.api.Test; import java.io.InputStream; public class MybatisTest { @Test public void test() throws Exception{ //1.創建一個SqlSessionFactoryBuilder對象 SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); //2.載入配置文件 InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); //3.創建SqlSessionFactory工廠對象 SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream); //4.獲取SqlSession對象 SqlSession sqlSession = sqlSessionFactory.openSession(); //5.執行sql語句 UserBaseInfo userBaseInfo = sqlSession.selectOne("getUserById", 16); System.out.println(userBaseInfo); //關閉資源 sqlSession.close(); } }View Code
運行結果如下: