Mybatis实战

Mybatis实战
1、使用spring-mabatis 工具自动生成数据库相关代码和xml文件
1.1 在数据库中生成数据库表(设计时确定表名称和字段类型)
1.2 配置工具中的generatorConfig1.xml,确定目标文件
1.3 执行工具cmd

2、在配置 TableName***DoMapper.xml 中增加你的sql脚本和java函数名,注意函数的输入/输出参数

2.1 查询操作传递多个参数时,建议利用hashmap做,parameterType="map"
<select id="selectByDate" parameterType="map" resultMap="campaignStats">
<![CDATA[
Select * FROM CampaignStats Where statsDate >= #{start} AND statsDate <= #{end}
]]>
</select>

对应的 Java 代码为
public List<DpCampaignStats> selectByDate(Date start, Date end){
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Date> map = new HashMap<String, Date>();
map.put("start", start);
map.put("end", end);
List<DpCampaignStats> list = session.selectList("DpCampaignStats.selectByDate", map);
return list;
} finally {
session.close();
}
}

2.2 查询操作返回list类型而定义 resultMap, id 是唯一标识
select id="selectUsers" parameterType="string" resultMap="resultListUser"
//函数参数类型String,返回类型是list
#{name}中name大小写敏感。

2.3 联合查询
多对一的实现:
场景:在读取某个用户发表的所有文章
<!-- User 联合文章进行查询 方法之一的配置 (多对一的方式) -->
<resultMap id="resultUserArticleList" type="Article">
   <id property="id" column="ai d" />
   <result property="title" column="title" />
   <result property="content" column="content" />
   <association property="user" javaType="User">
   <id property="id" column="id" />
   <result property="userName" column="userName" />
   <result property="userAddress" column="userAddress" />
</association>
</resultMap>
<select id="getUserArticles" parameterType="int" resultMap="resultUserArticleList">
     select user.id,user.userName,user.userAddress,article.id aid,article.title,article.content from user,article
     where user.id=article.userid and user.id=#{id}
</select>
用 association 来得到关联的用
3、数据源配置
webapp/WEB-INF/web.xml -> classpath:spring/applicationContext.xml,classpath:spring/spring-jdbc.xml,classpath:spring/spring-timer.xml
spring-jdbc.xml -> classpath:application.properties (数据库配置)

 
原文地址:https://www.cnblogs.com/jing1617/p/6423143.html