读书人

MyBatis与Spring、commons-dbcp的集成

发布时间: 2012-12-19 14:13:14 作者: rapoo

MyBatis与Spring、commons-dbcp的集成开发(三)
通过 Mapper.xml中的 SQL 操作的 id 来操作数据表,这个不是十分方便
Org_Type org=sess.selectOne("aps.tables.org_type.selectByID",20);
sess.update("aps.tables.org_type.update", org);

如果这个字符串写错了,编译并不会报错,而且众多的ID,开发者也并记不住这么多的ID。
那么就需要更好的封装它。

说一下如何通过 Java 的 interface 来封装 DAO,而不是Class.

来看一下 aps.tables.org_type.selectByID,我们可以把它看成 包.接口名.方法名

那么这个接口就是如下,把Mapper.xml 中的4个操作都封装好了。

package aps.tables;import MybatisTest.domain.Org_Type;public interface org_type {    Org_Type selectByID(int id);    int delete(int id);    int update(Org_Type type);    int insert(Org_Type type);}


具体的使用时,那就简单了,而且不会有错,更可以在接口方法上写JAVADOC注释,便于使用。
org_type typedao=sess.getMapper(org_type.class);
Org_Type org=typedao.selectByID(20);
typedao.update(org);


在这里,如何使用事务保持一致性呢?
在不使用容器事务的情况下,可以使用底层的JDBC的事务来完成。
如下:

session.getConnection().setAutoCommit(false); //开启了事务,没有commit是不会提交的。
try{
......
session.commit();
}
catch(Exception e)
{
try( session.rollback(); )catch(Exception ee){}
}
finally{
session.close();
}

读书人网 >其他数据库

热点推荐