如何编写Java的MyBatis框架中SQL语句java 数据库映射框架部分

Java的MyBatis框架中对数据库进行动态SQL查询的教程
作者:红烧狮子头
字体:[ ] 类型:转载 时间:
这篇文章主要介绍了Java的MyBatis框架中对数据库进行动态SQL查询的教程,讲解了MyBatis中一些控制查询流程的常用语句,需要的朋友可以参考下
其实MyBatis具有的一个强大的特性之一通常是它的动态 SQL 能力。 如果你有使用 JDBC 或其他 相似框架的经验,你就明白要动态的串联 SQL 字符串在一起是十分纠结的,确保不能忘了空格或在列表的最后省略逗号。Mybatis中的动态 SQL 可以彻底处理这种痛苦。对于动态SQL,最通俗简单的方法就是我们自己在硬编码的时候赋予各种动态行为的判断,而在Mybatis中,用一种强大的动态 SQL 语 言来改进这种情形,这种语言可以被用在任意映射的 SQL 语句中。动态 SQL 元素和使用 JSTL 或其他相似的基于 XML 的文本处理器相似。MyBatis 采用功能强大的基于 OGNL 的表达式来消除其他元素。
我们常用的几个节点元素有if,choose(when, otherwise),trim(where, if),foreach。真正使用下来我感觉有点像XSLT(文章后面会顺带提一下~)的用法。
(1)if 的用法
在ViisitMapper的分页配置中,如果pageIndex&-1 and pageSize&-1的时候就加入相应的分页SQL,否则就不添加(默认取全部),如下:
&select id="getListByPagenate" parameterType="PagenateArgs"
resultType="Visitor"&
select * from (
&include refid="getListSql" /& &include refid="orderBySql"/&
) t &!-- #{}表示参数化输出,${}表示直接输出不进行任何转义操作,自己进行转移 --&
&if test="pageStart&-1 and pageSize&-1"&
limit #{pageStart}, #{pageSize}
&sql id="getListSql"&
select * from Visitor where
&sql id="orderBySql"&
order by ${orderFieldStr} ${orderDirectionStr}
  因为我们的参数pageIndex与pageSize都是int值所以可以这样直接判断,如果是对象实例我们可以利用null判断来进行一些动态逻辑的控制,具体实际开发中就要看业务需求了。这里我认为要注意的是别十分顺手的吧and写成&&,这个在配置中不会被识别~。
(2)choose (when, otherwise)的用法
  choose when 主要在多个条件的情况下只满足其中一个条件的应用场景中使用,例如这里就构建一个query条件,分别传递id,name与createTime。假设我们查询Visitor表时,如果VisitorId有值则,使用Id查询,如果VisitorName有值则采用VisitName查询,如下,还是在david.mybatis.demo.IVisitorOperation接口类中添加List&Visitor& getListChooseWhenDemo(BasicQueryArgs args)方法。在VisitorMapper中添加相应的的select节点配置:
package david.mybatis.
import java.util.L
import david.mybatis.model.BasicQueryA
import david.mybatis.model.PagenateA
import david.mybatis.model.V
import david.mybatis.model.VisitorWithRn;
public interface IVisitorOperation {
* 添加访问者
public int add(Visitor visitor);
* 删除访问者
public int delete(int id);
* 更新访问者
public int update(Visitor visitor);
* 查询访问者
public Visitor query(int id);
* 查询List
public List&Visitor& getList();
* 分页查询List
public List&Visitor& getListByPagenate(PagenateArgs args);
* 分页查询List(包含Rownum)
public List&VisitorWithRn& getListByPagenateWithRn(PagenateArgs args);
* 基础查询
public Visitor basicQuery(int id);
* 动态条件查询(choose,when)实例
public List&Visitor& getListChooseWhenDemo(BasicQueryArgs args);
* 动态条件查询(where,if)实例
public List&Visitor& getListWhereDemo(BasicQueryArgs args);
* 动态查询(foreach)实例
public List&Visitor& getListForeachDemo(List&Integer& ids);
&?xml version="1.0" encoding="UTF-8"?&
&!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"&
&mapper namespace="david.mybatis.demo.IVisitorOperation"&
&resultMap type="Visitor" id="visitorRs"&
&id column="Id" property="id" /&
&result column="Name" property="name" /&
&result column="Email" property="email" /&
&result column="Status" property="status" /&
&result column="CreateTime" property="createTime" /&
&/resultMap&
&sql id="getListSqlConditions"&
select * from Visitor
&!-- 满足其中一个条件时候用choose when操作 --&
&select id="getListChooseWhenDemo" resultMap="visitorRs"
parameterType="BasicQueryArgs"&
&include refid="getListSqlConditions" /&
&if test="queryStatus&0"&
status=#{queryStatus}
&when test="queryId!=0"&
and id=#{queryId}
&when test="queryName!=null"&
and name like #{queryName}
&otherwise&
and createTime&= #{queryTime}
&/otherwise&
(3)where if (trim)的用法
where关键词的好处是在于,如果有相应的过滤条件的话,它知道在适当的时候插入where关键词。而且它也知道在何时该去掉相应的AND与OR的连接符,主要应对如下情景
&select id="findActiveBlogLike"
resultType="Blog"&
SELECT * FROM BLOG
&if test="state != null"&
state = #{state}
&if test="title != null"&
AND title like #{title}
&if test="author != null and author.name != null"&
AND author_name like #{author.name}
不会因为所有条件不满足变为
&select id="findActiveBlogLike"
resultType="Blog"&
SELECT * FROM BLOG
或者因为没有满足第一个条件,单单满足后面的条件变成
&select id="findActiveBlogLike"
resultType="Blog"&
SELECT * FROM BLOG
AND title like ‘someTitle'
所以针对这种我们可以在建立choose when条件示例,同样在IVisitorOperation接口类中加入相应的方法public List&Visitor& getListWhereDemo(BasicQueryArgs args),把VisitorMapper配置文件中的相对应配置加上去如下:
&?xml version="1.0" encoding="UTF-8"?&
&!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"&
&mapper namespace="david.mybatis.demo.IVisitorOperation"&
&sql id="getListSqlConditions"&
select * from Visitor
&!-- 满足条件的都加上去操作 --&
&select id="getListWhereDemo" resultMap="visitorRs"
parameterType="BasicQueryArgs"&
&include refid="getListSqlConditions" /&
&if test="queryStatus&0"&
&if test="queryId&0"&
and id=#{queryId}
&if test="queryName!=null"&
and name like=#{queryName}
&if test="queryTime!=null"&
and createTime&=#{queryTime}
&trim prefix="WHERE" prefixOverrides="AND |OR "&
&if test="queryStatus&0"&
&if test="queryId&0"&
and id=#{queryId}
&if test="queryName!=null"&
and name like=#{queryName}
&if test="queryTime!=null"&
and createTime&=#{queryTime}
(4)foreach的用法
在常用的动态SQL中我们有个业务场景是要where id in 一大串的ID,像这种情况我们就可以用到foreach啦,不必自己辛辛苦苦去拼接Id字符串啦。同样的步骤还是在IVisitorOperation接口类中加入相应的方法public List&Visitor& getListForeachDemo(List&Integer& ids),然后再对应的Mapper文件中配置上相应的节点元素信息,如下:
&?xml version="1.0" encoding="UTF-8"?&
&!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"&
&mapper namespace="david.mybatis.demo.IVisitorOperation"&
&sql id="getListSqlConditions"&
select * from Visitor
&!-- Foreach循环条件 --&
&select id="getListForeachDemo" resultMap="visitorRs"&
&include refid="getListSqlConditions"/&
where status&0 and id in
&foreach collection="list" item="item" index="index" open="(" separator="," close=")"&
&/foreach&
最后你只需要在DemoRun中建立相应的测试方法,Mybatis里面的动态SQL也就完成啦,下面测试用的DemoRun方法
* 动态查询foreach实例
public static void getListForeachDemo(List&Integer& ids) {
SqlSession session = MybatisUtils.getSqlSession();
IVisitorOperation vOperation = session.getMapper(IVisitorOperation.class);
List&Visitor& ls = vOperation.getListForeachDemo(ids);
for (Visitor visitor : ls) {
System.out.println(visitor);
* 动态查询where if实例
public static void getListWhereCondition(int id, String name, Date createTime) {
name = name == "" ? null :
SqlSession session = MybatisUtils.getSqlSession();
BasicQueryArgs args = new BasicQueryArgs(id, name, createTime);
IVisitorOperation vOperation = session.getMapper(IVisitorOperation.class);
List&Visitor& ls = vOperation.getListWhereDemo(args);
if (ls.size() == 0)
System.out.println("查无匹配!");
for (Visitor visitor : ls) {
System.out.println(visitor);
* 动态查询choose when实例
public static void getListChooseWhenDemo(int id, String name, Date createTime) {
name = name == "" ? null :
SqlSession session = MybatisUtils.getSqlSession();
BasicQueryArgs args = new BasicQueryArgs(id, name, createTime);
IVisitorOperation vOperation = session.getMapper(IVisitorOperation.class);
List&Visitor& ls = vOperation.getListChooseWhenDemo(args);
if (ls.size() == 0)
System.out.println("查无匹配!");
for (Visitor visitor : ls) {
System.out.println(visitor);
PS:关于OGNL
OGNL 是 Object-Graph Navigation Language 的缩写,从语言角度来说:它是一个功能强大的表达式语言,用来获取和设置 java 对象的属性 , 它旨在提供一个更高抽象度语法来对 java 对象图进行导航,OGNL 在许多的地方都有应用,例如:
作为 GUI 元素(textfield,combobox, 等)到模型对象的绑定语言。
数据库表到 Swing 的 TableModel 的数据源语言。
web 组件和后台 Model 对象的绑定语言 (WebOGNL,Tapestry,WebWork,WebObjects) 。
作为 Jakarata Commons BeanUtils 或者 JSTL 的表达式语言的一个更具表达力的替代语言。
另外,java 中很多可以做的事情,也可以使用 OGNL 来完成,例如:列表映射和选择。 对于开发者来说,使用 OGNL,可以用简洁的语法来完成对 java 对象的导航。通常来说: 通过一个“路径”来完成对象信息的导航,这个“路径”可以是到 java bean 的某个属性,或者集合中的某个索引的对象,等等,而不是直接使用 get 或者 set 方法来完成。
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具如何在mybatis中调试查看生成的sql语句? - 知乎22被浏览18266分享邀请回答typeAliasRegistry.registerAlias("STDOUT_LOGGING", StdOutImpl.class);
public void error(String s) {
System.err.println(s);
public void debug(String s) {
System.out.println(s);
public void trace(String s) {
System.out.println(s);
显而易见,STDOUT_LOGGING 这种方式就是输出在了控制台上。在 IDE 中是控制台,在服务器上就是 web 服务器的输出日志中了。92 条评论分享收藏感谢收起42 条评论分享收藏感谢收起查看更多回答1 个回答被折叠()java持久层框架mybatis如何防止sql注入《声明为转载》
sql注入大家都不陌生,是一种常见的攻击方式,攻击者在界面的表单信息或url上输入一些奇怪的sql片段,例如“or&‘1’=’1’”这样的语句,有可能入侵参数校验不足的应用程序。所以在我们的应用中需要做一些工作,来防备这样的攻击方式。在一些安全性很高的应用中,比如银行软件,经常使用将sql语句全部替换为存储过程这样的方式,来防止sql注入,这当然是一种很安全的方式,但我们平时开发中,可能不需要这种死板的方式。
mybatis框架作为一款半自动化的持久层框架,其sql语句都要我们自己来手动编写,这个时候当然需要防止sql注入。其实Mybatis的sql是一个具有“输入+输出”功能,类似于函数的结构,如下:
&&/span&select&id=“getBlogById“&resultType=“Blog“
parameterType=”int”&
&&&&&&&select
id,title,author,content
from blog where id=#{id}
&&&&&/&/span&select&
这里,parameterType标示了输入的参数类型,resultType标示了输出的参数类型。回应上文,如果我们想防止sql注入,理所当然地要在输入参数上下功夫。上面代码中高亮部分即输入参数在sql中拼接的部分,传入参数后,打印出执行的sql语句,会看到sql是这样的:
id,title,author,content from blog where id = ?
不管输入什么参数,打印出的sql都是这样的。这是因为mybatis启用了预编译功能,在sql执行前,会先将上面的sql发送给数据库进行编译,执行时,直接使用编译好的sql,替换占位符“?”就可以了。因为sql注入只能对编译过程起作用,所以这样的方式就很好地避免了sql注入的问题。
mybatis是如何做到sql预编译的呢?其实在框架底层,是jdbc中的PreparedStatement类在起作用,PreparedStatement是我们很熟悉的Statement的子类,它的对象包含了编译好的sql语句。这种“准备好”的方式不仅能提高安全性,而且在多次执行一个sql时,能够提高效率,原因是sql已编译好,再次执行时无需再编译。
话说回来,是否我们使用mybatis就一定可以防止sql注入呢?当然不是,请看下面的代码:
&&/span&select&id=“orderBlog“&resultType=“Blog“
parameterType=”map”&
&&&&&&&select
id,title,author,content
from blog order by ${orderParam}
&&&&&/&/span&select&
仔细观察,内联参数的格式由“#{xxx}”变为了${xxx}。如果我们给参数“orderParam”赋值为”id”,将sql打印出来,是这样的:
id,title,author,content from
blog order by id
&&&&&显然,这样是无法阻止sql注入的。在mybatis中,”${xxx}”这样格式的参数会直接参与sql编译,从而不能避免注入攻击。但涉及到动态表名和列名时,只能使用“${xxx}”这样的参数格式,所以,这样的参数需要我们在代码中手工进行处理来防止注入。
&&&&结论:在编写mybatis的映射语句时,尽量采用“#{xxx}”这样的格式。若不得不使用“${xxx}”这样的参数,要手工地做好过滤工作,来防止sql注入攻击。
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。mybatis怎么配置log4j打印出sql语句 - ITeye问答
我的项目是struts2+mybatis-3.0.4,可是怎么配置log4j的配置文件也出不来后台的sql语句。
有些人说项目中slf4j的jar包的话,怎么配置也出不来的,但是我的项目这个jar包是必须的呀。
#需要slf4j-api-1.6.1.jar slf4j-log4j12.-1.6.1.jar
然后针对你自己的项目把日志输入
.你自己.的包.=DEBUG,CONSOLE
我是这么配置的
log4j.rootLogger=DEBUG, stdout
log4j.logger.org.mybatis=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n
在log4j.properties中配置如下信息
log4j.appender.PRODUCT=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.PRODUCT=org.apache.log4j.RollingFileAppender
log4j.appender.PRODUCT.Append=true
log4j.appender.PRODUCT.DatePattern='.'yyyy-MM-dd
log4j.appender.PRODUCT.File=D:/logs/AMS.log#为日志输出文件位置
log4j.appender.PRODUCT.Threshold=DEBUG
#log4j.appender.PRODUCT.Threshold=INFO
#log4j.appender.PRODUCT.MaxFileSize=20MB
log4j.appender.PRODUCT.layout=org.apache.log4j.PatternLayout
log4j.appender.PRODUCT.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} [%-5p] %m%n%n
.ibatis=debug
.opensymphony.xwork2=info
log4j.logger.java.sql=debug
log4j.logger.org.apache.struts=info
log4j.logger.org.springframework=info
log4j.rootLogger=info, CONSOLE, PRODUCT
我也遇到过这个问题,mybatis-3.0.4 升级到3.1后的版本就可以了。
貌似这个版本是不可以的。
直接添加java.sql包下面的内容作为输出就可以了
mybaits提供两种日志打印的机制,一个是common;一个是slf4j
public void shouldUseCommonsLogging() {
LogFactory.useCommonsLogging();
Log log = LogFactory.getLog(Object.class);
logSomething(log);
assertEquals(log.getClass().getName(), JakartaCommonsLoggingImpl.class.getName());
public void shouldUseLog4J() {
LogFactory.useLog4JLogging();
Log log = LogFactory.getLog(Object.class);
logSomething(log);
assertEquals(log.getClass().getName(), Log4jImpl.class.getName());
.ibatis = debug
.mon.jdbc.SimpleDataSource = debug
.mon.jdbc.ScriptRunner = debug
.ibatis.sqlmap.engine.impl.SqlMapClientDelegate = debug
log4j.logger.org.apache.ibatis=debug
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
已解决问题
未解决问题什么是 MyBatis?
MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。 MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索。MyBatis 可以使用简单的XML 或注解用于配置和原始映射,将接口和 Java 的 POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。
MyBatis下载:/mybatis/mybatis-3/releases
Mybatis实例
对一个User表的CRUD操作:
-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(50) DEFAULT NULL,
`userAge` int(11) DEFAULT NULL,
`userAddress` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'summer', '30', 'shanghai');
INSERT INTO `user` VALUES ('2', 'test2', '22', 'suzhou');
INSERT INTO `user` VALUES ('3', 'test1', '29', 'some place');
INSERT INTO `user` VALUES ('4', 'lu', '28', 'some place');
INSERT INTO `user` VALUES ('5', 'xiaoxun', '27', 'nanjing');
在Src目录下建一个mybatis的xml配置文件Configuration.xml
&?xml version="1.0" encoding="UTF-8" ?&
&!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd"&
&configuration&
&!-- mybatis别名定义 --&
&typeAliases&
&typeAlias alias="User" type="com.mybatis.test.User"/&
&/typeAliases&
&environments default="development"&
&environment id="development"&
&transactionManager type="JDBC"/&
&dataSource type="POOLED"&
&property name="driver" value="com.mysql.jdbc.Driver"/&
&property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis" /&
&property name="username" value="root"/&
&property name="password" value="admin"/&
&/dataSource&
&/environment&
&/environments&
&!-- mybatis的mapper文件,每个xml配置文件对应一个接口 --&
&mapper resource="com/mybatis/test/User.xml"/&
&/mappers&
&/configuration&
定义User mappers的User.xml配置文件
&?xml version="1.0" encoding="UTF-8" ?&
&!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"&
&mapper namespace="com.mybatis.test.IUserOperation"&
&!-- select语句 --&
&select id="selectUserByID" parameterType="int" resultType="User"&
select * from `user` where user.id = #{id}
&!-- 定义的resultMap,可以解决类的属性名和数据库列名不一致的问题--&
&!-- &resultMap type="User" id="userResultMap"&
&id property="id" column="user_id"
&result property="userName" column="user_userName"
&result property="userAge" column="user_userAge"
&result property="userAddress" column="user_userAddress"
&/resultMap& --&
&!-- 返回list的select语句,注意 resultMap的值是指向前面定义好的 --&
&!-- &select id="selectUsersByName" parameterType="string" resultMap="userResultMap"&
select * from user where user.userName = #{userName}
&/select& --&
&select id="selectUsersByName" parameterType="string" resultType="User"&
select * from user where user.userName = #{userName}
&!--执行增加操作的SQL语句。id和parameterType分别与IUserOperation接口中的addUser方法的名字和参数类型一致。
useGeneratedKeys设置为"true"表明要MyBatis获取由数据库自动生成的主键;keyProperty="id"指定把获取到的主键值注入到User的id属性--&
&insert id="addUser" parameterType="User"
useGeneratedKeys="true" keyProperty="id"&
insert into user(userName,userAge,userAddress)
values(#{userName},#{userAge},#{userAddress})
&update id="updateUser" parameterType="User" &
update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id}
&delete id="deleteUser" parameterType="int"&
delete from user where id=#{id}
配置文件实现了接口和SQL语句的映射关系。selectUsersByName采用了2种方式实现,注释掉的也是一种实现,采用resultMap可以把属性和数据库列名映射关系定义好,property为类的属性,column是表的列名,也可以是表列名的别名!
User类的定义:
package com.mybatis.
public class User {
private int
private String userN
private int userA
private String userA
public int getId() {
public void setId(int id) {
public String getUserName() {
return userN
public void setUserName(String userName) {
this.userName = userN
public int getUserAge() {
return userA
public void setUserAge(int userAge) {
this.userAge = userA
public String getUserAddress() {
return userA
public void setUserAddress(String userAddress) {
this.userAddress = userA
public String toString(){
return this.userName+" "+this.userAge+" "+this.userA
IUserOperaton定义:
package com.mybatis.
import java.util.L
public interface IUserOperation {
public User selectUserByID(int id);
public List&User& selectUsersByName(String userName);
public void addUser(User user);
public void updateUser(User user);
public void deleteUser(int id);
IUserOperation为操作接口,函数名和mybatis的xml配置文件中的操作id名对应。
测试类Test:
package com.mybatis.
import java.io.R
import java.util.L
import org.apache.ibatis.io.R
import org.apache.ibatis.session.SqlS
import org.apache.ibatis.session.SqlSessionF
import org.apache.ibatis.session.SqlSessionFactoryB
public class Test {
private static SqlSessionFactory sqlSessionF
private static R
reader = Resources.getResourceAsReader("Configuration.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
public static SqlSessionFactory getSession() {
return sqlSessionF
public void getUserByID(int userID) {
SqlSession session = sqlSessionFactory.openSession();
IUserOperation userOperation = session
.getMapper(IUserOperation.class);
User user = userOperation.selectUserByID(userID);
if (user != null) {
System.out.println(user.getId() + ":" + user.getUserName()
+ ":" + user.getUserAddress());
} finally {
session.close();
public void getUserList(String userName) {
SqlSession session = sqlSessionFactory.openSession();
IUserOperation userOperation = session
.getMapper(IUserOperation.class);
List&User& users = userOperation.selectUsersByName(userName);
for (User user : users) {
System.out.println(user.getId() + ":" + user.getUserName()
+ ":" + user.getUserAddress());
} finally {
session.close();
* 增加后要commit
public void addUser() {
User user = new User();
user.setUserAddress("place");
user.setUserName("test_add");
user.setUserAge(30);
SqlSession session = sqlSessionFactory.openSession();
IUserOperation userOperation = session
.getMapper(IUserOperation.class);
userOperation.addUser(user);
System.out.println("新增用户ID:" + user.getId());
} finally {
session.close();
* 修改后要commit
public void updateUser() {
SqlSession session = sqlSessionFactory.openSession();
IUserOperation userOperation = session
.getMapper(IUserOperation.class);
User user = userOperation.selectUserByID(1);
if (user != null) {
user.setUserAddress("A new place");
userOperation.updateUser(user);
} finally {
session.close();
* 删除后要commit.
* @param id
public void deleteUser(int id) {
SqlSession session = sqlSessionFactory.openSession();
IUserOperation userOperation = session
.getMapper(IUserOperation.class);
userOperation.deleteUser(id);
} finally {
session.close();
public static void main(String[] args) {
Test test = new Test();
// test.getUserByID(1);
// test.getUserList("test1");
// test.addUser();
// test.updateUser();
// test.deleteUser(6);
} catch (Exception e) {
System.out.println(e.getMessage());
代码下载:http://download.csdn.net/detail/luxiaoxun/8056559
http://www.mybatis.org/mybatis-3/zh/getting-started.html
http://legend5/d-5
http://mybatis.github.io/mybatis-3/zh/sqlmap-xml.html
阅读(...) 评论()}

我要回帖

更多关于 orm映射框架 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信