iBatis开发的一个应用

JavaWeb技术篇 尼古拉斯.赵四 222601℃ 0评论

今天开始学习iBatis框架,感觉这个框架很轻巧,方便,使用上手很快,没有多大的难点,下面就介绍一下第一个应用开发的步骤:

第一步:在mysql的test数据库中建立一张表:account

create table account(
_id int,first_name varchar(10),
last_name varchar(10),
emall varchar(10),
primary key(_id)
)engine=InnoDB default charset=gb2312;

然后插入两条测试数据:

insert account(_id,first_name,last_name,emall) values(1,'jiangwei','wei','123@qq.com');
insert account(_id,first_name,last_name,emall) values(2,'huang','yang','234@qq.com');

这样第一步就完成了

第二步:开始配置iBatis文件:

首先来看一下应用工程的结构图:


配置:Account.xml:

<?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="Account">//命名空间

  <!-- 给Account实体类起一个别名 -->
  <typeAlias alias="Account" type="com.ibatis.demo.domain.Account"/>

  <!-- 将Account实体类中的属性和mysql中的account表中的字段对应起来 -->
  <resultMap id="AccountResult" class="Account">
    <result property="id" column="_id"/>
    <result property="firstName" column="first_name"/>
    <result property="lastName" column="last_name"/>
    <result property="emailAddress" column="emall"/>
  </resultMap>

  <!-- 查询account表中所有数据,其中id是这条查询语句的id号,在代码中用到,具有唯一性 -->
  <select id="selectAllAccounts" resultMap="AccountResult">
    select * from account
  </select>

  <!-- 通过id来查询account表中的数据 -->
  <select id="selectAccountById" parameterClass="int" resultClass="Account">
    select
      id as _id,
      first_name as firstName,
      last_name as lastName,
      emall as emailAddress
    from account
    where _id = #id#
  </select>
   
  <!--插入语句-->
  <insert id="insertAccount" parameterClass="Account">
    insert into accout (
      _id,
      first_name,
      last_name,
      emall
    values (
      #id#, #firstName#, #lastName#, #emailAddress#
    )
  </insert>

  <!-- 更新语句 -->
  <update id="updateAccount" parameterClass="Account">
    update account set
      first_name = #firstName#,
      last_name = #lastName#,
      emall = #emailAddress#
    where
      _id = #id#
  </update>

  <!-- 删除语句 -->
  <delete id="deleteAccountById" parameterClass="int">
    delete from account where _id = #id#
  </delete>

</sqlMap>

 

上面的配置完成后,接下来开始配置全局的文件:SqlMapConfig.xml:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE sqlMapConfig      
    PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"      
    "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<sqlMapConfig>

  <!-- 配置数据库连接 -->
  <transactionManager type="JDBC" commitRequired="false">
    <dataSource type="SIMPLE">
        <property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
        <property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8"/>
        <property name="JDBC.Username" value="root"/>
        <property name="JDBC.Password" value="jiangwei"/>     
        <property name="Pool.MaximumActiveConnections" value="10" />
        <property name="Pool.MaximumIdleConnections" value="5" />
        <property name="Pool.MaximumCheckoutTime" value="120000" />
        <property name="Pool.TimeToWait" value="500" />
        <property name="Pool.PingQuery" value="select 1 from account" />
        <property name="Pool.PingEnabled" value="false" />
        <property name="Pool.PingConnectionsOlderThan" value="1" />
        <property name="Pool.PingConnectionsNotUsedFor" value="1" />
    </dataSource>
  </transactionManager>

  <!-- 配置SQL查询的配置文件的Account.xml -->
  <sqlMap resource="/Account.xml"/>

</sqlMapConfig>

 

对于上面的数据源配置的参数说明:

transactionManager节点定义了iBatis的事务管理器,提供三种方式,(1、JDBC,2、jta:分布式数据库,3、EXTERNAL:itbatis本身不做事务处理由外部进行处理);
dataSource节点:从属于transactionManager节点,用于设定ibatis运行期使用的DataSource属性;
type属性:type属性指定了dataSource的实现模式,共三种模式,(1、simple:ibatis提供的较小的连接池 2、dbcp:是apache实现的连接池 3、jndi:tomcate或weblogic提供的服务);
JDBC.Driver:JDBC驱动;
JDBC.ConnectionURL:数据库连接URL,如果用的是SQLServer JDBC Driver,需要在url后追加SelectMethod=Cursor以获得JDBC事务的多Statement支持;

JDBC.Username:数据库用户名;
JDBC.Password:数据库用户密码;
Pool.MaximumActiveConnections:数据库连接池可维持的最大容量;
Pool.MaximumIdleConnections:数据库连接池中允许的挂起(idle)连接数;
Pool.MaximumCheckoutTime数据库连接池中,连接被某个任务所允许占用的最大时间,如果超过这个时间限定,连接将被强制收回,(毫秒);
Pool.TimeToWait:当线程试图从连接池中获取连接时,连接池中无可用连接可供使用,此时线程将进入等待状态,直到池中出现空闲连接。此参数设定了线程所允许等待的最长时间,(毫秒);
Pool.PingQuery:数据库连接状态检测语句。某些数据库在某段时间持续处于空闲状态时会将其断开。而连接池管理器将通过此语句检测池中连接是否可用,
检测语句应该是一个最简化的无逻辑SQL。如“select 1 from user”,如果执行此语句成功,连接池管理器将认为此连接处于可用状态;
Pool.PingEnabled:是否允许检测连接状态;
Pool.PingConnectionsOlderThan:对持续连接时间超过设定值(毫秒)的连接进行检测;
Pool.PingConnectionsNotUsedFor:对空闲超过设定值(毫秒)的连接进行检测;

 

第三步实现源代码:

Account的实体类:

package com.ibatis.demo.domain;

public class Account {

  private int id;
  private String firstName;
  private String lastName;
  private String emailAddress;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public String getEmailAddress() {
    return emailAddress;
  }

  public void setEmailAddress(String emailAddress) {
    this.emailAddress = emailAddress;
  }

}

 

这个类没什么好说的了。

然后就是iBatis访问数据的类:

package com.ibatis.demo.data;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.ibatis.common.resources.Resources;
import com.ibatis.demo.domain.Account;

import java.io.Reader;
import java.io.IOException;
import java.util.List;
import java.sql.SQLException;

public class IbaitsData {

  private static SqlMapClient sqlMapper;

  static {
    try {
      //读取iBatis的配置文件:SqlMapConfig.xml
      Reader reader = Resources.getResourceAsReader("/SqlMapConfig.xml");
      sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);
      reader.close(); 
    } catch (IOException e) {
      throw new RuntimeException("Something bad happened while building the SqlMapClient instance." + e, e);
    }
  }

  //查询account表中的所有记录
  @SuppressWarnings("unchecked")
  public static List selectAllAccounts () throws SQLException {
    return sqlMapper.queryForList("selectAllAccounts");
  }

  //查询account表中_id为id的记录
  public static Account selectAccountById  (int id) throws SQLException {
    return (Account) sqlMapper.queryForObject("selectAccountById", id);
  }

  //插入一条记录
  public static void insertAccount (Account account) throws SQLException {
    sqlMapper.insert("insertAccount", account);
  }

  //更新一条记录
  public static void updateAccount (Account account) throws SQLException {
    sqlMapper.update("updateAccount", account);
  }

  //删除一条记录
  public static void deleteAccount (int id) throws SQLException {
    sqlMapper.delete("deleteAccount", id);
  }

}

 

这个类就是访问数据库的数据,可以查看一下sqlMapper的一些其他的方法的使用.

然后就是写一个ServletDemo来访问数据测试了:

package com.ibaits.demo.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ibatis.demo.data.IbaitsData;

public class ServletDemo extends HttpServlet{

private static final long serialVersionUID = -1461257848765985759L;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
try{
req.setAttribute("listAccout", IbaitsData.selectAllAccounts());
req.getRequestDispatcher("/index.jsp").forward(req, resp);
}catch(Exception e){
e.printStackTrace();
}
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
doGet(req,resp);
}

}

 

这里只测试了访问所有的记录,将访问的结果放到request域中,然后再index.jsp中使用jstl标签访问:

 <!-- c:forEach标签的使用:迭代 -->
     <c:forEach var="userBean" items="${listAccout}">
    用户id:<c:out value="${userBean.id}"></c:out>
    姓:<c:out value="${userBean.firstName}"></c:out>
    名:<c:out value="${userBean.lastName}"></c:out>
    邮箱地址:<c:out value="${userBean.emailAddress}"></c:out>
    <br><br>
     </c:forEach>

最后千万不要忘记导入相关的jar包:具体引用到的jar包可以查看上面的图片。

转载请注明:尼古拉斯.赵四 » iBatis开发的一个应用

喜欢 (4)or分享 (0)
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
(1)个小伙伴在吐槽
  1. W2Cwx3 http://www.FyLitCl7Pf7kjQdDUOLQOuaxTXbj5iNG.com
    JimmiXS2016-08-09 03:59 回复