1.Mybatis

  a.定义:MyBatis 是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架

  b.步骤:

    ①在src下创建 SqlMapConfig.xml 及 datasource.properties

    ②建UserMapper.java(相当于DAO)

public interface UserMapper {

    public int addUser(@Param("user")User user);
public int delUserById(int userId);
public int updateUser(@Param("user")User user);
public User findUserById(int userId);
public List<User> findAllUser(); }

    ③建UserMapper.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.wode.mapper.UserMapper">
<resultMap id="userMap" type="User">
<id property="userId" column="user_id" />
<result property="userName" column="user_name"/>
<result property="userPwd" column="user_pwd"/>
<result property="userType" column="user_type"/>
</resultMap> <insert id="addUser" parameterType="User">
insert into users (user_id,user_name,user_pwd,user_type) values (null,#{user.userName},#{user.userPwd},#{user.userType})
</insert> <delete id="delUserById" parameterType="int">
delete from users where user_id=#{userId}
</delete> <update id="updateUser" parameterType="User">
update users set user_name = #{user.userName},user_pwd = #{user.userPwd},user_type = #{user.userType} where user_id = #{user.userId}
</update> <select id="findUserById" parameterType="int" resultMap="userMap">
select * from users where user_id = #{user.userId}
</select> <select id="findAllUser" resultMap="userMap">
select * from users
</select> </mapper>

    ④在Service中个使用

//一下代码可封装于另一个类中
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
SqlSession session = sessionFactory.openSession() //使用
UserMapper mapper=session.getMapper(UserMapper.class); //增
int result=mapper.addUser(user);
session.commit(); //删
int result=mapper.delUserById(id);
session.commit(); //改
int result=mapper.updateUser(user);
session.commit(); //查单个对象
User user = mapper.findUserById(userId); //查所有对象
List<User> users = mapper.findAllUser()

2.其他查询

  a.查询聚合函数

    UserMapper.xml中

     <select id="findCountUser" resultType="int">
select count(*) from users
</select>

    UserMapper.java中

public int findCountUser();

  b.模糊查询

    防止sql注入:

     <select id="findUserLikeName" parameterType="java.lang.String" resultMap="userMap">
select * from users where user_name like concat('%',#{name},'%')
</select>

    不防止sql注入:

     <select id="findUserLikeName" parameterType="java.lang.String" resultMap="userMap">
select * from users where user_name like '%${name}%'
</select>
public List<User> findUserLikeName(@Param("name")String name);

  c.查询单个字段

     <select id="findPwdByName" parameterType="java.lang.String" resultType="java.lang.String">
select user_pwd from users where user_name = #{userName}
</select>
    public String findPwdByName(@Param("userName")String userName);

3.一对一(One2One)

  a.方法一:

    UserMapper.xml中

    <resultMap id="userAndInfoMap" type="User">
<id property="userId" column="user_id" />
<result property="userName" column="user_name"/>
<result property="userPwd" column="user_pwd"/>
<result property="userType" column="user_type"/>
<association property="info" resultMap="com.wode.mapper.InfoMapper.InfoMapper"></association>
</resultMap> <select id="findUserAndInfoById" parameterType="int" resultMap="userAndInfoMap">
select * from users u left join infos i on u.user_id=i.user_id where u.user_id = #{userId}
</select>

  b.方法二

    UserMapper.xml中

    <resultMap id="userAndInfoMap2" type="User">
<id property="userId" column="user_id" />
<result property="userName" column="user_name"/>
<result property="userPwd" column="user_pwd"/>
<result property="userType" column="user_type"/>
<association property="info" column="user_id" javaType="Info" select="com.wode.mapper.InfoMapper.findInfoByUserId"></association>
</resultMap> <select id="findUserAndInfoById2" parameterType="int" resultMap="userAndInfoMap2">
select * from users u where u.user_id = #{userId}
</select>

    InfoMapper.xml中

    <resultMap type="Info" id="InfoMapper">
<id property="infoId" javaType="int" column="info_id" />
<result javaType="java.lang.String" property="infoName" column="info_name" />
<result javaType="java.lang.String" property="infoEmail" column="info_email" />
</resultMap> <select id="findInfoByUserId" resultMap="InfoMapper">
select * from infos where user_id=#{userId}
</select>

4.一对多(One2Many)

  同One2One,仅在List<Info>部分将<association ...></association > 更换为<collection ...></collection>

5.多对多(Many2Many)

  a.方法一:同上

    <resultMap id="UserAndCourseMapper2" type="User">
<id property="userId" column="user_id" />
<result property="userName" column="user_name"/>
<result property="userPwd" column="user_pwd"/>
<result property="userType" column="user_type"/>
<collection property="courses" resultMap="com.wode.mapper.CourseMapper.courseMap"></collection>
</resultMap> <select id="findUserAndCourseById2" parameterType="Integer"
resultMap="UserAndCourseMapper2">
select * from users u,course c,user_course uc where u.user_id=uc.user_id and c.courseId = uc.course_id and u.user_id=#{userId}
</select>

  b.方法二:在通过userId查Course时需用到子查询(即第二个select)

    <resultMap id="UserAndCourseMapper" type="User">
<id property="userId" column="user_id" />
<result property="userName" column="user_name"/>
<result property="userPwd" column="user_pwd"/>
<result property="userType" column="user_type"/>
<collection property="courses" column="user_id" select="findCourseByUser"></collection>
</resultMap> <select id="findUserAndCourseById" parameterType="Integer"
resultMap="UserAndCourseMapper">
select * from users where user_id=#{userId}
</select> <select id="findCourseByUser" parameterType="Integer"
resultMap="com.wode.mapper.CourseMapper.courseMap">
select * from course where courseId in(select course_id from user_course where user_id=#{userId})
</select>

6.二级缓存

  a.在SqlMapConfig.xml配置

<settings>
<setting name="cacheEnabled" value="true" />
</settings>

  b.在UserMapper.xml中配置

<cache />

7.动态查询

  a.if

    <select id="searchStudent" parameterType="java.util.Map"  resultMap="scoreMap">
select * from score where 1=1
<if test="java!=null">
and java &gt;=#{java}
</if>
<if test="web!=null">
and web &gt;=#{web}
</if>
<if test="mysql!=null">
and mysql &gt;=#{mysql}
</if>
</select>

  b.choose

    <select id="searchStudent2" parameterType="java.lang.String" resultMap="scoreMap">
select * from score
<choose>
<when test="course=='java'">
where java &gt;=60
</when>
<when test="course=='web'">
where web &gt;=60
</when>
<otherwise>
where mysql &gt;=60
</otherwise>
</choose>
</select>

  c.<where>

    <select id="searchStudent" parameterType="java.util.Map"  resultMap="scoreMap">
select * from score
<where>
<if test="java!=null">
and java &gt;=#{java}
</if>
<if test="web!=null">
and web &gt;=#{web}
</if>
<if test="mysql!=null">
and mysql &gt;=#{mysql}
</if>
</where>
</select>

  d.trim

    <select id="searchStudent" parameterType="java.util.Map"  resultMap="scoreMap">
select * from score
<trim prefix="where" prefixOverrides="and|or">
<if test="java!=null">
and java &gt;=#{java}
</if>
<if test="web!=null">
and web &gt;=#{web}
</if>
<if test="mysql!=null">
and mysql &gt;=#{mysql}
</if>
</trim>
</select>

  e.set

    <update id="updateScore" parameterType="java.util.Map">
update score
<set>
<if test="java != null">
java = #{java},
</if>
<if test="web != null">
web = #{web},
</if>
<if test="mysql != null">
mysql = #{mysql}
</if>
</set>
where id = #{id}
</update>

  f.foreach

    <select id="findUser"  parameterType="java.util.Map" resultMap="userMap">
select * from users
<where>
user_id in
<foreach collection="usersId" item="userId" separator="," open="(" close=")" index="">
#{userId}
</foreach>
</where>
</select>

8.注解

  a.SqlMapConfig.xml中<mappers>只需配置

    <mappers>
<package name="com/wode/mapper" />
</mappers>

  b.普通注解

    //使用注解的方式新增用户
@Insert("insert into users values(null,#{user.userName},#{user.userPwd},#{user.userType})")
@Options(keyProperty="user.userId",useGeneratedKeys=true)
public int addUser(@Param("user")User user);
//注解的方式修改用户资料
@Update("update users set user_name=#{name} where user_id=#{id}")
public int updateUserNameById(@Param("name")String name,@Param("id")int id);
//注解的方式删除用户
@Delete("delete from users where user_id=#{id}")
public int delById(@Param("id") int id); @Select("select * from users")
/** @Results({
@Result(id=true,property="userId",column="user_id",javaType=Integer.class),
@Result(property="userName",column="user_name",javaType=String.class),
@Result(property="userPwd",column="user_pwd",javaType=String.class),
@Result(property="userType",column="user_type",javaType=Integer.class)
})
*/
@ResultMap("userMap")
public List<User> findAllUser();

  c.一对多、多对一查询

    @Select("select * from users where user_id=#{id}")
@Results({
@Result(id=true,property="userId",column="user_id",javaType=Integer.class),
@Result(property="userName",column="user_name",javaType=String.class),
@Result(property="userPwd",column="user_pwd",javaType=String.class),
@Result(property="userType",column="user_type",javaType=Integer.class),
@Result(property="info",column="user_id",many=@Many(select="com.wode.mapper.UserInfoMapper.findByUser"))
}) @Select("select * from userInfo where info_id=#{infoId}")
@Results({
@Result(id=true,column="info_id",property="infoId",javaType=Integer.class),
@Result(column="nickName",javaType=String.class,property="nickName"),
@Result(column="email",property="email",javaType=String.class),
@Result(column="user_id",property="user",one=@One(select="com.wode.mapper.UserMapper.findUserById"))
})
public UserInfo findInfoAndUser(@Param("infoId")int infoId);

9.其他

  a.添加后返回主键

    <insert id="..." parameterType="...">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
insert into ... (...) values (...)
</insert>

  b.有则修改,无则添加

    <insert id="addUserNum">
insert into user_record (user_id, user_num) values (#{userId}, 1) ON DUPLICATE key UPDATE user_num = user_num+1
</insert>

JavaEE 之 Mybatis的更多相关文章

  1. JavaEE高级-MyBatis学习笔记

    一.MyBatis简介 - MyBatis 是支持定制化 SQL.存储过程以及高级映射的优秀的持久层框架. - MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集. - My ...

  2. JavaEE MyBatis

    1.  简介 MyBatis本是apache的一个开源项目iBatis的升级版,2013年11月迁移到Github,是三层架构中持久层框架. 目前提供了Java..NET.以及Ruby三种语言实现的版 ...

  3. 【整理】JavaEE基本框架(Struts2+Spring+MyBatis三层,Struts MVC)之间的关系

    #[整理]JavaEE基本框架(Struts2+Spring+MyBatis三层,Struts MVC)之间的关系 ![关系图解](http://images.cnitblog.com/blog/84 ...

  4. JavaEE开发之SpringBoot整合MyBatis以及Thymeleaf模板引擎

    上篇博客我们聊了<JavaEE开发之SpringBoot工程的创建.运行与配置>,从上篇博客的内容我们不难看出SpringBoot的便捷.本篇博客我们继续在上篇博客的基础上来看一下Spri ...

  5. JAVAEE——SpringMVC第一天:介绍、入门程序、架构讲解、SpringMVC整合MyBatis、参数绑定、SpringMVC和Struts2的区别

    1. 学习计划   第一天 1.SpringMVC介绍 2.入门程序 3.SpringMVC架构讲解 a) 框架结构 b) 组件说明 4.SpringMVC整合MyBatis 5.参数绑定 a) Sp ...

  6. JavaEE基本框架(Struts2+Spring+MyBatis三层,Struts MVC)之间的关系

    郭晨 软件151 1531610114 [整理]JavaEE基本框架(Struts2+Spring+MyBatis三层,Struts MVC)之间的关系 visio文件下载 概述 一个JavaEE的项 ...

  7. JAVAEE——Mybatis第一天:入门、jdbc存在的问题、架构介绍、入门程序、Dao的开发方法、接口的动态代理方式、SqlMapConfig.xml文件说明

    1. 学习计划 第一天: 1.Mybatis的介绍 2.Mybatis的入门 a) 使用jdbc操作数据库存在的问题 b) Mybatis的架构 c) Mybatis的入门程序 3.Dao的开发方法 ...

  8. JAVAEE——Mybatis第二天:输入和输出映射、动态sql、关联查询、Mybatis整合spring、Mybatis逆向工程

    1. 学习计划 1.输入映射和输出映射 a) 输入参数映射 b) 返回值映射 2.动态sql a) If标签 b) Where标签 c) Sql片段 d) Foreach标签 3.关联查询 a) 一对 ...

  9. 在JavaEE中使用Mybatis框架

    MyBatis 使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java 对象)映射成数据库中的记录.每个MyB ...

随机推荐

  1. 数字、ip转换python实现

    # 数字 ==> ip # 数字范围[0, 255^4] >>> num2ip = lambda x: '.'.join([str(x/(256**i)%256) for i ...

  2. npm无反应的问题&npm常用命令

    RT: windows安装完nodejs后做了相关环境变量配置后,cmd输入npm命令无反应,就光标一直闪,百度了半天终于找到解决办法 解决方法:C:\Users\Administrator(或你的账 ...

  3. 《剑指offer》 二进制中1的个数

    本题来自<剑指offer> 二进制中1的个数 题目: 输入一个整数,输出该数二进制表示中1的个数.其中负数用补码表示. 思路: 两种思路: 第一种:对n进行左移,检测最后一位是否为1,但考 ...

  4. HTML&javaSkcript&CSS&jQuery&ajax(五)

    一.Framset标签定义了每个框架中的HTML文档, 1. <framset cols="25%,75%"> <frame src="frame_a. ...

  5. linux安装python3+selenium

    安装笔记 当前安装使用centos7 安装python3 1.下载 [admin@ ~] wget https://www.python.org/ftp/python/3.6.0/Python-3.6 ...

  6. SVN项目迁移到Git上(并带有完整的提交记录)

    公司需求:早期的一些项目使用的是SVN,现在想要更换为Git,需要代码迁移并且能在Git上看到之前在SVN中的项目的提交记录,公司没有使用gitlab,代码都push在公司的服务器上,用的是Torto ...

  7. Mysql 5.7 CentOS 7 安装MHA

    Table of Contents 1. MHA简介 1.1. 功能 1.2. MHA切换逻辑 1.3. 工具 2. 环境 2.1. 软件 2.2. 环境 3. Mysql 主从复制 3.1. Mys ...

  8. python 利用split读取文本文件中每一行的数字并保存至相应文件夹

    import re from numpy import * def getStr(file_path,file_path1): fp = open(file_path, 'r') op = open( ...

  9. java实现满天星swing&awt

    一起有两个类 1.MyStar.java package day02; import java.awt.Color; import javax.swing.JFrame;import javax.sw ...

  10. 混合编译.c/.cpp与.cu文件

    混合编译.c/.cpp与.cu文件 项目中用到cuda编程,写了kernel函数,需要nvcc编译器来编译..c/.cpp的文件,假定用gcc编译. 如何混合编译它们,整体思路是:.cu文件编译出的东 ...