表和数据:
CREATE TABLE weather (
city varchar(80),
temp_lo int, -- low temperature
temp_hi int, -- high temperature
prcp real, -- average temperature
date 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 returned
from a query, and the class properties. A result map isn't
necessary 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 set
city = #city#,
temp_lo = #lowTemperature#,
temp_hi = #highTemperature#,
prcp = #avgTemperature#,
date = #date#
where
city = #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" );
}
}
运行结果: