mybatis是個持久層的框架,用來執行數據庫操作的,無外乎增刪改查,上一節對mybatis有了宏觀上的了解后,這一篇博客主要通過一個小示例來入門mybatis,先看一下要寫的示例需求:
根據用戶id查詢用戶信息
根據用戶名稱模糊查詢用戶信息
添加用戶、刪除用戶、更新用戶
其實也就是增刪改查,掌握這些,基本上就掌握了mybatis的基本操作了,下面一個個模塊來完成。
1.MyBatis環境準備
毫無疑問,砍柴得有把刀才行,環境的搭建是開發中必需的一個流程,mybatis的環境我分成以下幾個部分來總結:
1.1 mybatis運行環境
mybatis運行環境主要是指mybatis的jar包,mybatis已經將它的各個版本托管到github上了,大家可以去github上下載,(如果覺得不方便)也可以去CSDN下載頻道下載,我已經上傳上去了,我用的是mybatis-3.3.0版本,csdn搜索下
從mybatis的jar包中就可以看出,mybatis和hibernate有著強烈的對比,mybatis的jar包很簡潔,不像hibernate有很多jar包,mybatis的jar包包括一個核心包和幾個依賴包,我們全部導入到工程中即可。然后就是MySQL的驅動包,也要導入到工程中。下面看一下總共需要導入的jar包:
<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的也可以使用上面的
1.2 log4j配置文件
從上面的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或者ERROR
1.3 全局配置文件
mybatis需要配置一個全局配置文件SqlMapConfig.xml,這個文件是用來配置mybatis的運行環境,即數據源、事務等。我們也可以從官方的例子中拷貝一份,然后做一下修改:
<?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","男","山河");
對應數據庫的建表語句如上
下面開始寫代碼,完成示例程序。
2.1 根據用戶id查詢用戶信息
首先得創建配置文件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>
標簽:用于執行數據庫查詢的,所有關于查詢的都使用該標簽。- id屬性:標識映射文件中的sql,將sql語句封裝到mappedStatement對象中,即statement的id,下面執行數據庫的時候需要用到這個id。
- #{}:表示一個占位符,用來接收輸入參數的。
- #{id}:id標識接收輸入的參數,參數名稱就是id,如果輸入參數是簡單類型,那么#{}中的參數名可以任意,可以value或者其他名稱。
- parameterType:指定輸入參數的類型,這個要和數據庫中的保持一致。
- resultType:指定輸出結果的類型,即查詢結果所映射的java對象。
有了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中只要對應那個配置傳入我們想要的參數或者接受輸出參數即可,很方便。
2.2 根據用戶名稱模糊查詢用戶信息
有了上面的過程,接下來就比較簡單了,使用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(); } }
處理流程和上面一模一樣,不在贅述。
2.3 添加用戶
首先完成添加用戶的配置文件:
<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(); } }
2.4 更新用戶和刪除用戶
接下來都比較簡單了,基本參數的使用在上面都有涉及,我放在一起寫了:
<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的世界,包括我~~
文章列表