由于之前写的文章在提交的时候出错,导致没保存上
。重新打起精神,继续这篇Ibatis的基础介绍。
1、Ibatis功能简介
Ibatis用于完成OR的映射,但又没有Hibernate那么复杂,它只是减少了sql在java代码中的出现,sql语句都在xml配置文件中去完成。需要引入mysql的驱动包和Ibatis的包即可,本次使用的是mysql5.1、Ibatis2.3.4版本。文章下面有附件,包含了本次的代码、驱动和ibatis的jar包。
2、具体步骤如下:
1)在Mysql中创建表
create
table t_user(id
int,
name
varchar(10), sex
int);
2)创建POJO类:
User.java
package com.ctgusec.zhupan.model;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private Integer sex;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private Integer sex;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
3)创建User类的对应Ibatis配置文件:User.xml, 在包com.ctgusec.zhupan.maps下面
<?
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 ="User" >
< typeAlias alias ="user" type ="com.ctgusec.zhupan.model.User" />
< select id ="getUser" parameterClass ="java.lang.String"
resultClass ="user" >
select name,sex from t_user
where name = #name#
</ select >
< select id ="getAllUser" resultClass ="user" >
select
name,
sex
from t_user
</ select >
< update id ="updateUser" parameterClass ="user" >
UPDATE t_user
SET
name=#name#,
sex=#sex#
WHERE id = #id#
</ update >
< insert id ="insertUser" parameterClass ="user" >
INSERT INTO t_user (name,
sex) VALUES ( #name#, #sex# )
</ insert >
< delete id ="deleteUser" parameterClass ="java.lang.String" >
delete from t_user
where
id=#value#
</ delete >
</ sqlMap >
<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">
< sqlMap namespace ="User" >
< typeAlias alias ="user" type ="com.ctgusec.zhupan.model.User" />
< select id ="getUser" parameterClass ="java.lang.String"
resultClass ="user" >
select name,sex from t_user
where name = #name#
</ select >
< select id ="getAllUser" resultClass ="user" >
select
name,
sex
from t_user
</ select >
< update id ="updateUser" parameterClass ="user" >
UPDATE t_user
SET
name=#name#,
sex=#sex#
WHERE id = #id#
</ update >
< insert id ="insertUser" parameterClass ="user" >
INSERT INTO t_user (name,
sex) VALUES ( #name#, #sex# )
</ insert >
< delete id ="deleteUser" parameterClass ="java.lang.String" >
delete from t_user
where
id=#value#
</ delete >
</ sqlMap >
4)配置Ibatis的总控文件:SqlMapConfig.xml,在包com.ctgusec.zhupan.maps下面
<?
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 >
< settings cacheModelsEnabled ="true" enhancementEnabled ="true"
lazyLoadingEnabled ="true" errorTracingEnabled ="true" maxRequests ="32"
maxSessions ="10" maxTransactions ="5" useStatementNamespaces ="false" />
< transactionManager type ="JDBC" >
< dataSource type ="SIMPLE" >
< property name ="JDBC.Driver" value ="com.mysql.jdbc.Driver" />
< property name ="JDBC.ConnectionURL" value ="jdbc:mysql://localhost:3306/ibatis" />
< property name ="JDBC.Username" value ="root" />
< property name ="JDBC.Password" value ="123" /> <!--com测试admin-->
< property name ="Pool.MaximumActiveConnections" value ="10" />
< property name ="Pool.MaximumIdleConnections" value ="5" />
< property name ="Pool.MaximumCheckoutTime" value ="120000" />
< property name ="Pool.TimeToWait" value ="500" />
< property name ="Pool.PingQuery" value ="select 1 from sample" />
< property name ="Pool.PingEnabled" value ="false" />
< property name ="Pool.PingConnectionsOlderThan" value ="1" />
< property name ="Pool.PingConnectionsNotUsedFor" value ="1" />
</ dataSource >
</ transactionManager >
< sqlMap resource ="com/ctgusec/zhupan/maps/User.xml" />
</ sqlMapConfig >
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
< sqlMapConfig >
< settings cacheModelsEnabled ="true" enhancementEnabled ="true"
lazyLoadingEnabled ="true" errorTracingEnabled ="true" maxRequests ="32"
maxSessions ="10" maxTransactions ="5" useStatementNamespaces ="false" />
< transactionManager type ="JDBC" >
< dataSource type ="SIMPLE" >
< property name ="JDBC.Driver" value ="com.mysql.jdbc.Driver" />
< property name ="JDBC.ConnectionURL" value ="jdbc:mysql://localhost:3306/ibatis" />
< property name ="JDBC.Username" value ="root" />
< property name ="JDBC.Password" value ="123" /> <!--com测试admin-->
< property name ="Pool.MaximumActiveConnections" value ="10" />
< property name ="Pool.MaximumIdleConnections" value ="5" />
< property name ="Pool.MaximumCheckoutTime" value ="120000" />
< property name ="Pool.TimeToWait" value ="500" />
< property name ="Pool.PingQuery" value ="select 1 from sample" />
< property name ="Pool.PingEnabled" value ="false" />
< property name ="Pool.PingConnectionsOlderThan" value ="1" />
< property name ="Pool.PingConnectionsNotUsedFor" value ="1" />
</ dataSource >
</ transactionManager >
< sqlMap resource ="com/ctgusec/zhupan/maps/User.xml" />
</ sqlMapConfig >
5)对Ibatis的调用,只需要调用Ibatis的POJO对应的配置文件中的id即可
package com.ctgusec.zhupan;
import java.sql.SQLException;
import java.util.List;
import com.ctgusec.zhupan.model.User;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
public class ExampleMain {
public static void update() {
// 首先初始化iBatis获得一个SqlMapClient对象
String resource = "com/ctgusec/zhupan/maps/SqlMapConfig.xml";
com.ibatis.sqlmap.client.SqlMapClient sqlMap = null;
try {
java.io.Reader reader = com.ibatis.common.resources.Resources
.getResourceAsReader(resource);
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
} catch (Exception e) {
e.printStackTrace();
}
// sqlMap系统初始化完毕,开始执行update操作
try {
sqlMap.startTransaction();
User user = new User();
user.setId( new Integer(1));
user.setName( "zhupan");
user.setSex( new Integer(1));
sqlMap.update( "updateUser", user);
sqlMap.commitTransaction();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
try {
sqlMap.endTransaction();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static List getUser() {
// 首先初始化iBatis获得一个SqlMapClient对象
String resource = "com/ctgusec/zhupan/maps/SqlMapConfig.xml";
com.ibatis.sqlmap.client.SqlMapClient sqlMap = null;
List user = null;
try {
java.io.Reader reader = com.ibatis.common.resources.Resources
.getResourceAsReader(resource);
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
} catch (Exception e) {
e.printStackTrace();
}
// sqlMap系统初始化完毕,开始执行getAllUser操作
try {
sqlMap.startTransaction();
user = sqlMap.queryForList( "getAllUser", null);
sqlMap.commitTransaction();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
try {
sqlMap.endTransaction();
} catch (SQLException e) {
e.printStackTrace();
}
}
return user;
}
public static void main(String[] args) {
// update();
List user = getUser();
//System.out.println(user.size());
for ( int i = 0; i < user.size(); i++) {
System.out.println(((User) user.get(i)).getName());
}
}
}
import java.sql.SQLException;
import java.util.List;
import com.ctgusec.zhupan.model.User;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
public class ExampleMain {
public static void update() {
// 首先初始化iBatis获得一个SqlMapClient对象
String resource = "com/ctgusec/zhupan/maps/SqlMapConfig.xml";
com.ibatis.sqlmap.client.SqlMapClient sqlMap = null;
try {
java.io.Reader reader = com.ibatis.common.resources.Resources
.getResourceAsReader(resource);
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
} catch (Exception e) {
e.printStackTrace();
}
// sqlMap系统初始化完毕,开始执行update操作
try {
sqlMap.startTransaction();
User user = new User();
user.setId( new Integer(1));
user.setName( "zhupan");
user.setSex( new Integer(1));
sqlMap.update( "updateUser", user);
sqlMap.commitTransaction();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
try {
sqlMap.endTransaction();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static List getUser() {
// 首先初始化iBatis获得一个SqlMapClient对象
String resource = "com/ctgusec/zhupan/maps/SqlMapConfig.xml";
com.ibatis.sqlmap.client.SqlMapClient sqlMap = null;
List user = null;
try {
java.io.Reader reader = com.ibatis.common.resources.Resources
.getResourceAsReader(resource);
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
} catch (Exception e) {
e.printStackTrace();
}
// sqlMap系统初始化完毕,开始执行getAllUser操作
try {
sqlMap.startTransaction();
user = sqlMap.queryForList( "getAllUser", null);
sqlMap.commitTransaction();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
try {
sqlMap.endTransaction();
} catch (SQLException e) {
e.printStackTrace();
}
}
return user;
}
public static void main(String[] args) {
// update();
List user = getUser();
//System.out.println(user.size());
for ( int i = 0; i < user.size(); i++) {
System.out.println(((User) user.get(i)).getName());
}
}
}
6) 测试,运行结果如下
zhangsan
lisi
wangwu
lisi
wangwu
3、总结
Ibatis减少了sql语句在java代码中的出现,java编程只需要操作对象就可以了,是面向对象的编程更加的纯洁。
【注意】
1、dbcp直连mysql数据库
- Properties pros = new Properties();
- pros.put("driverClassName", "com.mysql.jdbc.Driver");
- pros.put("url", "jdbc:mysql://10.20.144.27:3306/druid");
- pros.put("username", "druid");
- pros.put("password", "druid123");
- DataSource dataSource = BasicDataSourceFactory.createDataSource(pros);
Connection conn = dataSource.getConnection();
本文转自 tianya23 51CTO博客,原文链接:http://blog.51cto.com/tianya23/275606,如需转载请自行联系原作者