MyBatis见解
2023-12-21 13:07:16
一,mybatis介绍
- 为什么要使用mybatis?
手动创建和释放连接
对结果的解析
sql语句硬编译在代码中 - 什么是mybatis?
mybatis前身是apache的ibatis,是封装了jdbc的持久层框架,使开发者只需关注sql即可
二,mybatis入门
- pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.by</groupId>
<artifactId>01_mybatis_HelloWorld</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<!-- 项目源码及编译输出的编码 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- 项目编译JDK版本 -->
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
// 如果jdk的版本不是8.0以上,需要修改
//<version>版本号</version>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<build>
<!-- 如果不添加此节点src/main/java目录下的所有配置文件都会被漏掉。 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
- log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
- pojo
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
- mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<configuration>
<!--使用dev环境-->
<environments default="dev">
<!--dev环境-->
<environment id="dev">
<transactionManager type="JDBC"></transactionManager>
<!--使用连接池中的数据源-->
<dataSource type="POOLED">
//jdk版本8以上的
// <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
// <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=Asia/Shanghai"/>
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="1111"/>
</dataSource>
</environment>
</environments>
<!-- 扫描映射文件 -->
<mappers>
<mapper resource="com/by/dao/UserDao.xml"/>
</mappers>
</configuration>
- mapper
public interface UserDao{
List<User> findAll();
}
- mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.by.dao.UserDao">
<select id="findAll" resultType="com.by.pojo.User">
select * from user
</select>
</mapper>
- pom.xml
<build>
<!-- 如果不添加此节点src/main/java目录下的所有配置文件都会被漏掉。 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
三,mybatis的运行原理
四,mybatis传递多个参数
- 序号传递多个参数
WHERE id=#{arg0} AND username=#{arg1}
WHERE id=#{param1} AND username=#{param2}
// 定义的方法
User getUser(Integer id, String username);
<select id="getUser" resultType="com.by.pojo.User">
<!--select * from user where id=#{arg0} and username=#{arg1}--><!-- arg0 arg1-->
select * from user where id=#{param1} and username=#{param2}<!-- param1 param2-->
</select>
/**
* 序号传递多个参数
* @throws IOException
*/
@Test
public void testGetUse() throws IOException {
//返回接口的代理类
UserDao userDao = sqlSession.getMapper(UserDao.class);
User user = userDao.getUser(43,"俞莲舟");
System.out.println(user);
}
- 注解传递多个参数—【推荐】
User getUser2(@Param(“id”) Integer id, @Param(“username”) String username);
select * from user where id=#{id} and username=#{username}
User getUser2(@Param("id")Integer id, @Param("username") String username);
<select id="getUser2" resultType="com.by.pojo.User">
select * from user where id=#{id} and username=#{username}
</select>
/**
* 注释传递多个参数
* @throws IOException
*/
@Test
public void testGetUse2() throws IOException {
//返回接口的代理类
UserDao userDao = sqlSession.getMapper(UserDao.class);
User user = userDao.getUser2(43,"俞莲舟");
System.out.println(user);
}
- pojo传递多个参数—【推荐】
User getUser3(User user);
select * from user where id=#{id} and username=#{username}
User getUser3(User user);
<select id="getUser3" parameterType="com.by.pojo.User" resultType="com.by.pojo.User">
select * from user where id=#{id} and username=#{username}
</select>
/**
* 对象传递多个参数
* @throws IOException
*/
@Test
public void testGetUse3() throws IOException {
//返回接口的代理类
UserDao userDao = sqlSession.getMapper(UserDao.class);
User user1 = new User();
user1.setId(43);
user1.setUsername("俞莲舟");
User user = userDao.getUser3(user1);
System.out.println(user);
}
- map传递多个参数
User getUser3(Map user);
select * from user where id=#{id} and username=#{username}
User getUser4(Map<String,Object> map);
<select id="getUser4" parameterType="java.util.Map" resultType="com.by.pojo.User">
select * from user where id=#{id} and username=#{username}
</select>
/**
* 集合传递多个参数
* @throws IOException
*/
@Test
public void testGetUse4() throws IOException {
//返回接口的代理类
UserDao userDao = sqlSession.getMapper(UserDao.class);
Map<String,Object> map = new HashMap<>();
map.put("id",43);
map.put("username","俞莲舟");
User user = userDao.getUser4(map);
System.out.println(user);
}
五,${}和#{}的区别
sql注入 底层 jdbc类型转换 单个简单类型的参数
$ 不防止 Statement 不转换 value
# 防止 preparedStatement 转换 任意
结论:除模糊匹配外,杜绝使用${}
- 模糊查询
/**
* 模糊查询
* @throws IOException
*/
@Test
public void testGetUserByUsername() throws IOException {
//返回接口的代理类
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> list = userDao.getUserByUsername("张");
for (User user:list){
System.out.println(user);
}
}
List<User> getUserByUsername(String username);
<select id="getUserByUsername" parameterType="java.lang.String" resultType="com.by.pojo.User">
select * from user where username like '%${value}%'
</select>
- sql注入
/**
* sql注入
* @throws IOException
*/
@Test
public void testLogin() throws IOException {
//返回接口的代理类
UserDao userDao = sqlSession.getMapper(UserDao.class);
User userInfo = new User();
userInfo.setUsername("张三丰'#");
userInfo.setPassword("222");
User user = userDao.login(userInfo);
System.out.println(user);
}
User login(User userInfo);
<select id="login" parameterType="com.by.pojo.User" resultType="com.by.pojo.User">
select * from user where username='${username}' and password='${password}'
</select>
六,mybatis的主键回填
- 删
<delete id="deleteUserById" parameterType="java.lang.Integer">
delete from user where id = #{id}
</delete>
void deleteUserById(Integer id);
/**
* 删除sql
* 返回值是Rolling
* 需要删除调用sqlSession.commit()
* @throws IOException
*/
@Test
public void testDeleteUserById() throws IOException {
//返回接口的代理类
UserDao userDao = sqlSession.getMapper(UserDao.class);
userDao.deleteUserById(42);
//提交
sqlSession.commit();
}
- 改
void updateUserById(User user);
<update id="updateUserById" parameterType="com.by.pojo.User">
update user set username=#{username}, password=#{password}, birthday=#{birthday}, sex=#{sex}, address=#{address} where id=#{id}
</update>
/**
* 修改指定内容
* @throws IOException
*/
@Test
public void testUpdateUserById() throws IOException {
//返回接口的代理类
UserDao userDao = sqlSession.getMapper(UserDao.class);
User user = new User();
user.setUsername("郭襄");
user.setPassword("222");
user.setBirthday(new Date());
user.setAddress("峨眉山");
user.setSex("女");
user.setId(42);
userDao.updateUserById(user);
sqlSession.commit();
}
- 增
/**
* 新增内容
* @throws IOException
*/
@Test
public void testAddUser() throws IOException {
//返回接口的代理类
UserDao userDao = sqlSession.getMapper(UserDao.class);
User user = new User();
user.setUsername("杨过");
user.setPassword("222");
user.setBirthday(new Date());
user.setAddress("峨眉山");
user.setSex("男");
userDao.AddUser(user);
System.out.println("返回自增id:"+user.getId());
//提交
sqlSession.commit();
}
void AddUser(User user);
<!--
useGeneratedKeys="true":使用自增id
keyProperty="id":回填到实体类的哪个属性
-->
<insert id="AddUser" useGeneratedKeys="true" keyProperty="id" parameterType="com.by.pojo.User">
<!--
逐渐回填(返回自增id):插入记录后返回自增的id到参数
keyProperty="id":回填到实体类的哪个属性
order="AFTER":先执行插入,再主键回填
resultType="java.lang.Integer":主键的类型
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>-->
INSERT INTO user(username,password,birthday,sex,address) VALUE(#{username},#{password},#{birthday},#{sex},#{address})
</insert>
方式一:
<insert id="" useGeneratedKeys="true" keyProperty="id" parameterType="">
方式二:
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
文章来源:https://blog.csdn.net/y666__/article/details/135093121
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!