JavaWeb - Mybatis - 基础操作

删除@Delete

接口方法:

@Mapper
public interface EmpMapper {
//@Delete("delete from emp where id = 17")
//public void delete();
//以上delete操作的SQL语句中的id值写成固定的17,就表示只能删除id=17的用户数据
//SQL语句中的id值不能写成固定数值,需要变为动态的数值
//解决方案:在delete方法中添加一个参数(用户id),将方法中的参数,传给SQL语句
/**
* 根据id删除数据
* @param id 用户id
*/
    @Delete("delete from emp where id = #{id}")//使用#{key}方式获取方法中的参数值
    public void delete(Integer id);
}
@Delete 注解:用于编写 delete 操作的 SQL 语句
如果 mapper 接口方法形参只有一个普通类型的参数, #{…} 里面的属性名可以随便写,如: #
{id} #{value} 。但是建议保持名字一致。
在单元测试类中通过 @Autowired 注解注入 EmpMapper 类型对象
@SpringBootTest
class SpringbootMybatisCrudApplicationTests {
    @Autowired //从Spring的IOC容器中,获取类型是EmpMapper的对象并注入
    private EmpMapper empMapper;
    @Test
    public void testDel(){
    //调用删除方法
    empMapper.delete(16);
    }
}

日志输入

Mybatis 当中我们可以借助日志,查看到 sql语句的执行、执行传递的参数以及执行结果。具体操作如下:
1. 打开 application.properties 文件
2. 开启 mybatis 的日志,并指定输出到控制台
#指定mybatis输出日志的位置, 输出控制台
mybatis.configuration.log-
impl=org.apache.ibatis.logging.stdout.StdOutImpl

预编译SQL

预编译 SQL 有两个优势:
1. 性能更高:  预编译 SQL ,编译一次之后会将编译后的 SQL 语句缓存起来,后面再次执行这条语句
时,不会再次编译。(只是输入的参数不同)
2. 更安全 ( 防止 SQL 注入):  将敏感字进行转义,保障 SQL 的安全性。

SQL注入

是通过操作输入的数据来修改事先定义好的 SQL 语句,以达到执行代码对服务器进行攻击的方法。
由于没有对用户输入进行充分检查,而 SQL 又是拼接而成,在用户输入参数时,在参数中添加一些
SQL 关键字,达到改变 SQL 运行结果的目的,也可以完成恶意攻击。

参数占位符

Mybatis 中提供的参数占位符有两种: ${...} #{...}

#{...}

执行 SQL 时,会将 #{…} 替换为 ? ,生成预编译 SQL ,会自动设置参数值
使用时机:参数传递,都使用 #{…}

${...}

拼接 SQL 。直接将参数拼接在 SQL 语句中,存在 SQL 注入问题
使用时机:如果对表名、列表进行动态设置时使用
注意事项:在项目开发中,建议使用 #{...} ,生成预编译 SQL ,防止 SQL 注入安全。

新增@Insert

接口方法:

@Mapper
public interface EmpMapper {
    @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);
}
#{...} 里面写的名称是对象的属性名 (驼峰命名法)

新增(主键返回)

在数据添加成功后,需要获取插入数据库数据的主键。
默认情况下,执行插入操作时,是不会主键值返回的。如果我们想要拿到主键值,需要在 Mapper
接口中的方法上添加一个 Options 注解,并在注解中指定属性 useGeneratedKeys=true和 keyProperty=" 实体类属性名 "
@Mapper
public interface EmpMapper {
    //会自动将生成的主键值,赋值给emp对象的id属性
    @Options(useGeneratedKeys = true,keyProperty = "id")
    @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);
}

更新@Update

接口方法

@Mapper
public interface EmpMapper {
/**
* 根据id修改员工信息
* @param emp
*/
    @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);
}

查询@select

接口方法

@Mapper
public interface EmpMapper {
    @Select("select id, username, password, name, gender, image, job,
entrydate, dept_id, create_time, update_time from emp where id=#{id}")
    public Emp getById(Integer id);
}

数据封装

  • 实体类属性名和数据库表查询返回的字段名一致,mybatis会自动封装。
  • 如果实体类属性名和数据库表查询返回的字段名不一致,不能自动封装。
解决方案:
  • 1. 起别名
  • 2. 结果映射
  • 3. 开启驼峰命名

起别名

SQL 语句中,对不一样的列名起别名,别名和实体类属性名一样
@Select("select id, username, password, name, gender, image, job,
entrydate, " +
"dept_id AS deptId, create_time AS createTime, update_time AS
updateTime " +
"from emp " +
"where id=#{id}")
public Emp getById(Integer id);

手动结果映射

通过 @Results @Result 进行手动结果映射
@Results({@Result(column = "dept_id", property = "deptId"),
@Result(column = "create_time", property = "createTime"),
@Result(column = "update_time", property = "updateTime")})
@Select("select id, username, password, name, gender, image, job,
entrydate, dept_id, create_time, update_time from emp where id=#{id}")
public Emp getById(Integer id);

开启驼峰命名

如果字段名与属性名符合驼峰命名规则, mybatis 会自动通过驼峰命名规则映射
# application.properties 中添加:
mybatis.configuration.map-underscore-to-camel-case = true
要使用驼峰命名前提是 实体类的属性数据库表中的字段名严格遵守驼峰命名。

查询(条件查询)

SQL:
select id, username, password , name, gender, image, job, entrydate,
dept_id, create_time, update_time
from emp
where name like '% %'
and gender = 1
and entrydate between '2010-01-01' and '2020-01-01 '
order by update_time desc ;

接口方法一:

@Mapper
public interface EmpMapper {
    @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);
}

方式二(解决SQL注入风险)

使用MySQL提供的字符串拼接函数:concat('%' , '关键字' , '%')

@Mapper
public interface EmpMapper {
    @Select("select * from emp " +
        "where name like concat('%',#{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);
}

  • 17
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java EE 项目的目录结构可以根据具体的需求进行灵活设计,但一般情况下,推荐使用以下的标准目录结构: ``` project ├── src │ ├── main │ │ ├── java │ │ │ └── com │ │ │ └── example │ │ │ ├── controller │ │ │ ├── dao │ │ │ ├── entity │ │ │ ├── service │ │ │ └── util │ │ ├── resources │ │ │ ├── mapper │ │ │ └── db.properties │ │ └── webapp │ │ ├── WEB-INF │ │ │ ├── classes │ │ │ ├── lib │ │ │ └── web.xml │ │ ├── css │ │ ├── js │ │ ├── images │ │ └── index.jsp │ └── test │ ├── java │ └── resources ├── target ├── pom.xml └── README.md ``` 其中,各个目录的作用如下: - `src/main/java`:存放项目的 Java 源代码,按照包名分层,一般包括 `controller`、`dao`、`entity`、`service` 和 `util` 等包; - `src/main/resources`:存放项目的配置文件和资源文件,一般包括数据库连接配置文件 `db.properties`、MyBatis 的 mapper 文件等; - `src/main/webapp`:存放 Web 应用的 Web 资源,包括 JSP 页面、CSS 样式表、JavaScript 脚本等; - `src/test/java`:存放项目的测试代码; - `src/test/resources`:存放测试代码所需要的资源文件; - `target`:存放编译后的 .class 文件、打包后的 .war 文件等; - `pom.xml`:Maven 项目管理工具的配置文件; - `README.md`:项目说明文件。 以上是一种常见的 Java EE 项目目录结构,但并不是唯一的标准。在实际开发中,可以根据项目的具体需求进行合理的调整和修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值