ibatis的简单入门
2015-11-29 14:23
330 查看
ibatis也是一个ORM映射的框架,也是面向对象编程的一种框架。
下面是一个简单的类Account的CRUD的基本操作。
首先创建数据库的表
use test;
create table ACCOUNT(ACC_ID int (10) primary key,ACC_FIRST_NAME varchar(100),ACC_LAST_NAME varchar(100),ACC_EMAILADDRESS varchar(100));
实现java的代码:
实体类
package com.mydomain.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;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return firstName+" "+emailAddress;
}
}
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" commitRequired="false">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
<property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost:3306/test"/>
<property name="JDBC.Username" value="root"/>
<property name="JDBC.Password" value=""/>
</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/mydomain/data/Account.xml"/>
<!-- List more here...
<sqlMap resource="com/mydomain/data/Order.xml"/>
<sqlMap resource="com/mydomain/data/Documents.xml"/>
-->
</sqlMapConfig>
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">
<!-- Use type aliases to avoid typing the full classname every time. -->
<typeAlias alias="Account" type="com.mydomain.domain.Account"/>
<!-- 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="AccountResult" class="Account">
<result property="id" column="ACC_ID"/>
<result property="firstName" column="ACC_FIRST_NAME"/>
<result property="lastName" column="ACC_LAST_NAME"/>
<result property="emailAddress" column="ACC_EMAIL"/>
</resultMap>
<!-- Select with no parameters using the result map for Account class. -->
<select id="selectAllAccounts" resultMap="AccountResult">
select * from ACCOUNT
</select>
<insert id="addAccountBySequenceId" parameterClass="Account">
<selectKey resultClass="int" keyProperty="id">
select AccountPKSequence.nextVal from dual
</selectKey>
insert into ACCOUNT (
ACC_ID,
ACC_FIRST_NAME,
ACC_LAST_NAME,
ACC_EMAIL
)
values (
#id#, #firstName#, #lastName#, #emailAddress#
)
</insert>
<!-- A simpler select example without the result map. Note the
aliases to match the properties of the target result class. -->
<select id="selectAccountById" parameterClass="int" resultClass="Account">
select
ACC_ID as id,
ACC_FIRST_NAME as firstName,
ACC_LAST_NAME as lastName,
ACC_EMAIL as emailAddress
from ACCOUNT
where ACC_ID = #id#
</select>
<!-- Insert example, using the Account parameter class -->
<insert id="insertAccount" parameterClass="Account">
insert into ACCOUNT (
ACC_ID,
ACC_FIRST_NAME,
ACC_LAST_NAME,
ACC_EMAIL
values (
#id#, #firstName#, #lastName#, #emailAddress#
)
</insert>
<!-- Update example, using the Account parameter class -->
<update id="updateAccount" parameterClass="Account">
update ACCOUNT set
ACC_FIRST_NAME = #firstName#,
ACC_LAST_NAME = #lastName#,
ACC_EMAIL = #emailAddress#
where
ACC_ID = #id#
</update>
<!-- Delete example, using an integer as the parameter class -->
<delete id="deleteAccountById" parameterClass="int">
delete from ACCOUNT where ACC_ID = #id#
</delete>
</sqlMap>
DAO接口层
package com.mydomain.dao;
import java.sql.SQLException;
import java.util.List;
import com.mydomain.domain.Account;
public interface AccountDao {
public List<Account> selectAllAccounts() throws SQLException;
public Account selectAccountById(int id)throws SQLException;
public void insertAccount(Account account)throws SQLException;
public void addAccountBySequenceId(Account account)throws SQLException;
public void updateAccount(Account account)throws SQLException;
public void deleteAccount(int id)throws SQLException;
}
DAOImpl的实现层
package com.mydomain.dao.impl;
import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.List;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.mydomain.dao.AccountDao;
import com.mydomain.domain.Account;
public class AccountDaoImpl implements AccountDao{
/**
* 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/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 List<Account> selectAllAccounts () throws SQLException {
return sqlMapper.queryForList("selectAllAccounts");
}
public Account selectAccountById (int id) throws SQLException {
return (Account) sqlMapper.queryForObject("selectAccountById", id);
}
public void insertAccount (Account account) throws SQLException {
sqlMapper.insert("insertAccount", account);
}
public void updateAccount (Account account) throws SQLException {
sqlMapper.update("updateAccount", account);
}
public void deleteAccount (int id) throws SQLException {
sqlMapper.delete("deleteAccount", id);
}
public static void main(String[] args) throws SQLException{
AccountDao dao=new AccountDaoImpl();
List<Account> list=dao.selectAllAccounts();
for(Account account:list){
System.out.println(account);
}
}
public void addAccountBySequenceId(Account account) throws SQLException {
}
}
下面是一个简单的类Account的CRUD的基本操作。
首先创建数据库的表
use test;
create table ACCOUNT(ACC_ID int (10) primary key,ACC_FIRST_NAME varchar(100),ACC_LAST_NAME varchar(100),ACC_EMAILADDRESS varchar(100));
实现java的代码:
实体类
package com.mydomain.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;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return firstName+" "+emailAddress;
}
}
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" commitRequired="false">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
<property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost:3306/test"/>
<property name="JDBC.Username" value="root"/>
<property name="JDBC.Password" value=""/>
</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/mydomain/data/Account.xml"/>
<!-- List more here...
<sqlMap resource="com/mydomain/data/Order.xml"/>
<sqlMap resource="com/mydomain/data/Documents.xml"/>
-->
</sqlMapConfig>
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">
<!-- Use type aliases to avoid typing the full classname every time. -->
<typeAlias alias="Account" type="com.mydomain.domain.Account"/>
<!-- 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="AccountResult" class="Account">
<result property="id" column="ACC_ID"/>
<result property="firstName" column="ACC_FIRST_NAME"/>
<result property="lastName" column="ACC_LAST_NAME"/>
<result property="emailAddress" column="ACC_EMAIL"/>
</resultMap>
<!-- Select with no parameters using the result map for Account class. -->
<select id="selectAllAccounts" resultMap="AccountResult">
select * from ACCOUNT
</select>
<insert id="addAccountBySequenceId" parameterClass="Account">
<selectKey resultClass="int" keyProperty="id">
select AccountPKSequence.nextVal from dual
</selectKey>
insert into ACCOUNT (
ACC_ID,
ACC_FIRST_NAME,
ACC_LAST_NAME,
ACC_EMAIL
)
values (
#id#, #firstName#, #lastName#, #emailAddress#
)
</insert>
<!-- A simpler select example without the result map. Note the
aliases to match the properties of the target result class. -->
<select id="selectAccountById" parameterClass="int" resultClass="Account">
select
ACC_ID as id,
ACC_FIRST_NAME as firstName,
ACC_LAST_NAME as lastName,
ACC_EMAIL as emailAddress
from ACCOUNT
where ACC_ID = #id#
</select>
<!-- Insert example, using the Account parameter class -->
<insert id="insertAccount" parameterClass="Account">
insert into ACCOUNT (
ACC_ID,
ACC_FIRST_NAME,
ACC_LAST_NAME,
ACC_EMAIL
values (
#id#, #firstName#, #lastName#, #emailAddress#
)
</insert>
<!-- Update example, using the Account parameter class -->
<update id="updateAccount" parameterClass="Account">
update ACCOUNT set
ACC_FIRST_NAME = #firstName#,
ACC_LAST_NAME = #lastName#,
ACC_EMAIL = #emailAddress#
where
ACC_ID = #id#
</update>
<!-- Delete example, using an integer as the parameter class -->
<delete id="deleteAccountById" parameterClass="int">
delete from ACCOUNT where ACC_ID = #id#
</delete>
</sqlMap>
DAO接口层
package com.mydomain.dao;
import java.sql.SQLException;
import java.util.List;
import com.mydomain.domain.Account;
public interface AccountDao {
public List<Account> selectAllAccounts() throws SQLException;
public Account selectAccountById(int id)throws SQLException;
public void insertAccount(Account account)throws SQLException;
public void addAccountBySequenceId(Account account)throws SQLException;
public void updateAccount(Account account)throws SQLException;
public void deleteAccount(int id)throws SQLException;
}
DAOImpl的实现层
package com.mydomain.dao.impl;
import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.List;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.mydomain.dao.AccountDao;
import com.mydomain.domain.Account;
public class AccountDaoImpl implements AccountDao{
/**
* 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/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 List<Account> selectAllAccounts () throws SQLException {
return sqlMapper.queryForList("selectAllAccounts");
}
public Account selectAccountById (int id) throws SQLException {
return (Account) sqlMapper.queryForObject("selectAccountById", id);
}
public void insertAccount (Account account) throws SQLException {
sqlMapper.insert("insertAccount", account);
}
public void updateAccount (Account account) throws SQLException {
sqlMapper.update("updateAccount", account);
}
public void deleteAccount (int id) throws SQLException {
sqlMapper.delete("deleteAccount", id);
}
public static void main(String[] args) throws SQLException{
AccountDao dao=new AccountDaoImpl();
List<Account> list=dao.selectAllAccounts();
for(Account account:list){
System.out.println(account);
}
}
public void addAccountBySequenceId(Account account) throws SQLException {
}
}
相关文章推荐
- 2015年11月 广州深圳 MVP 线下活动
- Linux终端的总结和shell
- POJ1840 Eqr (哈希)
- Fragment生命周期方法的说明
- Ping使用
- framebuffer 子系统分析
- [Sort]堆排序
- 如何打开A20地址线的方法
- 微信多客服开发
- 将.mdf和_log.ldf的文件添加到Microsoft SQL Server的方法
- RISC 、 CISC 和 ARM处理器
- Webkit之平台相关层
- Webkit之UI层布局
- Javascript模板引擎:Hogan
- BestCoder Round #64 1001
- iOS UIKit:Auto Layout
- 内存工作原理
- 15、OSPF配置实验之LSA4、LSA5
- iOS开发——网络请求案例汇总(AFNetworking)
- LintCode-剑指Offer-(378)将二叉查找树转换成双链表