Day10.Mybatis 8.1
- 创建时起步依赖(mybatis、mysql驱动、lombok)
2.Application.properties文件中 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/仓库名spring.datasource.username=root spring.datasource.password=1234 #指定mybatis输出日志的位置, 输出控制台 mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl #开启驼峰命名(推荐):如果字段名与属性名符合驼峰命名规则,mybatis会自动通过驼峰命名规则映射。 mybatis.configuration.map-underscore-to-camel-case=true #下面这些内容是为了让MyBatis映射 |
3.pojo实体类要和mybatis中的字段对应(有软件的书写不同) |
4.准备Mapper接口 ...Mapper(接口文件) |
5.MySQL数据库中设定下仓库的位置 |
6.测试文件中测试 |
增删改查
删除:(mapper文件内) @Delete("delete from 表名 where id = #{id}") public void delete(Integer id);} |
测试文件中 @Autowired Private ...Mapper 对象 @Test Public 返回类型 方法名(){ 对象.mapper文件中方法(实参)} |
- 预编译SQL,优势:1)性能更高: 预编译SQL,编译一次之后会将编译后的SQL语句缓存起来,再次执行相同SQL语句时,不会再次编译。 只是输入的参数不同。2)将敏感字进行转义,安全。
- SQL注入:通过操作输入来修改事先定义好的SQL语句,用以达到执行代码对服务器进行攻击的方法。 of ‘1=1’
9.参数占位符
#{...} |
执行SQL时,会将#{…}替换为?,生成预编译SQL,会自动设置参数值。 使用时机:参数传递,都使用#{…} |
${...} |
拼接SQL。直接将参数拼接在SQL语句中,存在SQL注入问题。 使用时机:如果对表名、列表进行动态设置时使用。 |
新增
@Insert("insert into 表名( 字段1,字段2,....) " + "values(#{pojo变量名1}, #{pojo变量名2}, ...")< |