mybatis是個持久層的框架,用來執行數據庫操做的,無外乎增刪改查,上一節對mybatis有了宏觀上的瞭解後,這一篇博客主要經過一個小示例來入門mybatis,先看一下要寫的示例需求:java
根據用戶id查詢用戶信息
根據用戶名稱模糊查詢用戶信息
添加用戶、刪除用戶、更新用戶
其實也就是增刪改查,掌握這些,基本上就掌握了mybatis的基本操做了,下面一個個模塊來完成。mysql
1.MyBatis環境準備git
毫無疑問,砍柴得有把刀才行,環境的搭建是開發中必需的一個流程,mybatis的環境我分紅如下幾個部分來總結:github
mybatis運行環境主要是指mybatis的jar包,mybatis已經將它的各個版本託管到github上了,你們能夠去github上下載,(若是以爲不方便)也能夠去CSDN下載頻道下載,我已經上傳上去了,我用的是mybatis-3.3.0版本,csdn搜索下
從mybatis的jar包中就能夠看出,mybatis和hibernate有着強烈的對比,mybatis的jar包很簡潔,不像hibernate有不少jar包,mybatis的jar包包括一個核心包和幾個依賴包,咱們所有導入到工程中便可。而後就是MySQL的驅動包,也要導入到工程中。下面看一下總共須要導入的jar包: spring
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- mybatis支持 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <!--mysql支持 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.26</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.12</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.12</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.17.1-GA</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>org.ow2.asm</groupId> <artifactId>asm</artifactId> <version>4.2</version> </dependency> </dependencies>
喜歡用maven的也可使用上面的sql
從上面的jar包中能夠看出,mybatis的依賴包中有不少日誌包,既然mybatis依賴log4j,那咱們首先要創建一個log4j.properties文件,這個能夠在官方的文件中拷貝下,以下:數據庫
1 # Global logging configuration 2 # developer-->DEBUG productor-->INFO or ERROR 3 log4j.rootLogger=DEBUG, stdout 4 # MyBatis logging configuration... 5 log4j.logger.org.mybatis.example.BlogMapper=TRACE 6 # Console output... 7 log4j.appender.stdout=org.apache.log4j.ConsoleAppender 8 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 9 log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
在開發環境下日誌級別要設置成DEBUG,產品模式下能夠設置成INFO或者ERRORapache
mybatis須要配置一個全局配置文件SqlMapConfig.xml,這個文件是用來配置mybatis的運行環境,即數據源、事務等。咱們也能夠從官方的例子中拷貝一份,而後作一下修改:api
<?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整合後environment配置都會被幹掉 --> <environments default="development"> <environment id="development"> <!-- 使用jdbc事務管理,目前由mybatis來管理 --> <transactionManager type="JDBC" /> <!-- 數據庫鏈接池,目前由mybatis來管理 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <mappers> <mapper resource="sqlmap/User.xml" /> </mappers> </configuration>
以上這些環境配置(<environments>
標籤中的內容在之後和spring整合後,都會交給Spring來管理,如今暫時交給 mybatis來管理)中,修改爲本身數據庫相對應的狀況便可,<mapper>
標籤用來配置映射文件的,這些映射文件是針對不一樣的pojo的,這個示例中只操做一個User對象,因此只有一個配置文件,在sqlmap目錄下的User.xml,在下文中能夠看到。最後來看一下整個環境的結構:
安全
接下來就開始開發示例程序了。
2.程序的編寫
首先咱們得有一個pojo,在mybatis.po包中新建一個User.Java類:
public class User { private Integer id; private String username; private Date birthday; private String sex; private String address; public User(String username, Date birthday, String sex, String address) { this.username=username; this.birthday=birthday; this.sex=sex; this.address=address; } //省略get set
use mybatis drop table if exists user; create table user ( id int primary key not null auto_increment, username varchar(40), birthday date, sex char(1), address varchar(255) ); insert into user(username,birthday,sex,address) values("張三1","1990-09-19","男","山河"); insert into user(username,birthday,sex,address) values("張三2","1990-09-19","男","山河");
對應數據庫的建表語句如上
下面開始寫代碼,完成示例程序。
首先得建立配置文件User.xml,並在配置文件中建立sql語句,以下:
<?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="test"> <!-- 需求:經過id查詢用戶 --> <select id="findUserById" parameterType="int" resultType="mybatis.po.User"> select * from user where id = #{id} </select> </mapper>
來簡單解釋下該配置文件中一些參數的做用:
<select>
標籤:用於執行數據庫查詢的,全部關於查詢的都使用該標籤。有了User.xml配置文件後,須要在全局配置文件SqlMapConfig.xml中添加這個映射,上面已經添加過了,即:
<mappers> <mapper resource="sqlmap/User.xml" /> </mappers>
接下來就是寫測試類了:
public class MybatisFirst { //由於接下來的測試代碼中,獲取sqlSession這部分都相同,因此抽取成一個方法 public SqlSession getSession() throws IOException { String resource = "SqlMapConfig.xml"; //mybatis配置文件 //獲得配置文件的流 InputStream inputStream = Resources.getResourceAsStream(resource); //建立會話工廠SqlSessionFactory,要傳入mybaits的配置文件的流 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //經過工廠獲得SqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); return sqlSession; } //根據id查詢用戶的信息,獲得一條記錄的結果 @Test public void findUserById() throws IOException { SqlSession sqlSession = getSession(); //調用上面的方法獲取sqlSession //經過SqlSession操做數據庫 //第一個參數:映射文件中statement的id,= namespace + statement的id //第二個參數:指定和映射文件中所匹配的parameterType類型的參數 //selectOne表示查詢出一條記錄進行映射 User user = sqlSession.selectOne("test.findUserById", 1); System.out.println(user); //釋放資源,最好放在finally中,這裏只是測試程序,就不弄了 sqlSession.close(); } }
從java程序中能夠看出,這個流程很明確,就是上一節我畫的那個mybatis的流程圖,並且mybatis有個特色,就是要執行什麼語句,都寫在配置文件中,須要傳入或者輸出什麼參數類型也寫在配置文件中,在java中只要對應那個配置傳入咱們想要的參數或者接受輸出參數便可,很方便。
有了上面的過程,接下來就比較簡單了,使用mybatis開發,流程都同樣,先在User.xml中添加配置:
<mapper namespace="test"> <!-- 省略其餘 --> <!-- 根據用戶名稱模糊查詢用戶信息,可能返回多條 --> <select id="findUserByName" parameterType="java.lang.String" resultType="mybatis.po.User"> select * from user where username like '%${value}%' </select> </mapper>
來解釋下部分參數的做用:
1.resultType:這裏雖然是查詢多條記錄,可是resultType指定的就是單條記錄所映射的java對象類型。
2.${}:表示拼接sql串,將接收到的參數的內容不加任何的修飾拼接在sql中,${}中只能使用value,可是使用${}來拼接sql,可能會引發sql注入,因此不建議使用這種方法。
這裏使用${}來拼接sql是爲了後面java程序中直接輸入方便(好比我模糊查詢「張三」,就不用輸入「%張三%」了),可是有sql注入的隱患。若是安全一點,仍是使用#{}來接收參數,不過此時的話,java程序中輸入參數就得是「%張三%」了。
下面看下java程序:
public class MybatisFirst { //省略不相關代碼 //根據用戶名稱模糊查詢用戶列表 @Test public void findUserByName() throws IOException { SqlSession sqlSession = getSession(); //selectList表示查詢出一個列表(多條記錄)進行映射 List<User> list = sqlSession.selectList("test.findUserByName", "張三"); System.out.println(list); //釋放資源,最好放在finally中,這裏只是測試程序,就不弄了 sqlSession.close(); } }
處理流程和上面如出一轍,不在贅述。
首先完成添加用戶的配置文件:
<mapper namespace="test"> <!-- 省略不相關配置 --> <!-- 添加用戶 --> <insert id="insertUser" parameterType="mybatis.po.User"> insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address}) <!-- 將插入數據的主鍵返回,返回到user對象中 --> <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer"> select last_insert_id() </selectKey> <!-- <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String"> select uuid() </selectKey> --> </insert> </mapper>
下面解釋下部分屬性的做用:
1 <insert>標籤:用於執行數據庫查詢的,全部關於查詢的都使用該標籤。 2 parameterType:要傳入一個具體的pojo(包括用戶信息) 3 #{}中指定pojo的屬性名,接收到pojo對象的屬性值,mybatis經過OGNL獲取對象的屬性值。 4 <selectKey>標籤:用來返回插入數據的主鍵的,實際中若是有得到主鍵的須要就可使用它。 5 select last_insert_id():是sql函數,表示獲得剛剛insert進去記錄的主鍵值,只適用於自增主鍵。 6 keyProperty:表示將查詢到主鍵值設置到上面parameterType指定的對象的哪一個屬性。 7 order:表示select last_insert_id()的執行順序,是相對於insert語句來講的。 8 resultType:表示select last_insert_id()的結果類型。
下面看下java代碼:
public class MybatisFirst { //省略不相關代碼 //添加用戶信息 @Test public void insertUser() throws IOException { SqlSession sqlSession = getSession(); User user = new User("倪升武", new Date(), "男", "同濟大學"); sqlSession.insert("test.insertUser", user); //添加一項 //提交事務 sqlSession.commit(); System.out.println(user.getId()); //獲取剛剛添加的id //釋放資源,最好放在finally中,這裏只是測試程序,就不弄了 sqlSession.close(); } }
接下來都比較簡單了,基本參數的使用在上面都有涉及,我放在一塊兒寫了:
<mapper namespace="test"> <!-- 省略不相關配置 --> <!-- 刪除用戶 --> <delete id="deleteUser" parameterType="java.lang.Integer"> delete from user where id=#{id} </delete> <!-- 更新用戶 --> <update id="updateUser" parameterType="mybatis.po.User"> update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id} </update> </mapper>
下面看一下java代碼:
public class MybatisFirst { //刪除用戶信息 @Test public void deleteUser() throws IOException { SqlSession sqlSession = getSession(); //傳入id,刪除用戶 sqlSession.delete("test.deleteUser", 16); //提交事務 sqlSession.commit(); //釋放資源,最好放在finally中,這裏只是測試程序,就不弄了 sqlSession.close(); } //更新用戶信息 @Test public void updateUser() throws IOException { SqlSession sqlSession = getSession(); User user = new User("倪升武", new Date(), "男", "同濟大學"); user.setId(9); //更新用戶 sqlSession.update("test.updateUser", user); //提交事務 sqlSession.commit(); //釋放資源,最好放在finally中,這裏只是測試程序,就不弄了 sqlSession.close(); } }
好了,到這裏mybatis的入門程序就寫完了,從上面的程序來看,mybatis的基本操做仍是挺簡便的。主要要搞清楚mybatis的一個執行流程就比較好理解了。入門就總結這麼多吧,但願這篇博文能代領mybatis的初學者走進mybatis的世界,包括我~~