iBatis 操作数据库,简单例子之一

时间:2022-12-09 16:15:19

数据库对应的sql语句:


 

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `t_user`
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `sex` int(1) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=latin1;

 

iBatis对应的数据库配置文件:


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" "http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
 <!-- setting out properties file -->
 <properties resource="hibernate.properties"/>

说明:这里可以引入外部的属性文件,如配置数据库的属性文件,都可以在这里包含,简化配置文件
 <!-- setting ibatis properties -->
 <settings
   cacheModelsEnabled="true"
   lazyLoadingEnabled="false"
   enhancementEnabled="true"
   maxSessions="64"
   maxTransactions="8"
   maxRequests="128"
   useStatementNamespaces="true"/>注:这里  强制,使用命名空间
 
 <transactionManager type="JDBC">
   <dataSource type="SIMPLE">
     <property name="JDBC.Driver" value="${hibernate.connection.driver_class}"/>
     <property name="JDBC.ConnectionURL" value="${hibernate.connection.url}"/>
     <property name="JDBC.Username" value="${hibernate.connection.username}"/>
     <property name="JDBC.Password" value="${hibernate.connection.password}"/>
     <property name="Pool.MaximumActiveConnections" value="15"/>
     <property name="Pool.MaximumIdleConnections" value="15"/>
     <property name="Pool.MaximumWait" value="1000"/>
   </dataSource>
 </transactionManager>
 <sqlMap resource="sql-iBatis.xml"/>

注意:这里是映射对应的sql语句的xml文件,下面给出配置
</sqlMapConfig>

 

 

sql语句对应的配置文件


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map-2.dtd">

<sqlMap namespace="bean.User">

注意:这里的命名空间,最好给出,保证全局的命名不重复。
 <typeAlias alias="user" type="bean.User"/>
 <cacheModel id="userCache" type="LRU">
  <flushInterval hours="24"/>
  <!-- <flushOnExecute statement="updateUser"/>   -->
  <property name="size" value="100"/>
 </cacheModel>

注:这里是缓冲设置。 


 <select id="getUser" parameterClass="user" resultClass="user" cacheModel="userCache">
  <![CDATA[
   select id,name,sex from t_user where name like #name#
  ]]>
 </select>
 <insert id="InsertUser" parameterClass="user">
  <![CDATA[
   insert into t_user(name, sex) values( #name#, #sex# )
  ]]>
 </insert>
 <update id="updateUser" parameterClass="user">
  <![CDATA[
   update t_user set name = #name#, sex = #sex# where id = #id#
  ]]>
 </update>
 <delete id="deleteUser" parameterClass="user">
  <![CDATA[
   delete from t_user where id = #id#
  ]]>
 </delete>

</sqlMap>

演示例子


package servlet;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import bean.User;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.engine.builder.xml.XmlSqlMapClientBuilder;

public class OperateIBatis extends HttpServlet {

 private Logger logger = Logger.getLogger(OperateOrder.class);
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  doPost(request, response);
 }

 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  response.setCharacterEncoding("UTF-8");
  request.setCharacterEncoding("UTF-8");
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter out = response.getWriter();
  
  XmlSqlMapClientBuilder xsmcb = new XmlSqlMapClientBuilder();
  try {
   Reader reader = Resources.getResourceAsReader("sql-map-config.xml");
   SqlMapClient smc = xsmcb.buildSqlMap(reader);
   smc.startTransaction();
   User user = new User();
   user.setName("zwc");
   user.setSex(1);
   smc.insert("bean.User.InsertUser", user);  因为上面强制,所以这里要给出全名,包括命名空间
   user = new User();
   user.setName("%zwc%");
   Iterator<User> i = (Iterator<User>) smc.queryForList("bean.User.getUser", user).iterator();
   while(i.hasNext()){
    user = i.next();
    out.println("<br>============================<br>");
    out.println(user.getName() + ":" + user.getSex());
   }
   smc.commitTransaction();
  } catch (Exception e) {
   logger.debug("读取IBatis配置文件失败",e);
  }
 }
}