MyBatis是什么
MyBatis是什么,MyBatis的jar包中有它的官方文檔,文檔是這么描述MyBatis的:
MyBatis is a first class persistence framework with support for custom SQL, stored procedures and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJOs (Plain Old Java Objects) to database records.
翻譯過來就是:MyBatis是一款支持普通SQL查詢、存儲過程和高級映射的持久層框架。MyBatis消除了幾乎所有的JDBC代碼、參數的設置和結果集的檢索。MyBatis可以使用簡單的XML或注解用於參數配置和原始映射,將接口和Java POJO(普通Java對象)映射成數據庫中的記錄。
本文先入門地搭建表、建立實體類、寫基礎的配置文件、寫簡單的Java類,從數據庫中查出數據,深入的內容后面的文章再逐一研究。
建表、建立實體類
從簡單表開始研究MyBatis,所以我們先建立一張簡單的表:
create table student ( studentId int primary key auto_increment not null, studentName varchar(20) not null, studentAge int not null, studentPhone varchar(20) not null )charset=utf8 insert into student values(null, 'Jack', 20, '000000'); insert into student values(null, 'Mark', 21, '111111'); insert into student values(null, 'Lily', 22, '222222'); insert into student values(null, 'Lucy', 23, '333333'); commit;
一個名為student的表格,里面存放了student相關字段,當然此時我們需要有一個Java實體類與之對應:
public class Student { private int studentId; private String studentName; private int studentAge; private String studentPhone; public Student() { super(); } public Student(int studentId, String studentName, int studentAge, String studentPhone) { this.studentId = studentId; this.studentName = studentName; this.studentAge = studentAge; this.studentPhone = studentPhone; } public int getStudentId() { return studentId; } public void setStudentId(int studentId) { this.studentId = studentId; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public int getStudentAge() { return studentAge; } public void setStudentAge(int studentAge) { this.studentAge = studentAge; } public String getStudentPhone() { return studentPhone; } public void setStudentPhone(String studentPhone) { this.studentPhone = studentPhone; } public String toString() { return "StudentId:" + studentId + "\tStudentName:" + studentName + "\tStudentAge:" + studentAge + "\tStudentPhone:" + studentAge; } }
注意,這里空構造方法必須要有,SqlSession的selectOne方法查詢一條信息的時候會調用空構造方法去實例化一個domain出來。OK,這樣student表及其對應的實體類Student.java就創建好了。
寫config.xml文件
在寫SQL語句之前,首先得有SQL運行環境,因此第一步是配置SQL運行的環境。創建一個Java工程,右鍵src文件夾,創建一個普通文件,取個名字叫做config.xml,config.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> <typeAliases> <typeAlias alias="Student" type="com.xrq.domain.Student"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="student.xml"/> </mappers> </configuration>
這就是一個最簡單的config.xml的寫法。接着右鍵src,創建一個普通文件,命名為student.xml,和mapper里面的一致(resource沒有任何的路徑則表示student.xml和config.xml同路徑),student.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="com.xrq.StudentMapper"> <select id="selectStudentById" parameterType="int" resultType="Student"> <![CDATA[ select * from student where studentId = #{id} ]]> </select> </mapper>
專門有一個student.xml表示student表的sql語句,當然也可以幾張表共用一個.xml文件,這個看自己的項目和個人喜好。至此,MyBatis需要的兩個.xml文件都已經建立好,接下來需要做的就是寫Java代碼了。
Java代碼實現
首先要進入MyBatis的jar包:
第二個MySql-JDBC的jar包注意一下要引入,這個很容易忘記。
接着創建一個類,我起名字叫做StudentOperator,由於這種操作數據庫的類被調用頻繁但是調用者之間又不存在數據共享的問題,因此使用單例會比較節省資源。為了好看,寫一個父類BaseOperator,SqlSessionFactory和Reader都定義在父類里面,子類去繼承這個父類:
public class BaseOperator { protected static SqlSessionFactory ssf; protected static Reader reader; static { try { reader = Resources.getResourceAsReader("config.xml"); ssf = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); } } }
然后創建子類StudentOperator:
public class StudentOperator extends BaseOperator { private static StudentOperator instance = new StudentOperator(); private StudentOperator() { } public static StudentOperator getInstance() { return instance; } public Student selectStudentById(int studentId) { SqlSession ss = ssf.openSession(); Student student = null; try { student = ss.selectOne("com.xrq.StudentMapper.selectStudentById", 1); } finally { ss.close(); } return student; } }
這個類里面做了兩件事情:
1、構造一個StudentOperator的單實例
2、寫一個方法根據studentId查詢出一個指定的Student
驗證
至此,所有步驟全部就緒,接着寫一個類來驗證一下:
public class MyBatisTest { public static void main(String[] args) { System.out.println(StudentOperator.getInstance().selectStudentById(1)); } }
運行結果為:
StudentId:1 StudentName:Jack StudentAge:20 StudentPhone:20
看一下數據庫中的數據:
數據一致,說明以上的步驟都OK,MyBatis入門完成,后面的章節,將會針對MyBatis的使用細節分別進行研究。