ibatis学习总结

ibatis数据库配置文件

PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"

"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

数据库与model映射配置文件

PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"

"http://ibatis.apache.org/dtd/sql-map-2.dtd">

insert into ACCOUNT (

ACC_ID,

ACC_FIRST_NAME,

ACC_LAST_NAME,

ACC_EMAIL

values (

#id#, #firstName#, #lastName#, #emailAddress#

)

update ACCOUNT set

ACC_FIRST_NAME = #firstName#,

ACC_LAST_NAME = #lastName#,

ACC_EMAIL = #emailAddress#

where

ACC_ID = #id#

delete from ACCOUNT where ACC_ID = #id#

Model对象

package com.mydomain.domain;

public class Account {

private int id;

private String firstName;

private String lastName;

private String emailAddress;

/*Model层,主要进行数据訪问部分*/

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;

}

}

DAO数据訪问对象

package com.mydomain.data;

import com.ibatis.sqlmap.client.SqlMapClient;

import com.ibatis.sqlmap.client.SqlMapClientBuilder;

import com.ibatis.common.resources.Resources;

import com.mydomain.domain.Account;

import java.io.Reader;

import java.io.IOException;

import java.util.List;

import java.sql.SQLException;

public class SimpleExample {

/**

* SqlMapClient instances are thread safe, so you only need one.In this case, we'll use a static singleton.

*/

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/mydomain/data/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);

}

}

public static List selectAllAccounts () throws SQLException {

return sqlMapper.queryForList("selectAllAccounts");

}

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);

}

}

结论:

1、通过数据库和Model对象映射配置文件,将数据库中表与java对象进行关联;

2、通过数据库配置文件。里面包括数据库与model对象映射配置文件。保证数据库连接。

3、通过DAO进行数据库的增删改查操作。

查看原文