求教,Mybatis如何实现dao层的通用base操作

2025-03-19 04:21:37
推荐回答(1个)
回答1:

1.ibatis 实例配置

一个典型的配置文件如下:

PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">


cacheModelsEnabled="true"
enhancementEnabled="true"
lazyLoadingEnabled="true"
errorTracingEnabled="true"
maxRequests="32"
maxSessions="10"
maxTransactions="5"
useStatementNamespaces="false"
/>



















2. POJO(Plain Ordinary Java Object)
下面是用作示例的一个POJO:
public class User implements Serializable {
private Integer id;
private String name;
private Integer sex;
private Set addresses = new HashSet();

/** default constructor */
public User() {
}

public Integer getId() {
return this.id; }
public void setId(Integer id) {
this.id = id;
}

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

public Integer getSex() {
return this.sex;
}

public void setSex(Integer sex) {
this.sex = sex;
}
}

3. 映射文件
与Hibernate 不同。因为需要人工编写SQL 代码,ibatis 的映射文件一般采用手动编写(通过Copy/Paste,手工编写映射文件也并没想象中的麻烦)。针对上面POJO 的映射代码如下:









UPDATE t_user
SET name=#name#, sex=#sex#
WHERE id = #id#
]]>



INSERT INTO t_user ( name, sex)
VALUES ( #name#,#sex# )



delete from t_user
where id = #value#




上面的映射文件可以看出,通