mybatis第二篇

1.${}和#{}的区别

  • 1.#在传参的时候,会自动拼接单引号;$不能拼接单引号;
  • 2.$传参时,一般不支持jdbcType指定类型的写法;#则可以;如:

    ​ #{name,jdbcType=VARCHAR}

  • 3.$一般用于在sql中拼接表名,结果排序,模糊查询等操作;其他正常参数传递一般使用

  • 4.因为${}使用后不会自动拼接单引号,所以可能还会导致sql攻击

select * from user where username=${username} and password=${username}

当输入值为" ttt' or '22'='22' 时,sql就被替换为

select * from user where username='ttt' or '22'='22' and password='ttt'  or '22'='22'

在影射文件中结果类型的处理

	<resultMap type="cn.sz.gl.pojo.DeptPlus" id="deptinfo">
<result column="deptno" property="deptno"/>
<result column="dname" property="dname"/>
<result column="loc" property="loc"/>
<!--第一种,通过association 标签实现连表查询
<association column="deptno" property="dept"
select="cn.sz.gl.dao.DeptDao.findById"></association>-->
<!--第二种 连表查询,多对一模式
<collection property="emplist">
<id column="empno" property="empno"/>
<result column="ename" property="ename"/>
<result column="job" property="job"/>
<result column="hiredate" property="hiredate"/>
<result column="sal" property="sal"/>
<result column="comm" property="comm"/>
</collection>
-->
<!-- 方案3 联表查询下,一对多-->
<collection property="emplist" column="deptno"
ofType="cn.sz.gl.pojo.Emp" javaType="java.util.List"
select="cn.sz.gl.pojo.Emp.findByDeptno"></collection>
</resultMap>
<!--根据部门编号查看部门所有员工 1对多-->
<select id="findByIdlist" resultMap="deptinfo" parameterType="java.lang.String">
select deptno, dname, loc from dept where deptno=#{deptno}
</select>

定义接口方法

    /**
* 根据部门编号查看部门所有员工
* @param deptno Integer
* @return DeptPlus 部门和员工的组合
*/
public DeptPlus findByIdlist(Integer deptno);

测试

@Test
public void testFindByIdlist() { SqlSession sqlsession
=MySqlSessionFactory.getMySqlSession();
//通过工厂调用getMapper获取接口实例
DeptDao dao = sqlsession.getMapper(DeptDao.class); System.out.println(dao.findByIdlist(10));
MySqlSessionFactory.closeSqlSession();
}

2.在插入数据时获取主键

<!-- 增加 -->
<insert id="insert" parameterType="cn.sz.gl.pojo.Users" >
insert into users(id,name,password)
values(users_seq.nextval, #{name,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR})
</insert>

这里提供两种方案

  1. 在oracle中,因为自身使用序列自增策略

    我们在insert语句中加入selectKey 这样就会把主键,映射到实体类的主键上

    <insert id="insert" parameterType="cn.sz.gl.pojo.Users" >
    <selectKey order="AFTER" keyProperty="empno" resultType=" java.lang.Integer">
    select emp_seq.currval from daul
    </selectKey>
    insert into users(id,name,password)
    values(users_seq.nextval, #{name,jdbcType=VARCHAR},
    #{password,jdbcType=VARCHAR})
    </insert>
  2. 对于mysql和mssql的主键自增策略

    先设置启用主键自增策略,将属性useGeneratedKeys="true,指定返回到实体类的属性名,设置对应列名keyColumn="empno",后就会映射到实体类之中

    	<!-- 增加 -->
    <insert id="insert" parameterType="cn.sz.gl.pojo.Emp" useGeneratedKeys="true" keyColumn="empno" keyProperty="empno" >
    insert into emp(empno, ename, job, mgr, hiredate, sal, comm, deptno)
    values(emp_seq.nextval, #{ename,jdbcType=VARCHAR}, #{job,jdbcType=VARCHAR}, #{mgr,jdbcType=NUMERIC}, #{hiredate,jdbcType=DATE}, #{sal,jdbcType=NUMERIC}, #{comm,jdbcType=NUMERIC}, #{deptno,jdbcType=NUMERIC})
    </insert>

3.ThreadLocal本地线程的使用

现编写工具类MySqlSessionFactory.java

public class MySqlSessionFactory {
private static final String RESOURCE = "mybatis_config.xml";
private static SqlSessionFactoryBuilder builder = null;
private static SqlSessionFactory factory = null;
private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
static{
try {
InputStream is = Resources.getResourceAsStream(RESOURCE);
builder = new SqlSessionFactoryBuilder();
factory = builder.build(is);
} catch (IOException e) {
System.out.println("加载配置文件.....");
}
} public static SqlSession getMySqlSession() {
SqlSession sqlSession = threadLocal.get();
if(sqlSession==null) {
sqlSession = factory.openSession();
threadLocal.set(sqlSession);
}
return sqlSession;
}
public static void closeSqlSession() {
SqlSession sqlSession = threadLocal.get();
if(sqlSession!=null) {
sqlSession.close();
}
threadLocal.set(null);
} }

使用在service中

public class UsersServiceImpl implements UsersService {
private static SqlSession sqlsession
=MySqlSessionFactory.getMySqlSession();
private UsersDao dao = null; /**
* 查询全部
* @return
*/
public List<Users> findAll(){
try {
dao=sqlsession.getMapper(UsersDao.class);
return dao.findAll();
} catch (Exception e) {
System.out.println("findAll'查询列表失败!"); }
return Collections.EMPTY_LIST;
}
}

测试

public class UsersServiceImplTest {
private UsersService service=null;
@Before
public void init() {
service=new UsersServiceImpl();
} @Test
public void testFindAll() { service.findAll().forEach(System.out::println);
}
}

Mybatis需要注意的细节的更多相关文章

  1. Mybatis学习的一些细节

    一.mybatis 基本配置 最近几天一直在学习mybatis,看了一些源码,本文讲述mybatis的一些基本配置和基本的用法和注意到一些细节.个人时间和精力有限,本文属于流水账类型,不成体系,算是自 ...

  2. mybatis不可忽略的细节

    自我总结,欢迎拍砖! 目的:在需要返回int,long等基础类型数据的情况下,尽量在mybatis的Mapper中用基础类型的包装类. 原因:当查询的字段为空值时,mybatis会返回null,用基础 ...

  3. mybatis使用注意的细节

    1.mybatis对sql执行后会对结果进行封装,如果没有返回任何记录,只是封装后的对象没有值,而对象并不为空null: (这个问题疏忽坑了两次,在对返回数组结果进行判断的时候,我用的if(Array ...

  4. mybatis的一些小细节

    Mybatis要解决的问题: 1. 将sql语句硬编码到java代码中,如果修改sql语句,需要修改java代码,重新编译.系统可维护性不高. 设想如何解决? 能否将sql单独配置在配置文件中. 2. ...

  5. IntelliJ IDEA 2017版 spring-boot2.0.4+mybatis 自动部署的细节问题

    一.加载pom依赖包 <!--spring-boot开发热部署--> <dependency> <groupId>org.springframework.boot& ...

  6. MyBatis中的特殊符号[20160713]

    今天中午回到工位已经是12:20多了,没有时间睡觉了,本想着还能提前开始,结果看了点新闻之后,又是12:40了,所以新闻坚决不能看,执行力. 今天主要记录一下MyBatis中的特殊符号的问题,这个问题 ...

  7. 6、SpringBoot+Mybatis整合------参数传递

    开发工具:STS 代码下载链接:https://github.com/theIndoorTrain/SpringBoot_Mybatis/tree/7892801d804d2060774f3720f8 ...

  8. 图解Mybatis框架原理及使用

    1.前言 努力学习完ssm框架之后,终于也成功的把三大框架的使用以及配置文件细节忘得一干二净.为了努力捡起来以及方便今后的复习,决定写一篇博客记录一下. 本博客的所有分析都是在持久层接口以及接口中的方 ...

  9. mybatis框架的第二天

    一.mybatis的基础crud的操作 先在接口中,写对应的方法名称,返回类型,访问符. 之后在映射配置文件中,写具体的实现 二.mybati中crud的细节 1.模糊查询 这是接口中 这是xml中 ...

随机推荐

  1. 【前端知识体系-JS相关】JS基础知识总结

    1 变量类型和计算 1.1 值类型和引用类型的区别? 值类型:每个变量都会存储各自的值.不会相互影响 引用类型:不同变量的指针执行了同一个对象(数组,对象,函数) 1.2 typeof可以及检测的数据 ...

  2. Python 操作Gitlab-API 实现批量的合并分支

    1.需求:每次大批量上线完成后,都会进行将hotfix合并到Master,合并到test/uat等等重复操作(上线发布后自动合并master已完成). 2.现实:在完成发布后自动合并master后,可 ...

  3. 从壹开始 [ Ids4实战 ] 之六 ║ 统一角色管理(上)

    前言 书接上文,咱们在上周,通过一篇<思考> 性质的文章,和很多小伙伴简单的讨论了下,如何统一同步处理角色的问题,众说纷纭,这个我一会儿会在下文详细说到,而且我最终也定稿方案了.所以今天咱 ...

  4. [折腾笔记] 洛谷P1149-火柴棒等式 AC记

    原题链接: https://www.luogu.org/problem/P1149 题面简述: 给你n根火柴棍,你可以拼出多少个形如"A+B=C""A+B=C" ...

  5. 2019牛客暑期多校训练营(第九场) E All men are brothers

    传送门 知识点:并查集+组合数学 并查集合并操作可以理解为使得两个集合的人互相成为朋友,也就是两个集合并在了一起,答案是要求从所有人中挑出四个互相不是朋友的四个人,比较基础的组合数学知识,但因为每个集 ...

  6. centos7 安装wps

    # cat /etc/redhat-release CentOS Linux release 7.6.1810 (Core) # cat /proc/version Linux version 3.1 ...

  7. 2019-2020-1 20199304《Linux内核原理与分析》第四周作业

    第三章 MenuOs的构造 一.前情回顾 计算机的三大法宝: -存储程序计算机 -函数调用堆栈 -中断 操作系统的两把宝剑: -中断上下文的切换(保存现场和恢复现场) -进程上下文的切换 二.3.1 ...

  8. netty的调优-及-献上写过注释的源码工程

    Netty能干什么? Http服务器 使用Netty可以编写一个 Http服务器, 就像tomcat那样,能接受用户发送的http请求, , 只不过没有实现Servelt规范, 但是它也能解析携带的参 ...

  9. Composer安装和使用

    Composer 是 PHP 的一个依赖管理工具.它允许你申明项目所依赖的代码库,它会在你的项目中为你安装他们.Composer 不是一个包管理器.是的,它涉及 "packages" ...

  10. 浏览器/外网访问docker container中的hadoop

    假设你制作了个docker的 hadoop的镜像,镜像名叫 hd_image,如果想在外网的浏览器中访问hadoop的50070和8088端口,则在启动镜像hd_image时, 脚本如下: docke ...