使用MyBatis注解开发,可以省去类配置文件,简洁方便。但是比较复杂的SQL和动态SQL还是建议书写类配置文件。
注解还是不推荐使用的。只是了解了解!简单的CRUD可以使用注解。简单写写。
    把之前的例子改成使用注解的。
 
UserMapper.java

 package com.cy.mybatis.mapper;

 import java.util.List;
import java.util.Map; import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update; import com.cy.mybatis.beans.UserBean; public interface UserMapper {
// 简单的增删改查可以使用注解
// 注解+配置文件 /**
* 新增用戶
* @param user
* @return
* @throws Exception
*/
@Insert("insert into t_user value (null,user.username,user.password,user.account)")
@Options(useGeneratedKeys=true,keyProperty="user.id")
public int insertUser(@Param("user")UserBean user) throws Exception; /**
* 修改用戶
* @param user
* @param id
* @return
* @throws Exception
*/
@Update(" update t_user set username=#{u.username},password=#{u.password},account=#{u.account} where id=#{id}")
public int updateUser (@Param("u")UserBean user,@Param("id")int id) throws Exception; /**
* 刪除用戶
* @param id
* @return
* @throws Exception
*/
@Delete(" delete from t_user where id=#{id} ")
public int deleteUser(int id) throws Exception; /**
* 根据id查询用户信息
* @param id
* @return
* @throws Exception
*/ @Select(" select * from t_user where id=#{id}")
@Results({ @Result(id=true,property="id",column="id",javaType=Integer.class),
@Result(property="username",column="username",javaType=String.class),
@Result(property="password",column="password",javaType=String.class),
@Result(property="account",column="account",javaType=Double.class)
})
public UserBean selectUserById(int id) throws Exception;
/**
* 查询所有的用户信息
* @return
* @throws Exception
*/ @Select(" select * from t_user")
@ResultMap("userMap")
public List<UserBean> selectAllUser() throws Exception; /**
* 批量增加
* @param user
* @return
* @throws Exception
*/
public int batchInsertUser(@Param("users")List<UserBean> user) throws Exception; /**
* 批量删除
* @param list
* @return
* @throws Exception
*/
public int batchDeleteUser(@Param("list")List<Integer> list) throws Exception; /**
* 分页查询数据
* @param parma
* @return
* @throws Exception
*/
public List<UserBean> pagerUser(Map<String, Object> parmas) throws Exception; /**
*
* 分页统计数据
* @param parma
* @return
* @throws Exception
*/
public int countUser(Map<String, Object> parmas) throws Exception; }

UserMapper.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cy.mybatis.mapper.UserMapper">
<!-- 自定义返回结果集 -->
<resultMap id="userMap" type="UserBean">
<id property="id" column="id" javaType="java.lang.Integer"></id>
<result property="username" column="username" javaType="java.lang.String"></result>
<result property="password" column="password" javaType="java.lang.String"></result>
<result property="account" column="account" javaType="java.lang.Double"></result>
</resultMap> <!-- 批量操作和foreach标签 --> <insert id="batchInsertUser" parameterType="java.util.List">
insert into t_user values
<foreach collection="users" item="users" separator=",">
(null,#{users.username},#{users.password},#{users.account})
</foreach>
</insert> <delete id="batchDeleteUser">
delete from t_user where id in (
<foreach collection="list" item="list" separator=",">
#{id}
</foreach>
)
</delete> <!--collection 为用于遍历的元素(必选),支持数组、List、Set -->
<!-- item 表示集合中每一个元素进行迭代时的别名. -->
<!--separator表示在每次进行迭代之间以什么符号作为分隔 符. --> <!--#在生成SQL时,对于字符类型参数,会拼装引号
$在生成SQL时,不会拼装引号,可用于order by之类的参数拼装
-->
<select id="pagerUser" parameterType="java.util.Map" resultMap="userMap">
select * from t_user where 1=1
<if test="username!=null">
and username like '%${username}%'
</if>
limit ${index},${pageSize}
</select> <select id="countUser" parameterType="java.util.Map" resultType="int">
select count(*) from t_user where 1=1
<if test="username != null">
and username like '%${username}%'
</if>
</select> </mapper>
 简单的一个一对一的使用注解的。
 package com.lovo.mybatis.mapper;

 import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.ResultType;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select; import com.lovo.mybatis.beans.HusbandBean;
import com.lovo.mybatis.beans.WifeBean; public interface HusbandMapper { /**
* 保存丈夫
* @param husband
* @return
*/
@Insert("insert into t_husband values (null,#{h.name})")
@Options(useGeneratedKeys=true,keyProperty="h.id")
public int saveHusband(@Param("h")HusbandBean husband); /**
* 根据ID查询丈夫资料
* @param id
* @return
*/
@Select("select * from t_husband where id=#{id}")
@ResultType(HusbandBean.class)
public HusbandBean findHusbandById(int id); /**
* 根据ID查询丈夫与妻子资料
* @param id
* @return
*/
@Select("select * from t_husband where id=#{id}")
@Results({
@Result(id=true,property="id",column="id",javaType=Integer.class),
@Result(property="name",column="name",javaType=String.class),
@Result(property="wife",column="id",javaType=WifeBean.class,one=@One(select="com.lovo.mybatis.mapper.WifeMapper.findWifeByHusbandId"))
})
public HusbandBean findHusbandAndWife(int id); }
 package com.cy.mybatis.mapper;

 import org.apache.ibatis.annotations.ResultType;
import org.apache.ibatis.annotations.Select; import com.cy.mybatis.beans.WifeBean; public interface WifeMapper { @Select("select * from t_wife where fk_husband_id = #{id}")
@ResultType(WifeBean.class)
public WifeBean selectWifeByHusbandId(int id)throws Exception; }

注意:使用resultType时,一定要保证,你属性名与字段名相同;如果不相同,就使用resultMap 。

 

MyBatis学习笔记(四) 注解的更多相关文章

  1. mybatis学习笔记(四)-- 为实体类定义别名两种方法(基于xml映射)

    下面示例在mybatis学习笔记(二)-- 使用mybatisUtil工具类体验基于xml和注解实现 Demo的基础上进行优化 以新增一个用户为例子,原UserMapper.xml配置如下: < ...

  2. mybatis学习笔记四(动态sql)

    直接贴图,注解在代码上,其他的配置文件在学习一中就不贴了 1 数据库 2 实体类 package com.home.entity; /** * 此类是: 用户实体类 * @author hpc * @ ...

  3. MyBatis学习笔记(四)——解决字段名与实体类属性名不相同的冲突

    转自孤傲苍狼的博客:http://www.cnblogs.com/xdp-gacl/p/4264425.html 在平时的开发中,我们表中的字段名和表对应实体类的属性名称不一定都是完全相同的,下面来演 ...

  4. mybatis学习笔记(四)

    resultType 语句返回值类型的完整类名或别名 resultType 返回的是一个map集合,key是列名,value是对应的值 使用resultMap实现联表查询 resultMap 查询的结 ...

  5. Mybatis学习笔记(四) —— SqlMapConfig.xml配置文件

    一.properties(属性) SqlMapConfig.xml可以引用java属性文件中的配置信息 在config下定义db.properties文件,如下所示: db.properties配置文 ...

  6. mybatis学习笔记四

    记录下动态sql的常用标签: 1.where 一般用作数据操作添加的条件 例子: <select id="selectByRoleId" resultMap="re ...

  7. mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

    文章介绍结构一览 一.使用maven创建web项目 1.新建maven项目 2.修改jre版本 3.修改Project Facts,生成WebContent文件夾 4.将WebContent下的两个文 ...

  8. mybatis学习笔记(二)-- 使用mybatisUtil工具类体验基于xml和注解实现

    项目结构  基础入门可参考:mybatis学习笔记(一)-- 简单入门(附测试Demo详细过程) 开始体验 1.新建项目,新建类MybatisUtil.java,路径:src/util/Mybatis ...

  9. mybatis 学习笔记(四):mybatis 和 spring 的整合

    mybatis 学习笔记(四):mybatis 和 spring 的整合 尝试一下整合 mybatis 和 spring. 思路 spring通过单例方式管理SqlSessionFactory. sp ...

随机推荐

  1. 周赛-kiki's game 分类: 比赛 2015-08-02 09:24 7人阅读 评论(0) 收藏

    kiki's game Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 40000/10000 K (Java/Others) Total S ...

  2. 客服端调用自定义宿主的WCF报错"没有终结点在侦听可以接受消息的http://localhost:8085/mex。这通常是由于不正确的地址或者 SOAP 操作导致的错误"的解决方案。

    没有终结点在侦听可以接受消息的http://localhost:8085/mex.这通常是由于不正确的地址或者 SOAP 操作导致的错误. 这个错误是由于没有启动元数据交换终结点(MEX)导致的.在宿 ...

  3. 2016CCPC东北地区大学生程序设计竞赛 1001 HDU5922

    链接http://acm.hdu.edu.cn/showproblem.php?pid=5922 题意:最小生成树,但边的权值是连接两点的最小公倍数 解法:不要真的写最小生成树啦,只要其他点和第一点相 ...

  4. 2016年12月1日 星期四 --出埃及记 Exodus 20:22

    2016年12月1日 星期四 --出埃及记 Exodus 20:22 Then the LORD said to Moses, "Tell the Israelites this: `You ...

  5. Python操作文件、文件夹、字符串

    Python 字符串操作 去空格及特殊符号 s.strip().lstrip().rstrip(',') 复制字符串 #strcpy(sStr1,sStr2) sStr1 = 'strcpy' sSt ...

  6. JQuery中Ajax的Post提交中文乱码的解决方案

    出自:http://m.blog.csdn.net/blog/blueheart20/26370023 引言: 在JQuery的Ajax POST请求中,进行请求,其中的中文在后台,显示为乱码,该如何 ...

  7. 图片轮播的JS写法,通用涉及多个轮播

    本代码是借鉴大神的代码分析理解后,自己改写的!有不足指出希望给为大神指点. 核心只有一个JS,里面包含了css样式. 展示效果图:

  8. java正则API简单解析

    java.util.regex是一个用正则表达式所订制的模式来对字符串进行匹配工作的类库包. 1.简介: java.util.regex是一个用正则表达式所订制的模式来对字符串进行匹配工作的类库包. ...

  9. Python入门-引号

    Python 接收单引号(' ),双引号(" ),三引号(''' """) 来表示字符串,引号的开始与结束必须的相同类型的. 其中三引号可以由多行组成,编写多行 ...

  10. 6.mybatis异常:SQL Mapper Configuration,Error parsing Mapper XML,Could not resolve type alias

    在xxxMapper中 <select id="getClazz" parameterType="int" resultType="getCla ...