一个简单的 iBatis 实现——完整示例

表和数据:

CREATE TABLE weather (city            varchar(80),temp_lo         int,           -- low temperaturetemp_hi         int,           -- high temperatureprcp            real,          -- average temperaturedate            date
);insert into weather values ('Wuhan', 15, 30, 25.5, '2011-09-21');
insert into weather values ('Beijing', 10, 22, 15.3, '2011-09-22');
insert into weather values ('Shanghai', 17, 35, 28.6, '2011-09-22');
insert into weather values ('Guangzhou', 30, 36, 32.7, '2011-09-22');
insert into weather values ('Xiamen', 24, 32, 30.3, '2011-09-22');

文件目录及说明:


配置文件,WeatherRecord.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="WeatherRecord"><!-- Use type aliases to avoid typing the full classname every time. --><typeAlias alias="WeatherRecord" type="com.gq.ibatis.WeatherRecord"/><!-- Result maps describe the mapping between the columns returnedfrom a query, and the class properties.  A result map isn'tnecessary if the columns (or aliases) match to the properties exactly. --><resultMap id="WeatherResult" class="WeatherRecord"><result property="city" column="city"/><result property="lowTemperature" column="temp_lo"/><result property="highTemperature" column="temp_hi"/><result property="avgTemperature" column="prcp"/><result property="date" column="date"/></resultMap><!-- Select with no parameters using the result map for WeatherResult class. --><select id="selectAllWeatherRecords" resultMap="WeatherResult">select * from weather</select><!-- A simpler select example with the result map. Using the String parameter class --><select id="selectWeatherRecordByCity" parameterClass="String" resultMap="WeatherResult">select * from weather where city = #city#</select><!-- Insert example, using the WeatherResult parameter class --><insert id="insertWeatherRecord" parameterClass="WeatherRecord">insert into weather (city,temp_lo,temp_hi,prcp,date)values (#city#, #lowTemperature#, #highTemperature#, #avgTemperature#, #date#)</insert><!-- Update example, using the WeatherResult parameter class --><update id="updateWeatherRecord" parameterClass="WeatherRecord">update weather setcity = #city#,temp_lo = #lowTemperature#,temp_hi = #highTemperature#,prcp = #avgTemperature#,date = #date#wherecity = #city#</update><!-- Delete example, using an String as the parameter class --><delete id="deleteWeatherRecordByCity" parameterClass="String">delete from weather where city = #city#</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><!-- Configure a built-in transaction manager.  If you're using an app server, you probably want to use its transaction manager and a managed datasource --><transactionManager type="JDBC"><dataSource type="SIMPLE"><property name="JDBC.Driver" value="org.postgresql.Driver"/><property name="JDBC.ConnectionURL" value="jdbc:postgresql://localhost:5432/testdb"/><property name="JDBC.Username" value="postgres"/><property name="JDBC.Password" value="postgres"/></dataSource></transactionManager><!-- List the SQL Map XML files. They can be loaded from the classpath, as they are here (com.domain.data...) --><sqlMap resource="com/gq/ibatis/WeatherRecord.xml"/><!-- List more here...<sqlMap resource="com/mydomain/data/Order.xml"/><sqlMap resource="com/mydomain/data/Documents.xml"/>--></sqlMapConfig>
JavaBean 类 WeatherRecord.java

注意:数据库中的 date 为 date类型,则Java 中对应为 java.sql.Date !

不能改为 String 类型,会映射出错。

/**
*Create Date	:2011-9-22
*Create User	:GongQiang
*Modify Status	:
*File Location 	$Archive:Test-WebService/com.gq.ibatis/WeatherRecord.java$
*Last Modify	$Author:  $
*Modify Date	$Date: $
*Now Revision 	$Revision: $
*
*Copyright (c) 2004 Sino-Japanese Engineering Corp, Inc. All Rights Reserved.
*/package com.gq.ibatis;import java.sql.Date;public class WeatherRecord {private String city;private int lowTemperature;private int highTemperature;private float avgTemperature;private Date date;public String getCity() {return city;}public void setCity(String city) {this.city = city;}public int getLowTemperature() {return lowTemperature;}public void setLowTemperature(int lowTemperature) {this.lowTemperature = lowTemperature;}public int getHighTemperature() {return highTemperature;}public void setHighTemperature(int highTemperature) {this.highTemperature = highTemperature;}public float getAvgTemperature() {return avgTemperature;}public void setAvgTemperature(float avgTemperature) {this.avgTemperature = avgTemperature;}public Date getDate() {//DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//return dateFormat.format(date);return date;}public void setDate(Date date) {this.date = date;}}
操作类,SimpleExample.java

package com.gq.ibatis;import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.ibatis.common.resources.Resources;import java.io.Reader;
import java.io.IOException;
import java.util.List;
import java.sql.SQLException;/*** This is not a best practices class. It's just an example to give you an idea* of how iBATIS works. For a more complete example, see JPetStore 5.0 at* http://www.ibatis.com.*/
public class SimpleExample {/*** SqlMapClient instances are thread safe, so you only need one. In this* case, we'll use a static singleton. So sue me. ;-)*/private static SqlMapClient sqlMapper;/*** It's not a good idea to put code that can fail in a class initializer,* but for sake of argument, here's how you configure an SQL Map.*/static {try {Reader reader = Resources.getResourceAsReader("com/gq/ibatis/SqlMapConfig.xml");sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);reader.close();} catch (IOException e) {// Fail fast.throw new RuntimeException("Something bad happened while building the SqlMapClient instance."+ e, e);}}@SuppressWarnings("unchecked")/** It is safe cast, because list contain just WeatherRecord **/public static List<WeatherRecord> selectAllWeatherRecords() throws SQLException {return (List<WeatherRecord>) sqlMapper.queryForList("selectAllWeatherRecords");}public static WeatherRecord selectWeatherRecordByCity(String city)throws SQLException {return (WeatherRecord) sqlMapper.queryForObject("selectWeatherRecordByCity", city);}public static void insertWeatherRecord(WeatherRecord WeatherRecord)throws SQLException {sqlMapper.insert("insertWeatherRecord", WeatherRecord);}public static void updateWeatherRecord(WeatherRecord WeatherRecord)throws SQLException {sqlMapper.update("updateWeatherRecord", WeatherRecord);}public static void deleteWeatherRecordByCity(String city) throws SQLException {sqlMapper.delete("deleteWeatherRecordByCity", city);}}
测试类,TestIbatis.java 和输出的结果

/**
*Create Date	:2011-9-22
*Create User	:GongQiang
*Modify Status	:
*File Location 	$Archive:Test-WebService/com.gq.ibatis/TestIbatis.java$
*Last Modify	$Author:  $
*Modify Date	$Date: $
*Now Revision 	$Revision: $
*
*Copyright (c) 2004 Sino-Japanese Engineering Corp, Inc. All Rights Reserved.
*/package com.gq.ibatis;import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;public class TestIbatis {public static void main(String[] args) throws SQLException {testSelectAll();testSelectByCity();testInsert();System.out.println("---- After insert ----");testSelectAll();testUpdate();System.out.println("---- After update ----");testSelectAll();testDeleteByCity();System.out.println("---- After delete ----");testSelectAll();}/** 查询所有*/private static void testSelectAll() throws SQLException{List<WeatherRecord> weatherRecords = null;weatherRecords = SimpleExample.selectAllWeatherRecords();for( WeatherRecord wr : weatherRecords ){System.out.print( wr.getCity() + "\t" );System.out.print( wr.getLowTemperature() + "\t" );System.out.print( wr.getHighTemperature() + "\t" );System.out.print( wr.getAvgTemperature() + "\t" );System.out.println( wr.getDate() + "\t" );}}/** 根据城市名查询**/private static void testSelectByCity() throws SQLException{WeatherRecord wr = SimpleExample.selectWeatherRecordByCity("Beijing");System.out.println("Find record by city: "+ wr.getCity());System.out.print( wr.getCity() + "\t");System.out.print( wr.getLowTemperature() + "\t");System.out.print( wr.getHighTemperature() + "\t");System.out.print( wr.getAvgTemperature() + "\t");System.out.println( wr.getDate());}/** 插入操作**/private static void testInsert() throws SQLException{WeatherRecord wr = new WeatherRecord();wr.setCity( "Changchun" );wr.setLowTemperature( 5 );wr.setHighTemperature( 15 );wr.setAvgTemperature( 8.6f );wr.setDate( parseDate("2011-09-22") );SimpleExample.insertWeatherRecord(wr);}private static java.sql.Date parseDate( String dateStr ){DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");try {return new java.sql.Date(dateFormat.parse( dateStr ).getTime());} catch (ParseException e) {e.printStackTrace();}return null;}/** 更新操作**/private static void testUpdate() throws SQLException{WeatherRecord wr = new WeatherRecord();wr.setCity( "Changchun" );wr.setLowTemperature( 5 );wr.setHighTemperature( 15 );wr.setAvgTemperature( 8.6f );wr.setDate( parseDate("2012-01-01") );SimpleExample.updateWeatherRecord(wr);}private static void testDeleteByCity() throws SQLException{SimpleExample.deleteWeatherRecordByCity( "Changchun" );}}
运行结果:







本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/498089.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

测绘技术设计规定最新版_公示 | 29家单位申报甲级测绘资质审查意见

关于北京同创天成工程勘测有限公司等29家单位申报甲级测绘资质审查意见的公示  根据《中华人民共和国测绘法》和《测绘资质管理规定》《测绘资质分级标准》(国测管发〔2014〕31号)&#xff0c;我部对北京同创天成工程勘测有限公司、北京麦格天宝科技股份有限公司、中友四达(北…

智能驾驶时代已经到来

来源&#xff1a;中国科学报 概要&#xff1a;智能化、电动化、轻量化&#xff0c;无疑是被业界公认的汽车的三大发展方向。其中&#xff0c;汽车的智能化&#xff0c;或者说智能驾驶最为引人关注。 智能化、电动化、轻量化&#xff0c;无疑是被业界公认的汽车的三大发展方向。…

@requestparam @param @pathvariable @requestbody的区别

requestParam注解 用来获取前台传递过来的参数&#xff0c;例如获取以下链接的参数&#xff1a; http://api.nc.com/api/item/category/list?pid0 public String Demo1(RequestParam String pid){ System.out.println(“链接中请求参数的id&#xff1a;”pid); return null; }…

PostgreSQL 的一个简单连接和查询操作——示例

表和数据&#xff1a; CREATE TABLE weather (city varchar(80),temp_lo int, -- low temperaturetemp_hi int, -- high temperatureprcp real, -- average temperaturedate date );insert int…

8s nfs 挂载文件_Kubernetes集群使用网络存储NFS

NFS存储NFS即网络文件系统Network File System&#xff0c;它是一种分布式文件系统协议&#xff0c;最初是由Sun MicroSystems公司开发的类Unix操作系统之上的一款经典网络存储方案&#xff0c;其功能是在允许客户端主机可以像访问本地存储一样通过网络访问服务端文件。Kuberne…

2030全球新出行产业报告:2.2万亿美元蛋糕将这样分

来源:智东西 概要:汽车与出行产业面临的电动化、智能化、共享化以及轻量化变革,已经成了全球共识。

实现pv uv统计_聊聊前端监控(二)--行为监控的技术实现

上一篇梳理了前端监控的主要场景和类型&#xff0c;从本文开始&#xff0c;讨论下我知道的一些技术实现。前端黑科技层出不穷&#xff0c;个人眼界有限&#xff0c;尽量把了解到的实现方式都罗列出来&#xff0c;希望对大家有些启发&#xff0c;同时也欢迎流言讨论。限于篇幅&a…

Science:揭示人类大脑进化机制

来源&#xff1a;细胞 概要&#xff1a;人类与其它灵长类动物的最大区别在于我们大脑的不同&#xff0c;这也是我们作为人类最特殊的标志之一。 人类与其它灵长类动物的最大区别在于我们大脑的不同&#xff0c;这也是我们作为人类最特殊的标志之一。 然而&#xff0c;人类与灵长…

单元格格式_单元格格式的用法你知道吗~~

想了解excel吗&#xff1f;&#xff1f;&#xff1f; 想从小白变大神吗&#xff1f;&#xff1f;&#xff1f; 快来look look excel单元格格式的用处吧&#xff01;&#xff01;&#xff01;先来了解一下单元格格式的…

人工智能名人堂第54期 | 深度学习鼻祖:Geoffrey Hinton

来源&#xff1a;德先生 概要&#xff1a;近日&#xff0c;他因提出capsule 概念&#xff0c;推翻反向传播再次引发广泛关注与热议。 Geoffrey Hinton&#xff0c;被称为“神经网络之父”、“深度学习鼻祖”&#xff0c;他曾获得爱丁堡大学人工智能的博士学位&#xff0c;并且为…

eureka和zookeeper的区别

首先我们先说下&#xff1a; RDBMS>&#xff08;MySql,Oracle,SqlServer等关系型数据库&#xff09;遵循的原则是&#xff1a;ACID原则&#xff08;A&#xff1a;原子性。C&#xff1a;一致性。I&#xff1a;独立性。D&#xff1a;持久性。&#xff09;。 NoSql> &#…

struts2 防止重复提交 与 进入等待画面

演示重复提交的错误&#xff1a; 相关文件&#xff1a; struts.xml <?xml version"1.0" encoding"UTF-8"?> <!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN""http://struts.apache…

征服围棋之后 谷歌DeepMind宣布利用AI对抗乳腺癌

来源&#xff1a;全球人工智能 概要&#xff1a;在征服围棋世界之后&#xff0c;DeepMind公司将许多机器学习资源用于提升医疗水平&#xff0c;今天&#xff0c;DeepMind宣布利用人工智能对抗乳腺癌。 在征服围棋世界之后&#xff0c;DeepMind公司将许多机器学习资源用于提升医…

rabbitmq详细入门文档+springboot结合使用

在介绍RabbitMQ之前&#xff0c;我们先来看下面一个电商项目的场景&#xff1a; 商品的原始数据保存在数据库中&#xff0c;增删改查都在数据库中完成。 搜索服务数据来源是索引库&#xff08;Elasticsearch&#xff09;&#xff0c;如果数据库商品发生变化&#xff0c;索引库…

Cognizant:走向2028年将诞生的21个新工作

来源&#xff1a;亿欧 概要&#xff1a;未来十多年&#xff0c;伴随着AI等新技术的发展&#xff0c;部分工作岗位可能消失&#xff0c;但也可能创造出很多新的工作机会。 未来十多年&#xff0c;伴随着AI等新技术的发展&#xff0c;部分工作岗位可能消失&#xff0c;但也可能创…

delphi excel取批注所在的行列_excel技巧教程丨34个常用Excel小技巧,助你玩转职场!...

技巧1&#xff1a;单元格内强制换行在单元格中某个字符后按alt回车键&#xff0c;即可强制把光标换到下一行中。技巧2&#xff1a;锁定标题行选取第2行&#xff0c;视图 - 冻结窗格 - 冻结首行(或选取第2行 - 冻结窗格)冻结后再向下翻看时标题行始终显示在最上面。技巧3&#x…

Spring Security用户认证和权限控制(默认实现)

1 背景 实际应用系统中&#xff0c;为了安全起见&#xff0c;一般都必备用户认证&#xff08;登录&#xff09;和权限控制的功能&#xff0c;以识别用户是否合法&#xff0c;以及根据权限来控制用户是否能够执行某项操作。 Spring Security是一个安全相关的框架&#xff0c;能…

2017年数据可视化的七大趋势!

来源&#xff1a; 全球人工智能 概要&#xff1a;随着科技的不断进步与新设备的不断涌现&#xff0c;数据可视化领域目前正处在飞速地发展之中。 随着科技的不断进步与新设备的不断涌现&#xff0c;数据可视化领域目前正处在飞速地发展之中。ProPublica的调查记者兼开发者Lena…

struts2中用interceptor实现权限控制

在jsp servlet中我们通常使用Servlet Filter控制用户是否登入&#xff0c; 是否有权限转到某个页面。在struts2中我们应该会想到他的拦截器(Interceptor)&#xff0c; Interceptor在struts2中起着非常重要的作用。很多struts2中的功能都是使用Interceptor实现的。 需求&#xf…

CGAL的三维点集

CGAL提供了几种处理点集的算法&#xff0c;从形状检测到通过标准点集处理工具进行的表面重建。 虽然这些算法不强制使用特定的数据结构&#xff0c;但该软件包提供了一个3D点集结构&#xff0c;使用户更容易处理附加属性&#xff0c;如法向量、颜色、标签&#xff0c;并在其上调…