目录
一.mybatis的入门
1.dao数据访问层,又叫持久层,与数据库密切相关
2.mybatis--在dao持久层当中操作数据库的 底层JDBC操作数据库非常繁琐
1.快速入门
driver--数据库驱动
localhost:指的是本机 3306数据库服务器端口号
注解autowired--完成依赖注入
自动加载整个springboot的环境,并且创建spring的ioc容器
2.配置sql提示
要想写sql语句有提示,就要做如上操作
3.JDBC介绍
jdbc---是一套规范,仅仅是提供面向接口,并没有提供具体的实现,实现:各个数据库厂商提供 mysql oracle
各个厂商提供的jdbc规范(“数据库的驱动”)
jdbc有弊端--硬编码 繁琐 资源浪费 性能降低
数据库连接池统一管理和分配这些连接 connection对象
4.数据库连接池
1.类似于线程池--也是一个容器 存储数据库连接对象--connection
每次连接都要创建连接对象 执行sql语句 连接对象关闭--释放资源---这样比较浪费资源
在数据库连接池当中初始化一定数量的连接对象
客户端执行sql语句->在数据库连接池当中获取连接->获取到连接之后执行sql语句->最后将连接归还给数据库连接池(做到连接的复用,而不是每次都创建一个新的连接)
如何去连接数据库连接池?
所有的数据库连接池都有DataSource--官方提供的标准接口
切换连接池:引入德鲁伊数据库连接池的依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.8</version>
</dependency>
shift双击--打开源码
5.lombok工具包介绍
二.mybatis基础操作
1.删除
2.删除(预编译删除)
?---参数占位符
运行当前jar包
!!!!!!!!面试题
3.新增
@Insert("insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time)" + "values (#{username},#{name},#{gender},#{image},#{job},#{entrydate},#{deptId},#{createTime},#{updateTime})") public void insert(Emp emp);
4.新增(主键返回)
如何拿到生成的主键值?
获取返回主键
5.更新
@Update("update emp set username=#{username},name=#{name}, gender=#{gender}, image=#{image}, job=#{job}, entrydate=#{entrydate}," + " dept_id=#{deptId}, update_time=#{updateTime} where id=#{id}") public void update(Emp emp);
@Test public void testUpdate(){ Emp emp=new Emp(); emp.setId(17); emp.setUsername("Tom1111"); emp.setName("汤姆111"); emp.setImage("1.jpg"); emp.setGender((short)1); emp.setJob((short)1); emp.setEntrydate(LocalDate.of(2000,1,1)); emp.setUpdateTime(LocalDateTime.now()); emp.setDeptId(1); empMapper.update(emp); }
6.查询(根据id查询)
@Select("select * from emp where id=#{id} ") public Emp getById(Integer id);
@Test public void TestgetById(){ Emp emp = empMapper.getById(20); System.out.println(emp); }
起别名----对应成功
7.查询(条件查询)
@Select("select * from emp where name like '%${name}%' and gender=#{gender} and entrydate" + " between #{begin} and #{end} order by update_time desc ") public List<Emp> list(String name, Short gender, LocalDate begin,LocalDate end);
@Test public void testList(){ List<Emp> empList = empMapper.list("张", (short) 1, LocalDate.of(2010, 1, 1), LocalDate.of(2020, 1, 1)); System.out.println(empList); }
使用$符号不安全,存在sql注入问题
解决方法: