MyBatis示例 之 初学者教程

iBatis(当前称为 MyBatis)是另一个 popular 的持久性框架(如 hibernate),它可以自动执行SQL数据库对象(例如表)与Java,.NET和Ruby on Rails中的对象之间的映射。此映射是使用xml配置文件创建和维护的。这些配置文件包含各种SQL语句和其他与框架相关的选项。

与其他持久性框架相比,iBatis 的主要优点在于,它提供了更大的灵活性并可以控制SQL语句的编写。这意味着任何数据库专家都可以编写这些优化的语句,而Java开发人员只需要将其合并为xml文件即可。

iBatis教程中,我们将学习使用iBatis开发第一个hello world应用程序。我建议您自己按照以下步骤操作,但是如果您急忙,请直接下载源代码

1.在Eclipse中创建Maven应用程序

为此,请打开命令提示符并导航到工作区。运行以下命令:

mvn原型:generate -DgroupId = com.how2codex.ibatis.demo -DartifactId = ibatisHelloWorld 
-DarchetypeArtifactId = maven-archetype-quickstart -DinteractiveMode = false

此命令将在您的工作区中创建一个默认的Maven项目。现在将其转换为Eclipse项目。

mvn eclipse:eclipse

在eclipse中导入项目。

2. iBatis Maven依赖项

将iBatis添加到项目中需要以下依赖项。

<dependency>
    <groupid>org.apache.ibatis</groupid>
    <artifactid>ibatis-sqlmap</artifactid>
    <version>2.3.4.726</version>
</dependency>

我正在使用MySQL作为数据库。因此添加了数据库连接驱动程序支持。

<dependency>
    <groupid>mysql</groupid>
    <artifactid>mysql-connector-java</artifactid>
    <version>5.1.9</version>
</dependency>

为了进行日志记录,请添加log4j支持。

<dependency>
    <groupid>log4j</groupid>
    <artifactid>log4j</artifactid>
    <version>1.2.17</version>
</dependency>

3.创建数据库

在mysql中创建新的数据库demoDB并创建一个新表USERINFO。我们将使用此表进行数据持久化。

创建表USERINFO

ID  INT,
NAME  VARCHAR(100),
EMAIL  VARCHAR(50),
PASSWORD  VARCHAR(16),
STATUS  INT
);

4.创建模型类

将要映射到数据库中表的模型类。此类实际上是一个POJO,它将在数据库表中的对应列中仅包含一个字段。

package com.how2codex.ibatis.demo.dto;
public class UserTEO
{
    private Integer id;
    private String name;
    private String email;
    private String password;
    private int status;
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getStatus() {
        return status;
    }
    public void setStatus(int status) {
        this.status = status;
    }
}

5. DAO – SqlMapClient

继承接口UserDao来实现UserDaoIbatis,可以根据您的喜好使用不同的类名称。

UserDaoIbatis.java
package com.how2codex.ibatis.demo.dao;
import com.how2codex.ibatis.demo.dto.UserTEO;
import com.ibatis.sqlmap.client.SqlMapClient;
public class UserDaoIbatis implements UserDao
{
    @Override
    public UserTEO addUser(UserTEO user, SqlMapClient sqlmapClient) {
        try
        {
            Integer id = (Integer)sqlmapClient.queryForObject("user.getMaxId");
            id = id == null ? 1 : id + 1;
            user.setId(id);
            user.setStatus(1);
            sqlmapClient.insert("user.addUser", user);
            user = getUserById(id, sqlmapClient);
            return user;
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    public UserTEO getUserById(Integer id, SqlMapClient sqlmapClient) {
        try
        {
            UserTEO user = (UserTEO)sqlmapClient.queryForObject("user.getUserById", id);
            return user;
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    public void deleteUserById(Integer id, SqlMapClient sqlmapClient) {
        try
        {
            sqlmapClient.delete("user.deleteUserById", id);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

6.编写sqlmaps和sqlmap配置

这是主要部分。sqlmap config中,我们需要提供配置文件,例如databse连接属性和sqlmaps的路径,以便在其中编写实际的sql查询。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig
        PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
<sqlMapConfig>
    
    <settings useStatementNamespaces="true"/>
    
    <transactionManager type="JDBC">
        <dataSource type="SIMPLE">
          <property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
          <property name="JDBC.ConnectionURL"  value="jdbc:mysql://localhost:3306/demoDB"/>
          <property name="JDBC.Username" value="root"/>
          <property name="JDBC.Password" value="lg225295"/>
        </dataSource>
      </transactionManager>
    
    <sqlMap resource="user.xml"/>
</sqlMapConfig>

让我们编写带有查询的sqlmap并将结果映射到UserTEO

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap  PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="user">
    <typeAlias alias="USER" type="com.how2codex.ibatis.demo.dto.UserTEO" />
    <resultMap id="userResultMap" class="USER">
        <result property="id" column="ID" />
        <result property="name" column="NAME" />
        <result property="email" column="EMAIL" />
        <result property="password" column="PASSWORD" />
        <result property="status" column="STATUS" />
    </resultMap>
    
    <select id="getUserById" parameterClass="java.lang.Integer" resultMap="userResultMap">
          SELECT * FROM USERINFO WHERE ID = #value#
    </select>
    
    <select id="getMaxId" resultClass="java.lang.Integer">
          SELECT MAX(ID) FROM USERINFO
    </select>
    
    <insert id="addUser" parameterClass="USER">
        INSERT INTO USERINFO (ID,NAME,EMAIL,PASSWORD,STATUS)
         VALUES(#id#,#name#,#email#,#password#,#status#);
    </insert>
    
    <delete id="deleteUserById" parameterClass="java.lang.Integer">
          DELETE FROM USERINFO WHERE ID = #value#
    </delete>
    
</sqlMap>

7. iBatis演示

要测试iBatis hello世界示例,我们需要创建sqlmapClient,相当于EntityManager在JPA中起的作用。它将连接到数据库并执行所需的查询,并将结果更新回数据映射器

SQLMapClient可以在不同的框架中以不同的方式构建,但是由于这是ibatis示例应用程序,因此我使用代码创建它。

package com.how2codex.ibatis.demo;
import java.io.Reader;
import com.how2codex.ibatis.demo.dao.UserDao;
import com.how2codex.ibatis.demo.dao.UserDaoIbatis;
import com.how2codex.ibatis.demo.dto.UserTEO;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
public class TestMain
{
    public static void main(String[] args) throws Exception
    {
        //Initialize dao
        UserDao manager = new UserDaoIbatis();
        //Create the SQLMapClient
        Reader reader = Resources.getResourceAsReader("sql-maps-config.xml");
        SqlMapClient sqlmapClient = SqlMapClientBuilder.buildSqlMapClient (reader);
        //Create a new user to persist
        UserTEO user = new UserTEO();
        user.setId(1);
        user.setName("Demo User");
        user.setPassword("password");
        user.setEmail("demo-user@how2codex.com");
        user.setStatus(1);
        //Add the user
        manager.addUser(user,sqlmapClient);
        //Fetch the user detail
        UserTEO createdUser = manager.getUserById(1, sqlmapClient);
        System.out.println(createdUser.getEmail());
        //Lets delete the user
        manager.deleteUserById(1, sqlmapClient);
    }
}

在main方法上面运行将执行sql命令,可以使用生成的日志进行验证。

用户创建的ibatis

DEBUG [main] - Created connection 12589126.
DEBUG [main] - {conn-100000} Connection
DEBUG [main] - {conn-100000} Preparing Statement:      SELECT MAX(ID) FROM USERINFO
DEBUG [main] - {pstm-100001} Executing Statement:      SELECT MAX(ID) FROM USERINFO
DEBUG [main] - {pstm-100001} Parameters: []
DEBUG [main] - {pstm-100001} Types: []
DEBUG [main] - {rset-100002} ResultSet
DEBUG [main] - {rset-100002} Header: [MAX(ID)]
DEBUG [main] - {rset-100002} Result: [null]
DEBUG [main] - Returned connection 12589126 to pool.
DEBUG [main] - Checked out connection 12589126 from pool.
DEBUG [main] - {conn-100003} Connection
DEBUG [main] - {conn-100003} Preparing Statement:    INSERT INTO USERINFO (ID,NAME,EMAIL,PASSWORD,STATUS)    VALUES(?,?,?,?,?);
DEBUG [main] - {pstm-100004} Executing Statement:    INSERT INTO USERINFO (ID,NAME,EMAIL,PASSWORD,STATUS)    VALUES(?,?,?,?,?);
DEBUG [main] - {pstm-100004} Parameters: [1, Demo User, demo-user@how2codex.com, password, 1]
DEBUG [main] - {pstm-100004} Types:
DEBUG [main] - Returned connection 12589126 to pool.
DEBUG [main] - Checked out connection 12589126 from pool.
DEBUG [main] - {conn-100005} Connection
DEBUG [main] - {conn-100005} Preparing Statement:      SELECT * FROM USERINFO WHERE ID = ?
DEBUG [main] - {pstm-100006} Executing Statement:      SELECT * FROM USERINFO WHERE ID = ?
DEBUG [main] - {pstm-100006} Parameters: [1]
DEBUG [main] - {pstm-100006} Types:
DEBUG [main] - {rset-100007} ResultSet
DEBUG [main] - {rset-100007} Header: [ID, NAME, EMAIL, PASSWORD, STATUS]
DEBUG [main] - {rset-100007} Result: [1, Demo User, demo-user@how2codex.com, password, 1]
DEBUG [main] - Returned connection 12589126 to pool.
DEBUG [main] - Checked out connection 12589126 from pool.
DEBUG [main] - {conn-100008} Connection
DEBUG [main] - {conn-100008} Preparing Statement:      SELECT * FROM USERINFO WHERE ID = ?
DEBUG [main] - {pstm-100009} Executing Statement:      SELECT * FROM USERINFO WHERE ID = ?
DEBUG [main] - {pstm-100009} Parameters: [1]
DEBUG [main] - {pstm-100009} Types:
DEBUG [main] - {rset-100010} ResultSet
DEBUG [main] - {rset-100010} Header: [ID, NAME, EMAIL, PASSWORD, STATUS]
DEBUG [main] - {rset-100010} Result: [1, Demo User, demo-user@how2codex.com, password, 1]
DEBUG [main] - Returned connection 12589126 to pool.
demo-user@how2codex.com
DEBUG [main] - Checked out connection 12589126 from pool.
DEBUG [main] - {conn-100011} Connection
DEBUG [main] - {conn-100011} Preparing Statement:      DELETE FROM USERINFO WHERE ID = ?
DEBUG [main] - {pstm-100012} Executing Statement:      DELETE FROM USERINFO WHERE ID = ?
DEBUG [main] - {pstm-100012} Parameters: [1]
DEBUG [main] - {pstm-100012} Types:
DEBUG [main] - Returned connection 12589126 to pool.

学习愉快!

saigon has written 1440 articles

Leave a Reply