MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了google code,並且改名為MyBatis 。2013年11月遷移到Github。iBATIS一詞來源於“internet”和“abatis”的組合,是一個基於Java的持久層框架。
MyBatis是支持普通SQL查詢,存儲過程和高級映射的優秀持久層框架。MyBatis消除了幾乎所有的JDBC代碼和參數的手工設置以及對結果集的檢索封裝。MyBatis可以使用簡單的XML或注解用於配置和原始映射,將接口和Java的POJO(Plain Old Java Objects,普通的Java對象)映射成數據庫中的記錄。
首先需要加入需要的jar包,構建Spring環境請參考:Spring學習之第一個hello world程序。見 http://www.linuxidc.com/Linux/2016-05/131391.htm 這裡我們需要加入mybatis包和MySQL驅動包,使用IDEA環境來開發程序,最後工程加入的包如下圖所示:
然後需要在test數據庫中新建測試表user,sql語句如下所示:
create table users ( id int primary key auto_increment, name varchar(20), age int ); insert into users (name, age) values('Tom', 12); insert into users (name, age) values('Jack', 11);
public class User { private int id; private String name; private int age; public User() { } public User(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
mybatisConfig.xml文件,該文件是在src目錄下新建的。
<?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> <environments default="development"> <!-- development:開發環境 work:工作模式 --> <environment id="development"> <transactionManager type="JDBC" /> <!-- 數據庫連接方式 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://192.168.1.150/test" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <!-- 注冊表映射文件 --> <mappers> <mapper resource="com/mybatis/userMapper.xml"/> </mappers> </configuration>
userMapper.xml文件,該配置文件在com.mybatis包下,user表對應的實體類User也在com.mybatis包下。
<?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.mybatis.userMapper"> <!-- 根據id查詢一個User對象 --> <select id="getUser" parameterType="int" resultType="com.mybatis.User"> select * from users where id=#{id} </select> <select id="getUserAll" resultType="com.mybatis.User"> select * from users </select> <!-- 插入一個User對象 --> <insert id="insertUser" parameterType="com.mybatis.User"> insert into users (name, age) value(#{name}, #{age}) </insert> <!-- 刪除一個User對象 --> <delete id="deleteUser" parameterType="int"> delete from users where id=#{id} </delete> <!-- 更新一個User對象--> <update id="updateUser" parameterType="com.mybatis.User"> update users set name=#{name}, age=#{age} where id=#{id} </update> </mapper>
測試代碼如下:
public class mybaitstest { SqlSessionFactory sessionFactory = null; SqlSession sqlSession = null; { String resource = "mybatisConfig.xml"; // 加載mybatis的配置文件(它也加載關聯的映射文件) Reader reader = null; try { reader = Resources.getResourceAsReader(resource); } catch (IOException e) { e.printStackTrace(); } // 構建sqlSession的工廠 sessionFactory = new SqlSessionFactoryBuilder().build(reader); // 創建能執行映射文件中sql的sqlSession,默認是手動提交事務的,使用自動提交的話加上參數 true sqlSession = sessionFactory.openSession(true); } public void testSelectUser() { // 映射sql的標識字符串 String statement = "com.mybatis.userMapper" + ".getUser"; // 執行查詢返回一個唯一user對象的sql User user = sqlSession.selectOne(statement, 1); System.out.println(user); } public void testSelectAll() { List<User> users = sqlSession.selectList("com.mybatis.userMapper.getUserAll"); System.out.println(users); } public void testInsertUser(User user) { int insert = sqlSession.insert("com.mybatis.userMapper.insertUser", user); // 如果不是自動提交的話,需要使用 sqlSession。commit() System.out.println(insert); } public void testDeleteUser(int id) { int delete = sqlSession.delete("com.mybatis.userMapper.deleteUser", id); System.out.println(delete); } public void testUpdateUser(User user) { int update = sqlSession.update("com.mybatis.userMapper.updateUser", user); System.out.println(update); } public static void main(String[] args) throws IOException { new mybaitstest().testSelectUser(); } }
最後輸出結果為:
Spring中如何配置Hibernate事務 http://www.linuxidc.com/Linux/2013-12/93681.htm
Struts2整合Spring方法及原理 http://www.linuxidc.com/Linux/2013-12/93692.htm
基於 Spring 設計並實現 RESTful Web Services http://www.linuxidc.com/Linux/2013-10/91974.htm
Spring-3.2.4 + Quartz-2.2.0集成實例 http://www.linuxidc.com/Linux/2013-10/91524.htm
使用 Spring 進行單元測試 http://www.linuxidc.com/Linux/2013-09/89913.htm
運用Spring注解實現Netty服務器端UDP應用程序 http://www.linuxidc.com/Linux/2013-09/89780.htm
Spring 3.x 企業應用開發實戰 PDF完整高清掃描版+源代碼 http://www.linuxidc.com/Linux/2013-10/91357.htm
基於注解的方式使用MyBatis,首先定義對應表的sql映射接口。
public interface IUserMapper { @Insert("insert into users (name, age) value(#{name}, #{age})") public int add(User user); @Delete("delete from users where id=#{id}") public int deleteById(int id); @Update("update users set name=#{name}, age=#{age} where id=#{id}") public int update(User user); @Select("select * from users where id=#{id}") public User getById(int id); @Select("select * from users") public List<User> getAll(); }
然後在mybatisConfig.xml配置文件中注冊該接口:
<!-- 注冊表映射文件 --> <mappers> <mapper class="com.mybatis.IUserMapper"/> </mappers>
測試示例:
/** * 使用注解測試的方法 */ public void test() { IUserMapper userMapper = sqlSession.getMapper(IUserMapper.class); User user = userMapper.getById(1); System.out.println(user); }
以上兩個程序示例都是直接在配置文件中寫連接數據庫的信息,其實還可以專門把數據庫連接信息寫到一個db.proteries文件中,然後由配置文件來讀取該db.properies文件信息。db.proteries文件內容如下:
user=root password=123456 driverClass=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql://192.168.1.150/test
然後在mybatisConfig.xml配置文件中將數據庫環境信息更改為如下所示:
<properties resource="db.properties"/> <environments default="development"> <!-- development:開發環境 work:工作模式 --> <environment id="development"> <transactionManager type="JDBC" /> <!-- 數據庫連接方式 --> <dataSource type="POOLED"> <property name="driver" value="${driverClass}" /> <property name="url" value="${jdbcUrl}" /> <property name="username" value="${user}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments>
配置表對應的sql映射文件時,可以使用別名來簡化配置,在mybatisConfig.xml中添加如下配置,在userMapper中parameterType就可以配置為"_User"。
<typeAliases> <typeAlias type="com.mybatis.User" alias="_User"/> </typeAliases>
新建表和數據,在test數據庫中執行以下SQL語句:
create table orders ( order_id int primary key auto_increment, order_no varchar(20), order_price float ); insert into orders (order_no, order_price) values('aaa', 12); insert into orders (order_no, order_price) values('bbb', 13); insert into orders (order_no, order_price) values('ccc', 14);
創建對應表的類:
public class Order { private int i; private String no; private float price; public Order() { } public Order(int i, String no, float price) { this.i = i; this.no = no; this.price = price; } public int getI() { return i; } public void setI(int i) { this.i = i; } public String getNo() { return no; } public void setNo(String no) { this.no = no; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } }
mybaitsConfig.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"/> <typeAliases> <typeAlias type="com.mybatis.Order" alias="Order"/> </typeAliases> <environments default="development"> <!-- development:開發環境 work:工作模式 --> <environment id="development"> <transactionManager type="JDBC" /> <!-- 數據庫連接方式 --> <dataSource type="POOLED"> <property name="driver" value="${driverClass}" /> <property name="url" value="${jdbcUrl}" /> <property name="username" value="${user}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments> <!-- 注冊表映射文件 --> <mappers> <mapper resource="com/mybatis/orderMapper.xml"/> </mappers> </configuration>
接下來配置orderMapper.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.mybatis.orderMapper"> <!-- 根據id查詢一個Order對象 --> <select id="getOrder" parameterType="int" resultType="Order"> SELECT order_id id, order_no no, order_price price FROM orders WHERE order_id=#{id} </select> <!-- 這種解決字段與屬性沖突方式較常用 --> <select id="getOrder2" parameterType="int" resultType="Order" resultMap="getOrder2Map"> SELECT * FROM orders WHERE order_id=#{id} </select> <!-- resultMap 封裝映射關系 id 專門針對主鍵 result 針對一般字段 --> <resultMap id="getOrder2Map" type="Order"> <id property="id" column="order_id"/> <result property="no" column="order_price"/> <result property="price" column="order_price"/> </resultMap> </mapper>View Code
測試用例:
public class MyBaitsMain { SqlSessionFactory sessionFactory = null; SqlSession sqlSession = null; { String resource = "mybatisConfig.xml"; // 加載mybatis的配置文件(它也加載關聯的映射文件) Reader reader = null; try { reader = Resources.getResourceAsReader(resource); } catch (IOException e) { e.printStackTrace(); } // 構建sqlSession的工廠 sessionFactory = new SqlSessionFactoryBuilder().build(reader); // 創建能執行映射文件中sql的sqlSession,默認是手動提交事務的,使用自動提交的話加上參數 true sqlSession = sessionFactory.openSession(true); } public static void main(String[] args) { String statement = "com.mybatis.orderMapper.getOrder"; String statement2 = "com.mybatis.orderMapper.getOrder2"; Order order = new MyBaitsMain().sqlSession.selectOne(statement, 2); System.out.println(order); order = new MyBaitsMain().sqlSession.selectOne(statement2, 2); System.out.println(order); } }
輸出結果為:
這裡實現班級id查詢班級信息,班級信息中包括老師信息。首先創建表結構:
CREATE TABLE teacher( t_id INT PRIMARY KEY AUTO_INCREMENT, t_name VARCHAR(20) ); CREATE TABLE class( c_id INT PRIMARY KEY AUTO_INCREMENT, c_name VARCHAR(20), teacher_id INT ); ALTER TABLE class ADD CONSTRAINT fk_teacher_id FOREIGN KEY (teacher_id) REFERENCES teacher(t_id); INSERT INTO teacher(t_name) VALUES('LS1'); INSERT INTO teacher(t_name) VALUES('LS2'); INSERT INTO class(c_name, teacher_id) VALUES('bj_a', 1); INSERT INTO class(c_name, teacher_id) VALUES('bj_b', 2);View Code
定義表對應的實體類:
public class Teacher { private int id; private String name; public Teacher() { } public Teacher(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Teacher{" + "id=" + id + ", name='" + name + '\'' + '}'; } }Teacher類
public class Classes { private int id; private String name; private Teacher teacher; public Classes() { } public Classes(int id, String name, Teacher teacher) { this.id = id; this.name = name; this.teacher = teacher; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Teacher getTeacher() { return teacher; } public void setTeacher(Teacher teacher) { this.teacher = teacher; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Classes{" + "id=" + id + ", name='" + name + '\'' + ", teacher=" + teacher + '}'; } }Classes類
定義sql映射文件,需要在mybatisConfig.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.mybatis.classesMapper"> <!-- 根據班級id查詢班級信息(包括老師信息) --> <select id="getClasses" parameterType="int" resultMap="ClassesMap"> SELECT * FROM class c, teacher t WHERE c.teacher_id = t.t_id and c.c_id = #{id} </select> <!-- 聯表查詢 --> <resultMap id="ClassesMap" type="com.mybatis.Classes"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" javaType="com.mybatis.Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> </resultMap> <!-- 嵌套查詢 --> <select id="getClasses2" parameterType="int" resultMap="ClassesMap2"> SELECT * FROM class WHERE c_id=#{id} </select> <select id="getTeacher" parameterType="int" resultType="com.mybatis.Teacher"> SELECT t_id id, t_name FROM teacher WHERE t_id=#{id} </select> <resultMap id="ClassesMap2" type="com.mybatis.Classes"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" select="getTeacher"> </association> </resultMap> </mapper>classesMapper.xml文件
測試類:
public class MyBaitsMain { SqlSessionFactory sessionFactory = null; SqlSession sqlSession = null; { String resource = "mybatisConfig.xml"; // 加載mybatis的配置文件(它也加載關聯的映射文件) Reader reader = null; try { reader = Resources.getResourceAsReader(resource); } catch (IOException e) { e.printStackTrace(); } // 構建sqlSession的工廠 sessionFactory = new SqlSessionFactoryBuilder().build(reader); // 創建能執行映射文件中sql的sqlSession,默認是手動提交事務的,使用自動提交的話加上參數 true sqlSession = sessionFactory.openSession(true); } public static void main(String[] args) { String statement = "com.mybatis.classesMapper.getClasses"; String statement2 = "com.mybatis.classesMapper.getClasses2"; Classes classes = new MyBaitsMain().sqlSession.selectOne(statement, 1); System.out.println(classes); classes = new MyBaitsMain().sqlSession.selectOne(statement2, 1); System.out.println(classes); } }MyBatisMain測試類
輸出結果:
這裡實現班級id查詢班級信息,班級信息中包括老師信息和學生信息。首先創建表結構:
CREATE TABLE student( s_id INT PRIMARY KEY AUTO_INCREMENT, s_name VARCHAR(20), class_id INT ); INSERT INTO student(s_name, class_id) VALUES('xs_A', 1); INSERT INTO student(s_name, class_id) VALUES('xs_B', 1); INSERT INTO student(s_name, class_id) VALUES('xs_C', 1); INSERT INTO student(s_name, class_id) VALUES('xs_D', 2); INSERT INTO student(s_name, class_id) VALUES('xs_E', 2); INSERT INTO student(s_name, class_id) VALUES('xs_F', 2);
定義表對應的實體類:
public class Student {定義sql映射文件,需要在mybatisConfig.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.mybatis.classesMapper2"> <select id="getClasses" parameterType="int" resultMap="ClassesMap"> SELECT * FROM class c, student s, teacher t WHERE c.c_id=s.class_id AND c.c_id=#{id} </select> <resultMap id="ClassesMap" type="com.mybatis.Classes"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" javaType="com.mybatis.Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> <!-- collection: 做一對多關聯查詢的 ofType: 指定集合中元素對象的類型 --> <collection property="students" ofType="com.mybatis.Student"> <id property="id" column="s_id"/> <result property="name" column="s_name"/> </collection> </resultMap> <!-- 第二種方式 --> <select id="getClasses2" resultMap="ClassesMap2"> SELECT * FROM class WHERE c_id=#{id} </select> <select id="getTeacher" resultType="com.mybatis.Teacher"> SELECT t_id id, t_name name FROM teacher WHERE t_id=#{id} </select> <select id="getStudent" resultType="com.mybatis.Student"> SELECT s_id id, s_name name FROM student WHERE class_id=#{id} </select> <resultMap id="ClassesMap2" type="com.mybatis.Classes"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" select="getTeacher"> </association> <collection property="students" column="c_id" select="getStudent"> </collection> </resultMap> </mapper>classesMapper2.xml文件
測試類:
public class MyBaitsMain { SqlSessionFactory sessionFactory = null; SqlSession sqlSession = null; { String resource = "mybatisConfig.xml"; // 加載mybatis的配置文件(它也加載關聯的映射文件) Reader reader = null; try { reader = Resources.getResourceAsReader(resource); } catch (IOException e) { e.printStackTrace(); } // 構建sqlSession的工廠 sessionFactory = new SqlSessionFactoryBuilder().build(reader); // 創建能執行映射文件中sql的sqlSession,默認是手動提交事務的,使用自動提交的話加上參數 true sqlSession = sessionFactory.openSession(true); } public static void main(String[] args) { String statement = "com.mybatis.classesMapper2.getClasses"; String statement2 = "com.mybatis.classesMapper2.getClasses2"; Classes classes = new MyBaitsMain().sqlSession.selectOne(statement, 1); System.out.println(classes); classes = new MyBaitsMain().sqlSession.selectOne(statement2, 1); System.out.println(classes); } }MyBaitsMain測試類
輸出結果:
更多詳情見請繼續閱讀下一頁的精彩內容: http://www.linuxidc.com/Linux/2016-06/132194p2.htm