文章目录
- mybatis是什么
- ORM是什么
- ORM框架和MyBatis的区别
- #{}和${}的区别
- 编码流程
- UserDaoImpl.java
- UserDao.java
- User.java
- db.properties
- SqlMapConfig.xml
- UserMapper.xml
- MybatisTest.java
- pom.xml
- user.sql
表现层 SpringMVC
业务层 Spring
持久层 Mybatis
https://mybatis.org/mybatis-3/
https://github.com/mybatis/mybatis-3
mybatis是什么
MyBatis 是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC代码和手动设置参数以及获取结果集,它可以使用简单的XML或注解来配置和映射SQL信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
ORM是什么
对象-关系映射(OBJECT/RELATIONALMAPPING,简称ORM),是随着面向对象的软件开发方法发展而产生的。用来把对象模型表示的对象映射到基于SQL 的关系模型数据库结构中去。这样,我们在具体的操作实体对象的时候,就不需要再去和复杂的 SQL 语句打交道,只需简单的操作实体对象的属性和方法 。ORM 技术是在对象和关系之间提供了一条桥梁,前台的对象型数据和数据库中的关系型的数据通过这个桥梁来相互转化。
ORM框架和MyBatis的区别
对比项 | Mybatis | Hibernate |
---|---|---|
市场占有率 | 高 | 高 |
适合的行业 | 互联网 电商 项目 | 传统的(ERP CRM OA) |
性能 | 高 | 低 |
Sql灵活性 | 高 | 低 |
学习门槛 | 低 | 高 |
Sql配置文件 | 全局配置文件、映射文件 | 全局配置文件、映射文件 |
ORM | 半自动化 | 完全的自动化 |
数据库无关性 | 低 | 高 |
#{}和${}的区别
区别一:
#{} :相当于JDBC SQL语句中的占位符? (PreparedStatement)
${} : 相当于JDBC SQL语句中的连接符合 + (Statement)
区别二:
#{} : 进行输入映射的时候,会对参数进行类型解析(如果是String类型,那么SQL语句会自动加上’’)
${} :进行输入映射的时候,将参数原样输出到SQL语句中
区别三:
#{} : 如果进行简单类型(String、Date、8种基本类型的包装类)的输入映射时,#{}中参数名称可以任意
${} : 如果进行简单类型(String、Date、8种基本类型的包装类)的输入映射时,${}中参数名称必须是value
区别四:
${} :存在SQL注入问题 ,使用OR 1=1 关键字将查询条件忽略
添加用户
#{}:是通过反射获取数据的—StaticSqlSource
${}:是通过OGNL表达式会随着对象的嵌套而相应的发生层级变化 --DynamicSqlSource
编码流程
1.编写全局配置文件:SqlMapConfig.xml(数据库配置等)
2.映射文件:xxxMapper.xml(编写sql语句)
3.编写dao代码:xxxDao接口、xxxDaoImpl实现类(编写mybatis API)
4.POJO类(用来传递参数和映射结果对象)
5.测试类
注意事项:
1:如果parameterType为简单类型(基本类型+String类),#{}中的参数名称可以任意
2:如果parameterType为POJO类型,#{}中的参数名称必须和POJO中的属性名称一致
3:如果resultType为POJO类型,SELECT的列名和POJO中的属性名称一致
UserDaoImpl.java
package com.xd.mybatisdemo.dao.impl;
import com.xd.mybatisdemo.dao.UserDao;
import com.xd.mybatisdemo.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;
public class UserDaoImpl implements UserDao {
//注入SqlSessionFactory
public UserDaoImpl(SqlSessionFactory sqlSessionFactory){
this. sqlSessionFactory = sqlSessionFactory;
}
private SqlSessionFactory sqlSessionFactory;
@Override
public User findUserById(int id) throws Exception {
SqlSession session = sqlSessionFactory.openSession();
User user = null;
try {
//通过sqlsession调用selectOne方法获取一条结果集
//参数1:指定定义的statement的id,参数2:指定向statement中传递的参数
user = session.selectOne("test.findUserById", id);
System.out.println(user);
} finally{
session.close();
}
return user;
}
@Override
public List<User> findUsersByName(String name) throws Exception {
SqlSession session = sqlSessionFactory.openSession();
List<User> users = null;
try {
users = session.selectList("test.findUserByUsername", name);
System.out.println(users);
} finally{
session.close();
}
return users;
}
}
UserDao.java
package com.xd.mybatisdemo.dao;
import com.xd.mybatisdemo.pojo.User;
import java.util.List;
public interface UserDao {
public User findUserById(int id) throws Exception;
public List<User> findUsersByName(String name) throws Exception;
}
User.java
package com.xd.mybatisdemo.pojo;
import java.util.Date;
public class User {
private int id;
private String username;
private Date birthday;
private String sex;
private String address;
public int getId() {
return id;
}
public void setId(int 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;
}
}
db.properties
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://127.0.0.1:3306/mybatisdemo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
db.username=root
db.password=root
SqlMapConfig.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>
<properties resource="db.properties"></properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml" />
</mappers>
</configuration>
UserMapper.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="test">
<!-- 根据id获取用户信息 -->
<select id="findUserById" parameterType="int"
resultType="com.xd.mybatisdemo.pojo.User">
select * from user where id = #{id}
</select>
<!-- 根据名称模糊查询用户列表 -->
<select id="findUserByUsername" parameterType="java.lang.String"
resultType="com.xd.mybatisdemo.pojo.User">
select * from user where username like '%${value}%'
</select>
</mapper>
MybatisTest.java
package com.xd.mybatisdemo;
import com.xd.mybatisdemo.dao.UserDao;
import com.xd.mybatisdemo.dao.impl.UserDaoImpl;
import com.xd.mybatisdemo.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.List;
public class MybatisTest {
private SqlSessionFactory sqlSessionFactory;
@Before
public void init() throws Exception {
SqlSessionFactoryBuilder sessionFactoryBuilder = new
SqlSessionFactoryBuilder();
InputStream inputStream =
Resources.getResourceAsStream("SqlMapConfig.xml");
sqlSessionFactory = sessionFactoryBuilder.build(inputStream);
}
@Test
public void testFindUserById() throws Exception {
UserDao userDao = new UserDaoImpl(sqlSessionFactory);
User user = userDao.findUserById(3);
System.out.println(user.getUsername());
}
@Test
public void testFindUsersByName() throws Exception {
UserDao userDao = new UserDaoImpl(sqlSessionFactory);
List<User> users = userDao.findUsersByName("老郭");
for (User user : users) {
System.out.println(user.getAddress());
}
}
}
pom.xml
<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>org.example</groupId>
<artifactId>mybatisdemo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mybatisdemo</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- mybatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- mysql依赖 -->
<!-- <dependency>-->
<!-- <groupId>mysql</groupId>-->
<!-- <artifactId>mysql-connector-java</artifactId>-->
<!-- <version>5.1.35</version>-->
<!-- </dependency>-->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.32</version>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</project>
user.sql
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`birthday` date NULL DEFAULT NULL,
`sex` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '老郭', '2024-12-17', '男', 'aaa');
INSERT INTO `user` VALUES (2, '张三', '2024-12-10', '女', 'ccc');
INSERT INTO `user` VALUES (3, '李四', '2024-12-19', '女', 'ddd');
INSERT INTO `user` VALUES (4, '老郭', '2024-12-20', '男', 'eee');
SET FOREIGN_KEY_CHECKS = 1;