Spring boot注解开发mybatis

数据库连接配置,在resources目录下的application.propertis文件配置:

#数据库连接配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db1
spring.datasource.username=root
spring.datasource.password=qw123456
#指定mybatis日志的输出位置,输出控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

在sql接口使用注解@Mapper。作用就是将接口生成一个动态代理类。这个注解就是用来映射mapper.xml文件的。

如果mapper接口方法形参只有一个普通类型的参数,#{...}里面的属性名可以随便写。

参数占位符:

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

                预编译sql:性能更高,更加安全(防止sql注入)

        ${...}:拼接sql。直接将参数拼接在sql语句中,存在sql注入问题。使用时机:如果对表名、列表进行动态设置时使用。

数据封装:

        mybatis要求列名与属性名一直才能自动封装数据,若列名与属性名不一致,则需要手动映射。

       1、起别名:在sql语句中,对不一样的列名起别名,别名和实体类属性名一样。

@Select("select id, username, password, name, gender, image, job, entrydate," +
            " dept_id deptId, create_time createTime, update_time updateTime " +
            "from emp where id=#{id}")
public Emp selectById(int id);

        2、手动结果映射:通过@Results及@Result进行手动结果映射。

@Select("select * from emp where id=#{id}")
@Results({
        @Result(column="dept_id",property="deptId"),
        @Result(column = "create_time",property="createTime"),
        @Result(column = "update_time",property="updateTime")
})
public Emp selectById(int id);

        3、对于字段名与属性名符合驼峰命名规则,mybatis会自动通过驼峰命名规则映射。

#开启驼峰命名自动映射
mybatis.configuration.map-underscore-to-camel-case=true
@Mapper
public interface EmpMapper {
    @Delete("delete from emp where id=#{id}")
    public int deleteForId(int id);

//    将自动生成的主键值返回,赋值给emp的id对象
    @Options(keyProperty = "id",useGeneratedKeys = true)
    @Insert("insert into emp(username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time) VALUES" +
            "(#{username},#{password},#{name}, #{gender}, #{image}, #{job}, #{entrydate}, #{deptId}, #{createTime}, #{updateTime})")
    public int insert(Emp emp);
}

在一个字段内传递参数时可使用concat来进行连接。比如:'%#{name}%'是不可用的,进行预编译时会将替换的?当成字符串来处理,无法传参,可使用concat('%',#{name},'%')来将字符串进行拼接。

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值