MyBatis Example

Firstly, give you a simple example as a tutorial, then you will get an another example to explain the detail usage:

In this examples you will see how to create or define a data mapper using the MyBatis. The mapper will communicate our application with the underlying databases where the data is stored. MyBatis data mapper is defined as an interface object. We can either use annotations or the xml mapper to define our database query.

In the first steps we will create a domain object, a simple pojo to store our data in the object world. The attributes / fields of our pojo resemble the structure of our records table in the database.

package org.kodejava.example.mybatis.domain;

import java.io.Serializable;
import java.util.Date;

public class Record implements Serializable {
    private Integer id;
    private String title;
    private Date releaseDate;
    private Integer artistId;
    private Integer labelId;
    private Date created;
    private Date modified;

    public Record() {
    }

    //
    // Define the getters and setters for our pojo.
    //
    // ...
    // ...
    // ...

    @Override
    public String toString() {
        return "Record{" +
                "id=" + id +
                ", title='" + title + "'" +
                ", releaseDate=" + releaseDate +
                ", artistId=" + artistId +
                ", labelId=" + labelId +
                "}";
    }
}

Next we define the mapper interface code, we’ll create a RecordMapper.java file that contains a method to get data from the table. At this time the interface will be as the following:

package org.kodejava.example.mybatis.persistence;

import org.kodejava.example.mybatis.domain.Record;

public interface RecordMapper {
    /**
     * Get a single Record from the database based on the record
     * identified.
     * 
     * @param id record identifier.
     * @return a record object.
     */
    Record getRecord(int id);
}

After create the ResultMapper.java interface we create a RecordMapper.xml file that defines the queries used by our mapper. Here is how it looks like:

<?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="org.kodejava.example.mybatis.persistence.RecordMapper">

    <resultMap id="recordResultMap" type="record">
        <result column="release_date" property="releaseDate"/>
        <result column="artist_id" property="artistId"/>
        <result column="label_id" property="labelId"/>
    </resultMap>

    <select id="getRecord" parameterType="int" resultMap="recordResultMap">
        SELECT
            id,
            title,
            release_date,
            artist_id,
            label_id,
            created,
            modified
        FROM records
        WHERE id = #{id}
    </select>
</mapper>

To tell MyBatis about our mapper we need to define the mapper inside MyBatis configuration file. We register the mapper inside the <mappers> element of the configuration file.

<?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="record" type="org.kodejava.example.mybatis.domain.Record"/>
    </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/mediadb"/>
                <property name="username" value="root"/>
                <property name="password" value="welcome"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="org/kodejava/example/mybatis/persistence/RecordMapper.xml"/>
    </mappers>
</configuration>

Finally, we create a simple application to use the data mapper to get record data from the database.

package org.kodejava.example.mybatis;

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.kodejava.example.mybatis.domain.Record;
import org.kodejava.example.mybatis.persistence.RecordMapper;

import java.io.Reader;

public class MediaClient {
    public static void main(String[] args) throws Exception {
        String resource = "org/kodejava/example/mybatis/Configuration.xml";
        Reader reader = Resources.getResourceAsReader(resource);

        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(reader);

        SqlSession session = factory.openSession();
        try {
            RecordMapper mapper = session.getMapper(RecordMapper.class);
            Record record = mapper.getRecord(1);
            System.out.println("Record = " + record);
        } finally {
            session.close();
        }
    }
}


 

在SSH框架盛行的時代,ORM和持久層框架都不斷響徹在耳邊,今天小編就帶領大家一起來認識另一種持久層框架;

一、基本概況

        MyBatis是一個支持普通SQL查詢,存儲過程和高級映射的優秀持久層框架。MyBatis可以使用簡單的XML或註解用於配置和原始映射,將接口和Java的POJO對象映射成數據庫中的記錄。

框架圖如下;

二、入門教程(使用mysql的數據庫)

1. 搭建開發環境:

  創建一個普通的Java項目,如下圖所示:

                         

 添加數據庫和mybatis的jar包;

創建數據庫,並建立數據表:

[sql]  view plain  copy
  1. <span style="font-size:18px;">CREATE TABLE `items` (  
  2.   `id` int(11) NOT NULL AUTO_INCREMENT,  
  3.   `namevarchar(32) NOT NULL COMMENT '商品名稱',  
  4.   `price` float(10,1) NOT NULL COMMENT '商品定價',  
  5.   `detail` text COMMENT '商品描述',  
  6.   `pic` varchar(64) DEFAULT NULL COMMENT '商品圖片',  
  7.   `createtime` datetime NOT NULL COMMENT '生產日期',  
  8.   PRIMARY KEY (`id`)  
  9. ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;  
  10.   
  11. /*Table structure for table `orderdetail` */  
  12.   
  13. CREATE TABLE `orderdetail` (  
  14.   `id` int(11) NOT NULL AUTO_INCREMENT,  
  15.   `orders_id` int(11) NOT NULL COMMENT '訂單id',  
  16.   `items_id` int(11) NOT NULL COMMENT '商品id',  
  17.   `items_num` int(11) DEFAULT NULL COMMENT '商品購買數量',  
  18.   PRIMARY KEY (`id`),  
  19.   KEY `FK_orderdetail_1` (`orders_id`),  
  20.   KEY `FK_orderdetail_2` (`items_id`),  
  21.   CONSTRAINT `FK_orderdetail_1` FOREIGN KEY (`orders_id`) REFERENCES `orders` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,  
  22.   CONSTRAINT `FK_orderdetail_2` FOREIGN KEY (`items_id`) REFERENCES `items` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION  
  23. ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;  
  24.   
  25. /*Table structure for table `orders` */  
  26.   
  27. CREATE TABLE `orders` (  
  28.   `id` int(11) NOT NULL AUTO_INCREMENT,  
  29.   `user_id` int(11) NOT NULL COMMENT '下單用戶id',  
  30.   `number` varchar(32) NOT NULL COMMENT '訂單號',  
  31.   `createtime` datetime NOT NULL COMMENT '創建訂單時間',  
  32.   `note` varchar(100) DEFAULT NULL COMMENT '備註',  
  33.   PRIMARY KEY (`id`),  
  34.   KEY `FK_orders_1` (`user_id`),  
  35.   CONSTRAINT `FK_orders_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION  
  36. ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;  
  37.   
  38. /*Table structure for table `user` */  
  39.   
  40. CREATE TABLE `user` (  
  41.   `id` int(11) NOT NULL AUTO_INCREMENT,  
  42.   `username` varchar(32) NOT NULL COMMENT '用戶名稱',  
  43.   `birthday` date DEFAULT NULL COMMENT '生日',  
  44.   `sex` char(1) DEFAULT NULL COMMENT '性別',  
  45.   `address` varchar(256) DEFAULT NULL COMMENT '地址',  
  46.   PRIMARY KEY (`id`)  
  47. ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;</span>  

2. 實例-- 查詢用戶表中姓名爲「小明」的模糊查詢

  在src中建立數據庫的配置文件(db.properties)和日誌的配置文件(log4j.properties),並創建用戶的實體類(User.java)

     db.properties

[html]  view plain  copy
  1.   在src中建立數據庫的配置文件(db.properties)和日誌的配置文件(log4j.properties),並創建用戶的實體類(User.java)

         db.properties

    [html]  view plain  copy
    1. <span style="font-size:18px;">jdbc.driver=com.mysql.jdbc.Driver  
    2. jdbc.url=jdbc:mysql://localhost:3306/mybatis  
    3. jdbc.username=root  
    4. jdbc.password=mysql</span>  
    log4j.properties:

    1. <span style="font-size:18px;">jdbc.driver=com.mysql.jdbc.Driver  
    2. jdbc.url=jdbc:mysql://localhost:3306/mybatis  
    3. jdbc.username=root  
    4. jdbc.password=mysql</span>  
    log4j.properties:

    [html]  view plain  copy
        copy
相關文章
相關標籤/搜索