MyBatis 常用写法

实际项目总结的一些用法,以后用相似的可以直接拷贝


foreach用法:

[java]  view plain  copy
  1. /** 
  2.  * 查询出用户最大的登录时间 
  3.  * @param informedObjIds 用户id集合 
  4.  * @return 
  5.  */  
  6. List<UserLastLoginBean> selectUserMaxLoginTimeByUserIds(  
  7.         List<Integer> informedObjIds);  

[html]  view plain  copy
  1. <resultMap id="MaxLoginTimeMap" type="com.clou.douliu.server.bean.UserLastLoginBean">  
  2.     <id column="userId" property="userId" jdbcType="INTEGER" />  
  3.     <result column="maxLoginTime" property="maxLoginTime" jdbcType="TIMESTAMP" />  
  4. </resultMap>  
[html]  view plain  copy
  1. <!-- 根据用户ID集合查询出用户最近登录时间 -->  
  2. <select id="selectUserMaxLoginTimeByUserIds" parameterType="map"  resultMap="MaxLoginTimeMap">  
  3.     SELECT  
  4.         USER_ID as userId ,  
  5.         MAX(LOGIN_TIME) as maxLoginTime  
  6.     FROM  
  7.         user_login_details  
  8.     WHERE  
  9.         USER_ID IN  
  10.         <foreach collection="list" item="userId" index="index" open="("  
  11.             close=")" separator=",">  
  12.             #{userId}  
  13.         </foreach>  
  14.     group by USER_ID  
  15.     ORDER BY USER_ID ASC  
  16. </select>  

得到insert后的自增长ID

[java]  view plain  copy
  1. 调用:(count为影响条数,reply的id字段在添加之后会有值---自增长ID)  
  2. int count = this.mapperFactory.replyMapper.insertSelective(reply);  

[java]  view plain  copy
  1. //mapper.java  
  2. public abstract int insert(Reply paramReply);  

[html]  view plain  copy
  1. <insert id="insert" parameterType="com.clou.douliu.server.bean.mybatis.Reply" >  
  2.     <selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER" >  
  3.       SELECT LAST_INSERT_ID()  
  4.     </selectKey>  
  5.     insert into comment (USER_ID, CONTENT, PICTURE,   
  6.       TIMETAG, TYPE, ACT_ID,   
  7.       VALID)  
  8.     values (#{userId,jdbcType=INTEGER}, #{content,jdbcType=VARCHAR},   
  9.      #{picture,jdbcType=VARCHAR,javaType=String,  
  10. typeHandler=com.clou.douliu.server.mybatis.plugin.RemoveDomainTypeHandler},   
  11.       #{timetag,jdbcType=TIMESTAMP}, #{type,jdbcType=INTEGER},#{actId,jdbcType=INTEGER},        
  12.       #{valid,jdbcType=SMALLINT})  
  13.  </insert>  

排除(筛选热门分享,排除管理员1号)

[html]  view plain  copy
  1. <!-- 选取分享列表,包含发布分享的人,以及该分享对应的图片列表. -->  
  2. <select id="selectHotShareAlternativeListByUserId" parameterType="map"   resultMap="ShareDetailMap">  
  3. SELECT  * FROM  
  4.     (SELECT   
  5. <include refid="Alias_Column_List" />,  
  6. <include refid="com.clou.douliu.server.mybatis.mapper.UserMapper.Alias_Column_List" />,  
  7. <include     refid="com.clou.douliu.server.mybatis.mapper.UserDetailsMapper.Alias_Column_List"/>  
  8.      FROM  
  9.         ACTIVITYS ACTIVITYS   
  10.     left join USER USER on (USER.ID=ACTIVITYS.USER_ID)   
  11.     left join user_details user_details ON (user_details.USER_ID = USER.ID)  
  12.     WHERE  
  13.         USER.TYPE > 0   
  14.         AND USER.ID = #{userId,jdbcType=INTEGER}  
  15. AND ACTIVITYS.valid = 1  
  16. AND ACTIVITYS.timetag >= #{startDate,jdbcType=TIMESTAMP}  
  17.         AND ACTIVITYS.timetag <= date_add(#{endDate,jdbcType=TIMESTAMP},interval 24 hour)  
  18.     ORDER BY date(ACTIVITYS.timetag) desc  
  19.     LIMIT #{start,jdbcType=INTEGER},#{loadSize,jdbcType=INTEGER})  TEMP  
  20. WHERE  
  21. NOT EXISTS(SELECT 1 FROM HOTS HOTS WHERE HOTS.ACT_ID = TEMP.ACTIVITYS_ID)  
  22. </select>  

list参数传递

[java]  view plain  copy
  1. /** 
  2.     * 通过id集合删除记录 
  3.     * @param delPhotoIdList id集合 
  4.     * @return 
  5. */  
  6. public abstract int removeByIdList(List<Integer> delPhotoIdList);  

[html]  view plain  copy
  1. <!-- 通过id集合删除记录 -->  
  2. <delete id="removeByIdList">  
  3.     delete from album_detail where ID in  
  4.        <foreach collection="list" item="photoId" index="index"  
  5.            open="(" close=")" separator=",">  
  6.            #{photoId}  
  7.       </foreach>  
  8. </delete>  

Map参数传递(find_in_set用法)

[java]  view plain  copy
  1. /** 
  2.  * 根据群id集合获取群的全部信息,按照list里面的序号排序 
  3.  * @param paramMap 参数map <br/> 
  4.  *  groupIdList  --- List<Integer>   <br/> 
  5.  *  sortStr ---- String   排序字符串,格式:'1932,2342,3242' 也就是集合中的id,已逗号隔开 
  6.  */  
  7. List<Groups> selectGroupListBySort(Map<String, Object> paramMap);  

[html]  view plain  copy
  1. <!-- 根据群id集合获取群的全部信息,按照list里面的序号排序 -->  
  2. <select id="selectGroupListBySort" resultMap="BaseResultMap" parameterType="java.util.Map" >  
  3.   select  
  4.   <include refid="Base_Column_List" />  
  5.   from groups  
  6.   where id in  
  7.    <foreach collection="groupIdList" item="item" index="index" open="(" close=")" separator=",">  
  8.     #{item}  
  9.  </foreach>  
  10.  and status = 1  
  11.  order by find_in_set(id, #{sortStr,jdbcType=VARCHAR}) asc;  
  12. </select>  

[java]  view plain  copy
  1. Bussiness方法:从redis中取出热门群组列表,按照指定顺序从数据库中查询详细信息  
  2. /** 
  3.  * 获取推荐群列表 
  4.  * @return 
  5.  */  
  6. public List<Groups> selectTopGroups() {  
  7.     CacheManager cm=CacheManager.getInstance();  
  8.     Set<String> s=cm.getRecommandGroups();  
  9.       
  10.     logger.debug("推荐列表" + s);  
  11.       
  12.     List<Integer> groupIds = null;   
  13.     if(s!=null && s.size() > 0){  
  14.         groupIds = new ArrayList<Integer>();  
  15.         for(String g : s){  
  16.             try {  
  17.                 Integer gId = Integer.parseInt(g);  
  18.                 groupIds.add(gId);  
  19.             } catch (Exception e) {  
  20.             }  
  21.         }  
  22.     }  
  23.     if(groupIds != null && groupIds.size() > 0){  
  24.             Map<String, Object> paramMap = new HashMap<String, Object>();  
  25.             StringBuilder sortStr = new StringBuilder();  
  26.             for(Integer id : groupIds){  
  27.                 sortStr.append(id).append(",");  
  28.             }  
  29.             sortStr.delete(sortStr.lastIndexOf(","), sortStr.length());  
  30.           
  31.             paramMap.put("groupIdList", groupIds);  
  32.             paramMap.put("sortStr", sortStr.toString());  
  33.           
  34.         return this.mapperFactory.groupsMapper.selectGroupListBySort(paramMap);  
  35.     }  
  36.     return null;  
  37. }  

Criteria的Where条件拼凑(工具自动生成)

1、不带别名的写法,用于单张表的操作

[html]  view plain  copy
  1. <sql id="Example_Where_Clause" >  
  2.   <where >  
  3.     <foreach collection="oredCriteria" item="criteria" separator="or" >  
  4.       <if test="criteria.valid" >  
  5.         <trim prefix="(" suffix=")" prefixOverrides="and" >  
  6.           <foreach collection="criteria.criteria" item="criterion" >  
  7.             <choose >  
  8.               <when test="criterion.noValue" >  
  9.                 and ${criterion.condition}  
  10.               </when>  
  11.               <when test="criterion.singleValue" >  
  12.                 and ${criterion.condition} #{criterion.value}  
  13.               </when>  
  14.               <when test="criterion.betweenValue" >  
  15.                 and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}  
  16.               </when>  
  17.               <when test="criterion.listValue" >  
  18.                 and ${criterion.condition}  
  19.                 <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >  
  20.                   #{listItem}  
  21.                 </foreach>  
  22.               </when>  
  23.             </choose>  
  24.           </foreach>  
  25.         </trim>  
  26.       </if>  
  27.     </foreach>  
  28.   </where>  
  29. </sql>  

例子:

[java]  view plain  copy
  1. List<PushSchema> selectByExample(PushSchemaCriteria example) throws RuntimeException;  
[html]  view plain  copy
  1. <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.clou.douliu.server.bean.mybatis.PushSchemaCriteria" >  
  2.   select  
  3.   <if test="distinct" >  
  4.     distinct  
  5.   </if>  
  6.   <include refid="Base_Column_List" />  
  7.   from push_schema  
  8.   <if test="_parameter != null" >  
  9.     <include refid="Example_Where_Clause" />  
  10.   </if>  
  11.   <if test="orderByClause != null" >  
  12.     order by ${orderByClause}  
  13.   </if>  
  14.   <if test="start >= 0 " >  
  15.     limit ${start}  
  16.   </if>  
  17.   <if test="count >= 0 " >  
  18.     ,${count}  
  19.   </if>  
  20. </select>  

带别名的写法,用于多张表联合操作

[html]  view plain  copy
  1. <sql id="Alias_Update_By_Example_Where_Clause" >  
  2.   <where >  
  3.     <foreach collection="example.oredCriteria" item="criteria" separator="or" >  
  4.       <if test="criteria.valid" >  
  5.         <trim prefix="(" suffix=")" prefixOverrides="and" >  
  6.           <foreach collection="criteria.criteria" item="criterion" >  
  7.             <choose >  
  8.               <when test="criterion.noValue" >  
  9.                 and PUSH_SCHEMA.${criterion.condition}  
  10.               </when>  
  11.               <when test="criterion.singleValue" >  
  12.                 and PUSH_SCHEMA.${criterion.condition} #{criterion.value}  
  13.               </when>  
  14.               <when test="criterion.betweenValue" >  
  15.                 and PUSH_SCHEMA.${criterion.condition} #{criterion.value} and #{criterion.secondValue}  
  16.               </when>  
  17.               <when test="criterion.listValue" >  
  18.                 and PUSH_SCHEMA.${criterion.condition}  
  19.                 <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >  
  20.                   #{listItem}  
  21.                 </foreach>  
  22.               </when>  
  23.             </choose>  
  24.           </foreach>  
  25.         </trim>  
  26.       </if>  
  27.     </foreach>  
  28.   </where>  
  29. </sql>  
例子:

[java]  view plain  copy
  1. /** 
  2.  * 查询方案列表(包含具体方案step的List) 
  3.  * @param example 
  4.  * @return 
  5.  * @throws RuntimeException 
  6.  */  
  7. List<PushSchema> selectWithStepByExample(PushSchemaCriteria example) throws RuntimeException;  
[html]  view plain  copy
  1. <!-- 查询方案列表(关联查询具体方案) -->  
  2. <select id="selectWithStepByExample" resultMap="SchemaWithStepMap" parameterType="com.clou.douliu.server.bean.mybatis.PushSchemaCriteria" >  
  3.   select  
  4.   <include refid="Alias_Column_List" />,  
  5.   <include refid="com.clou.douliu.server.mybatis.mapper.PushStepMapper.Alias_Column_List" />  
  6.   from push_schema PUSH_SCHEMA   
  7.      left join push_step PUSH_STEP on (PUSH_SCHEMA.ID=PUSH_STEP.SCHEMA_ID)   
  8.   <if test="_parameter != null" >  
  9.     <include refid="Alias_Example_Where_Clause" />  
  10.   </if>  
  11.   <if test="orderByClause != null" >  
  12.     order by ${orderByClause}  
  13.   </if>  
  14.   <if test="start >= 0 " >  
  15.     limit ${start}  
  16.   </if>  
  17.   <if test="count >= 0 " >  
  18.     ,${count}  
  19.   </if>  
  20. </select>  

3、复杂条件筛选

刚刚这个例子,只是针对与Push_Schma表有筛选条件,如果Push_step表也有条件,那么条件语句就要改写了

原理:

先有where语句,再把Criteria的条件拼凑到后面,

这就涉及到Criteria条件到底存不存在的问题,存在才有and ,不存在就直接结束

[html]  view plain  copy
  1. <if test="index == 0">  
  2.     AND  
  3. </if>  

暂时没有研究传递两个参数(PushSchemaCriteria, PushStepCriteria)的形式

有改写了where条件的写法,详细请看下一个案例。



Collection 和 association 的用法

[java]  view plain  copy
  1. /** 
  2.  * selectShareDetailList: 选取分享列表,包含发布分享的人,以及该分享对应的图片列表. <br/> 
  3.  *  
  4.  *  
  5.  * @author Hongbin Yuan 
  6.  * @param bean 
  7.  * @return 
  8.  * @since JDK 1.6 
  9.  */  
  10. public abstract List<Share> selectShareDetailList(ShareCriteria paramShareCriteria);  

[html]  view plain  copy
  1. <!-- 分享列表,包含发布分享的人,以及该分享对应的图片列表 -->  
  2. <resultMap id="ShareDetailMap" type="com.clou.douliu.server.bean.mybatis.Share" extends="AliasResultMap">  
  3.     <association property="publisher"  
  4.         resultMap="com.clou.douliu.server.mybatis.mapper.UserMapper.UserDetailResultMap"></association>  
  5.     <collection property="sharePictureList" resultMap="com.clou.douliu.server.mybatis.mapper.SharePictureMapper.AliasResultMap"></collection>  
  6. </resultMap>  

[html]  view plain  copy
  1. <!-- 选取分享列表,包含发布分享的人,以及该分享对应的图片列表. -->  
  2. <select id="selectShareDetailList" parameterType="com.clou.douliu.server.bean.mybatis.ShareCriteria" resultMap="ShareDetailMap">  
  3.     SELECT  
  4.     <include refid="Alias_Column_List" />,  
  5.     <include  
  6.         refid="com.clou.douliu.server.mybatis.mapper.UserMapper.Alias_Column_List" />,  
  7.     <include  
  8.         refid="com.clou.douliu.server.mybatis.mapper.SharePictureMapper.Alias_Column_List" />  
  9.     FROM  
  10.         ACTIVITYS ACTIVITYS   
  11.         left join USER USER on (USER.ID=ACTIVITYS.USER_ID)   
  12.         left join ACT_PICTURE ACT_PICTURE on (ACTIVITYS.ID=ACT_PICTURE.ACT_ID)  
  13.     WHERE   
  14.         USER.type > 0   
  15.         <foreach collection="oredCriteria" item="criteria" index="index" separator="or">  
  16.             <if test="criteria.valid" >  
  17.             <if test="index == 0">  
  18.                 AND  
  19.             </if>  
  20.             <trim prefix="(" suffix=")" prefixOverrides="and">  
  21.                 <foreach collection="criteria.criteria" item="criterion">  
  22.                     <choose>  
  23.                         <when test="criterion.noValue">  
  24.                             and ACTIVITYS.${criterion.condition}  
  25.                         </when>  
  26.                         <when test="criterion.singleValue">  
  27.                             and ACTIVITYS.${criterion.condition} #{criterion.value}  
  28.                         </when>  
  29.                         <when test="criterion.betweenValue">  
  30.                             and ACTIVITYS.${criterion.condition} #{criterion.value} and  
  31.                             #{criterion.secondValue}  
  32.                         </when>  
  33.                         <when test="criterion.listValue">  
  34.                             and ACTIVITYS.${criterion.condition}  
  35.                             <foreach collection="criterion.value" item="listItem"  
  36.                                 open="(" close=")" separator=",">  
  37.                                 #{listItem}  
  38.                             </foreach>  
  39.                         </when>  
  40.                     </choose>  
  41.                 </foreach>  
  42.             </trim>  
  43.         </if>  
  44.     </foreach>  
  45.     <if test="orderByClause != null">  
  46.         order by ${orderByClause}  
  47.     </if>  
  48.     <if test="start >= 0 ">  
  49.         limit ${start}  
  50.     </if>  
  51.     <if test="end >= 0 ">  
  52.         ,${end}  
  53.     </if>  
  54. </select>  

日期操作,choose语法,分页做法

[java]  view plain  copy
  1. /** 
  2.  * selectCommonShareList:查询分享列表,包含分享人的信息 <br/> 
  3.  * @author dhh 
  4.  * @param userId        查询指定用户的分享 
  5.  * @param daysBeforeToday   默认查询多少天之内的分享 
  6.  * @param lastShareId       页面加载时,查询的上一条分享的id 
  7.  * @param loadSize      每次加载的分享数量 
  8.  * @return 
  9.  * @since JDK 1.6 
  10.  */  
  11. public abstract List<Share> selectCommonShareList(  
  12.         @Param("userId") Integer userId,  
  13.         @Param("daysBeforeToday") Integer daysBeforeToday,  
  14.         @Param("lastShareId") Integer lastShareId,  
  15.         @Param("loadSize") Integer loadSize);  

[html]  view plain  copy
  1. <!-- 查询普通分享 -->  
  2. <resultMap id="SharePublisherMap" type="com.clou.douliu.server.bean.mybatis.Share"   extends="AliasResultMap">  
  3.     <association property="publisher"  
  4.         resultMap="com.clou.douliu.server.mybatis.mapper.UserMapper.AliasResultMap">  
  5. </association>  
  6. </resultMap>  
  7.   
  8.   
  9. <!-- 查询普通分享 -->  
  10. <select id="selectCommonShareList" parameterType="map" resultMap="SharePublisherMap">  
  11.     SELECT  
  12.     <include refid="Alias_Column_List" />,  
  13.     <include refid="com.douliu.server.mybatis.mapper.UserMapper.Alias_Column_List" />  
  14.     FROM  
  15.         USER USER,  
  16.         ACTIVITYS ACTIVITYS  
  17.     WHERE  
  18.         USER.ID=ACTIVITYS.USER_ID  
  19.         AND ACTIVITYS.TYPE = 5  
  20.         AND USER.TYPE > 0  
  21.         AND ACTIVITYS.VALID > -1  
  22.         <if test="userId != null and userId >0">  
  23.             AND USER.ID = #{userId,jdbcType=INTEGER}  
  24.         </if>  
  25.         AND ACTIVITYS.TIMETAG > DATE_ADD(CURDATE(),INTERVAL -  
  26.         <choose>  
  27.             <when test="daysBeforeToday != null and daysBeforeToday > 0">  
  28.                 #{daysBeforeToday}  
  29.             </when>  
  30.             <otherwise>  
  31.                 7  
  32.             </otherwise>  
  33.         </choose>  
  34.         DAY)  
  35.         <if test="lastShareId != null">  
  36.             AND ACTIVITYS.ID < #{lastShareId}  
  37.         </if>  
  38.         ORDER BY  
  39.             ACTIVITYS.ID DESC  
  40.         LIMIT 0 ,  
  41.         <choose>  
  42.             <when test="loadSize != null and loadSize > 0">  
  43.                 #{loadSize}  
  44.             </when>  
  45.             <otherwise>  
  46.                 10  
  47.             </otherwise>  
  48.         </choose>  
  49. </select>  

☞分页查询一个注意点:如果想分页查出的数据不出现重复(app有新增),最后记录上一次查询的最大值,然后在分页查询的时候 id>最大值 limit (也可以传最小值,不过客户端要每次维护这个值,但是如果存最大值,就第一次维护就行了)



Collection附加一种写法:




不推荐使用,只是语法是这样,之前做举报功能列表,而一个聊天举报可能对应很多条聊天信息,用这种方法查询,结果很慢,后来先查出列表,取出ID列表,然后in(ids) 查询聊天记录,然后for循坏加到对应的id,再set进去,效率反而快一些。

### 回答1: mybatis是一个用于Java应用程序的持久层框架。它提供了一种将应用程序与数据库连接的方式,并将数据库操作封装在映射语句中。 mybatis的mapper是一种使用XML或注解的方式来配置映射语句的方式。你可以在mapper中写入查询、插入、更新或删除数据的SQL语句,然后通过mybatis的API在应用程序中调用这些语句。 下面是一个使用XML配置映射语句的示例: ``` <mapper namespace="org.mybatis.example.BlogMapper"> <select id="selectBlog" resultType="Blog"> SELECT * FROM BLOG WHERE ID = #{id} </select> </mapper> ``` 这段代码定义了一个名为"selectBlog"的映射语句,它将返回一个名为"Blog"的对象。在应用程序中,你可以使用mybatis的API调用这个映射语句,如下所示: ``` BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); Blog blog = mapper.selectBlog(1); ``` 你也可以使用注解的方式来配置映射语句,如下所示: ``` @Mapper public interface BlogMapper { @Select("SELECT * FROM BLOG WHERE ID = #{id}") Blog selectBlog(int id); } ``` 在应用程序中,你可以通过注入mapper的方式来使用这个接口: ``` @Autowired private BlogMapper mapper; Blog blog = mapper.selectBlog(1); ``` 希望这些信息对你有帮助。如果你有任何关于mybatis的疑问,请随 ### 回答2: Mybatis 是一款开源的持久层框架,可以方便地与关系型数据库进行交互。在使用 Mybatis 进行开发时,我们需要通过编写 Mapper 文件来定义 SQL 语句和映射关系。 Mybatis 的 Mapper 文件通常以 XML 格式编写,主要包含以下内容: 1. Namespace 命名空间:用于唯一标识该 Mapper 文件,一般以 Mapper 接口的完全限定名命名。 2. SQL 语句定义:通过 `<sql>` 标签定义 SQL 片段,可以在不同的 SQL 语句中重复使用。例如,可以将查询条件、插入语句等常用语句定义为 SQL 片段。 3. ResultMap 结果映射:通过 `<resultMap>` 标签定义实体类与数据库表之间的映射关系。可以通过 `<result>` 标签指定数据库字段与实体类属性的对应关系。 4. Select 语句:通过 `<select>` 标签定义查询语句。其中可以使用 `<include>` 标签引用 SQL 片段,还可以通过 `<if>` 标签实现动态条件查询。 5. Insert、Update、Delete 语句:通过 `<insert>`、`<update>`、`<delete>` 标签定义插入、更新、删除语句。 6. 参数传递:可以通过 `<parameterType>` 标签指定参数类型,也可以通过 `#{}` 占位符接收传入的参数。 使用 Mybatis 的 Mapper 写法,可以将 SQL 语句与 Java 代码分离,使得代码更加清晰、易于维护。此外,Mybatis 还提供了注解方式的 Mapper 写法,可以使用注解直接在 Mapper 接口上定义 SQL 语句,更加简洁方便。 总而言之,Mybatis 的 Mapper 写法包括定义命名空间、定义 SQL 语句、定义结果映射、定义各种 CRUD 操作等。通过合理地使用这些标签,我们能够更方便地编写和管理数据库操作语句,提高开发效率。 ### 回答3: Mybatis是一个Java的持久层框架,它提供了一种通过配置文件或注解的方式来实现对象与关系数据库之间的映射。Mapper是Mybatis中重要的组成部分,它用于定义CRUD操作以及其他与数据库交互相关的方法。 在Mybatis中,我们可以使用XML文件或注解来编写Mapper。下面是使用XML文件编写Mapper的示例: 1. 首先,创建一个XML文件,命名为"UserMapper.xml"。在该文件中,定义了Mapper的命名空间以及方法的映射关系: ```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.example.UserMapper"> <select id="getUserById" parameterType="int" resultType="com.example.User"> SELECT * FROM user WHERE id = #{id} </select> <insert id="addUser" parameterType="com.example.User"> INSERT INTO user (id, name, age) VALUES (#{id}, #{name}, #{age}) </insert> <update id="updateUser" parameterType="com.example.User"> UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id} </update> <delete id="deleteUserById" parameterType="int"> DELETE FROM user WHERE id = #{id} </delete> </mapper> ``` 2. 在Java中创建一个接口,命名为"UserMapper",用于定义Mapper接口中的方法: ```java package com.example; public interface UserMapper { User getUserById(int id); void addUser(User user); void updateUser(User user); void deleteUserById(int id); } ``` 3. 编写一个类,实现UserMapper接口。在该类中使用Mybatis的SqlSessionFactory和SqlSession来执行SQL语句: ```java package com.example; public class UserMapperImpl implements UserMapper { private SqlSessionFactory sqlSessionFactory; public UserMapperImpl(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } @Override public User getUserById(int id) { SqlSession sqlSession = sqlSessionFactory.openSession(); User user = sqlSession.selectOne("com.example.UserMapper.getUserById", id); sqlSession.close(); return user; } @Override public void addUser(User user) { SqlSession sqlSession = sqlSessionFactory.openSession(); sqlSession.insert("com.example.UserMapper.addUser", user); sqlSession.commit(); sqlSession.close(); } @Override public void updateUser(User user) { SqlSession sqlSession = sqlSessionFactory.openSession(); sqlSession.update("com.example.UserMapper.updateUser", user); sqlSession.commit(); sqlSession.close(); } @Override public void deleteUserById(int id) { SqlSession sqlSession = sqlSessionFactory.openSession(); sqlSession.delete("com.example.UserMapper.deleteUserById", id); sqlSession.commit(); sqlSession.close(); } } ``` 通过以上步骤,我们就成功编写了一个使用Mybatis的Mapper。XML文件中定义了SQL语句,Java接口定义了Mapper接口方法,而实现类中用于执行SQL语句和数据库交互。这样,我们就可以通过调用Mapper接口来实现对数据库的增删改查操作。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值