当前位置:   article > 正文

Mysql与MyBatis_mysql和mybatis

mysql和mybatis

1  Sql语句 增删改查

1.1 建表

  1. -- cmd展示数据库
  2. show databases ;
  3. -- cmd登录数据库
  4. mysql localhost -u root -p
  5. -- auto_increment 自动增长,每添加一个表项id自动增1
  6. -- char定长字符串 0-255,不足十个字符按十个字符算, varchar变长字符串:有几个字符给几个的空间
  7. -- varchar(20)最多20个字符的空间,char11)直接给11个字符空间
  8. create table tbuser(
  9. id int primary key auto_increment comment 'ID 唯一标识',
  10. username varchar(20) not null unique comment '用户名',
  11. name varchar(10) not null comment '姓名',
  12. age int comment '年龄',
  13. gender char(1) default '男' comment '性别'
  14. )comment '用户表';

 

 图形化界面创建:

  1. price decimal(8.2)//最多8位,2位小数
  2. image varchar(300) 图像存储的是路径
  1. # 查看指定表结构
  2. desc tbuser;

 

  1. # 查看建表语句
  2. show create table tbuser;

1.2 修改删除

  1. alter table tbuser add height varchar(11) comment '身高';
  2. alter table tbuser modify height varchar(13) comment '身高';
  3. # 修改height名字为height1
  4. alter table tbuser change height height1 varchar(13) comment '身高';
  5. alter table tbuser drop column height1;
  6. rename table tbuser to tb_user;
  7. # 删除表
  8. drop table if exists tbuser;
  1. insert into tb_user (id,username,name) values (2,"haha","haha"),(3,"haha2","haha2");
  2. # 全部字段添加数据
  3. insert into tb_user values xxx
update  tb_user set username="bus" where id=1;
  1. delete from tb_user where id=1;
  2. #删除表中所有数据
  3. delete from tb_user;

1.3 查询

1.3.1 基本查询 

  1. # distinct表示不要重复
  2. select distinct job from tb_emp;
  3. # 查询并起别名
  4. select name as 姓名 from tb_emp;

 1.3.2 条件查询

  1. select * from tb_emp where id=5;
  2. select * from tb_emp where id is null;
  3. # 查询id不等于5的信息
  4. select * from tb_emp where id !=5;
  5. # 与上一个同义
  6. select * from tb_emp where id <>5;
  7. select * from tb_emp where id >5 and id<10;
  8. select * from tb_emp where id between 5 and 10;
  9. # id在5-10范围而且要gender=2
  10. select * from tb_emp where id between 5 and 10 and gender=2;
  11. select * from tb_emp where id =5 or id=6;
  12. # 与上一个同义
  13. select * from tb_emp where id in (5,6);
  14. # _表示一个字符
  15. select * from tb_emp where name like '__';
  16. # %表示任意字符
  17. select * from tb_emp where name like '张%';

1.3.3 聚合函数 

  1. # 统计,不对null值运算
  2. select count(id) from tb_emp;
  3. select count(*) from tb_emp;
  4. select min(entrydate) from tb_emp;
  5. select max(entrydate) from tb_emp;
  6. select avg(entrydate) from tb_emp;
  7. select sum(entrydate) from tb_emp;

1.3.4 分组查询

  1. # 根据性别分组,统计各自数量
  2. select gender,count(*) from tb_emp group by gender;
  3. # 查询entrydate<='2015-1-1',并职位分组,获取员工数量>=2的职位
  4. # where是分组之前过滤,之后不能使用聚合函数,having是分组之后的过滤
  5. select job,count(*) from tb_emp where entrydate<='2015-1-1' group by job having count(*)>=2;

1.3.5 排序查询

  1. # 排序,asc升序默认,desc默认,此句asc在前
  2. select * from tb_emp order by entrydate asc,id desc ;

1.3.6 分页查询

起始索引0可以省略

2 多表设计

外键约束

关系:一对一、一对多、多对多;多对多关系,需要一张中间表;一对多在多的一方添加一个外键

外键约束分为:物理外键(容易死锁)、逻辑外键(service层)

要把外键表相关信息删除之后,才能删除关联信息

  1. create table class(id int primary key auto_increment);
  2. //class_id是外键字段名
  3. create table student(id int primary key auto_increment,class_id int,constraint foreign key(class_id) references class(id));
  1. create table teacher(id int primary key);
  2. create table student (id int primary key);
  3. create table teacher_student(teacher_id int,student_id int,constraint foreign key(teacher_id) references teacher(id),constraint foreign key(student_id) references student(id));

3 多表查询

笛卡尔积:两个集合所有的组合情况; 需要设置条件消除无效笛卡尔积,比如where x.id=y.id

3.1 内连接

集合A,B交集的数据

  1. -- 查询员工的姓名,部门(内连接实现)
  2. select tb_emp.name ,tb_dept.name from tb_dept,tb_emp where tb_emp.dept_id=tb_dept.id;
  3. -- 起别名
  4. select e1.name ,b.name from tb_dept e1 ,tb_emp b where b.dept_id=e1.id;
  5. # 显式内连接
  6. select tb_emp.name ,tb_dept.name from tb_emp inner join tb_dept on tb_emp.dept_id=tb_dept.id;

3.2 外连接

查询集合A或B的所有

  1. # 左外连接
  2. select tb_emp.name ,tb_dept.name from tb_emp left join tb_dept on tb_emp.dept_id=tb_dept.id;
  3. # 右外连接
  4. select tb_emp.name ,tb_dept.name from tb_emp right join tb_dept on tb_emp.dept_id=tb_dept.id;

 3.3 子查询

嵌套select语句

1.标量子查询

返回单个值

select * from tb_emp where dept_id=(select id from tb_dept where name='张三丰');

 2.列子查询

返回一列

  1. # 查询教研部与咨询部所有员工信息
  2. select * from tb_emp where dept_id in (select id from tb_dept where name='教研部' or name='咨询部')

3.行子查询 

返回一行

  1. # 查询与金庸的出生日期以及职位都相同的信息
  2. select * from tb_emp where (entrydate,job) =(select entrydate,job from tb_emp where name='金庸')

4.列子查询

返回多行多列

  1. # 查询入职日期为2000-01-01的员工信息以及部门名称
  2. select * from (select * from tb_emp where entrydate>'2000-01-01') e ,tb_dept d where e.dept_id=d.id

4 事务

  1. # 事务:一组操作的集合,要么同时成功,要么同时失败
  2. # 开启事务
  3. start transaction ;
  4. # 删除部门
  5. delete from tb_dept where id=3;
  6. #删除员工
  7. delete from tb_emp where dept_id=3;
  8. # 提交事务,如果上面两行都成功使用
  9. commit ;
  10. # 回滚事务,只有上面两行有一个失败就使用,相对于撤销原操作
  11. rollback ;

5 索引

默认底层结构:B+树

IBD文件:存放数据库的数据与索引

  1. create index inname on tb_emp(name);
  2. show index from tb_emp;
  3. # 删除索引
  4. drop index inname on tb_emp;

6 MyBatis

6.1 配置

MyBatis是dao层(持久层)框架

数据库连接池:容器,管理数据库连接

接口:DataSource

产品:Druid、Hikari

  1. <!-- druyid连接池-->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>druid-spring-boot-starter</artifactId>
  5. <version>1.2.8</version>
  6. </dependency>

lombok :注解提供相应方法

  1. <dependency>
  2. <groupId>org.projectlombok</groupId>
  3. <artifactId>lombok</artifactId>
  4. </dependency>
  1. //@Getter
  2. //@Setter
  3. //@ToString
  4. //@EqualsAndHashCode
  5. @Data//相当于以上四个
  6. @NoArgsConstructor//无参构造
  7. @AllArgsConstructor//全参构造
  8. public class user {}
  1. #配置mybatis日志,指定输出到控制台
  2. mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

6.2 删除

UserMapper接口

  1. @Mapper
  2. public interface UserMapper {
  3. // #{id}表示占位符
  4. //如果有返回值,成功返回值为1
  5. @Delete("delete from emp where id=#{id}")
  6. public void list(Integer id);
  7. }
MybatisApplicationTests测试启动类
  1. @SpringBootTest
  2. class MybatisApplicationTests {
  3. @Autowired
  4. private UserMapper userMapper;
  5. @Test
  6. public void testUser(){
  7. userMapper.list(10);
  8. }
  9. }

成功!

 '#'表示预编译Sql:性能更高、更安全

性能更高:将编译后的结果缓存起来 

 安全原因:防止SQL注入

SQL注入是web应用程序在接收相关数据参数时未做好过滤,将其直接带入到数据库中查询,导致攻击者可以拼接执行构造的SQL语句

  1. //$是拼接,后台直接是delete from emp where id=id
  2. @Delete("delete from emp where id=${id}")
  3. public void list(Integer id);

6.3 插入

UserMapper接口

  1. @Mapper
  2. public interface UserMapper {
  3. //获取返回的主键
  4. @Options(keyProperty = "id",useGeneratedKeys = true)
  5. //更新是@Update
  6. @Insert("insert into dept (id, name,create_name,update_name) values (#{id},#{name},#{create_name},#{update_name})")
  7. public void insert(user u);
  8. }

 MybatisApplicationTests

  1. @Test
  2. public void testUser(){
  3. user u=new user();
  4. u.setAge((short) 18);
  5. u.setGender((short) 1);
  6. u.setName("123");
  7. u.setPhone(String.valueOf(12321));
  8. u.setId(12);
  9. userMapper.insert(u);
  10. System.out.println(u.getId());
  11. }
  12. }

6.3 查询

 UserMapper接口

  1. @Select("select * from dept where id=#{id}")
  2. public user select(Integer id);

  MybatisApplicationTests

  1. @SpringBootTest
  2. class MybatisApplicationTests {
  3. @Autowired
  4. private UserMapper userMapper;
  5. @Test
  6. public void testUser(){
  7. user u=userMapper.select(2);
  8. System.out.println(u);
  9. }
  10. }

 null原因:数据封装

实体类属性名与数据库查询返回的字段一致,mybatis会自动封装,不一致则不会

解决方法一:起别名

  1. @Select("select id, name, create_time createName, update_time updateName from dept where id=#{id}")
  2. public user select(Integer id);

解决方法二:@Results

  1. @Results({
  2. @Result(column="create_time",property="createName"),
  3. @Result(column="update_time",property="updateName"),
  4. })
  5. @Select("select * from dept where id=#{id}")
  6. public user select(Integer id);
  7. }

解决方法三:

application.properties

  1. #开启mybatis驼峰命名自动映射开关
  2. mybatis.configuration.map-underscore-to-camel-case=true

6.4 XML

同包同名:XML映射文件名与Mapper接口名称一致

 xml的sql语句的id要与mapper接口方法名、返回类型一致

  1. //namespace是接口copy->copy reference
  2. <mapper namespace="com.tencent.mybatis.mapper.UserMapper">
  3. </mapper>

xml要导入的文件: 

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

 UserMapper接口

动态SQL-if

  1. <mapper namespace="com.tencent.mybatis.mapper.UserMapper">
  2. <select id="select" resultType="com.tencent.mybatis.polo.user">
  3. select * from dept
  4. -- 如果if不成立,where不会创建,还会自动除去条件前面的and或者or
  5. -- 如果where改为set,那么set会自动除去条件后面的‘,’
  6. <where>
  7. <if test="name!=null">
  8. name like concat('%',#{name},'%');
  9. </if>
  10. <if test="id!=null">
  11. -- 没有<where>标签,name不成立id成立会报错
  12. and id =#{id}
  13. </if>
  14. </where>
  15. </select>
  16. </mapper>

删除

 UserMapper接口

  1. @Mapper
  2. public interface UserMapper {
  3. public void deleteId(List<Integer> ids);
  4. }
接口的ids要与MybatisApplicationTests的ids对应,不然报错
  1. <mapper namespace="com.tencent.mybatis.mapper.UserMapper">
  2. <!-- collection遍历的集合,item是遍历出的元素,separator分隔符-->
  3. <delete id="deleteId">
  4. delete from dept where id in
  5. <foreach collection="ids" item="id" separator="," open="(" close=")">
  6. #{id}
  7. </foreach>
  8. </delete>
  9. </mapper>
MybatisApplicationTests
  1. @SpringBootTest
  2. class MybatisApplicationTests {
  3. @Autowired
  4. private UserMapper userMapper;
  5. @Test
  6. public void testUser(){
  7. List<Integer> ids= Arrays.asList(1,2,3);
  8. userMapper.deleteId(ids);
  9. }
  10. }

6.5 解决Could not autowire. No beans of ‘UserMapper‘ type found问题

文件夹放入与启动项文件同级 

  成功!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/858262
推荐阅读
相关标签
  

闽ICP备14008679号