什么是 MyBatis? MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
如何获得Mybatis? maven 仓库:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
持久化
- 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
- 内存:断电即失
- 数据库(jdbc),io文件持久化
为什么需要持久化?
为什么需要Mybatis?
- 帮助程序员将数据存入到数据库中
- 传统的JDBC代码太复杂,简化–>框架–>自动化
- 方便,使用的人多
第一个Mybatis程序 思路:搭建环境–>导入Mybatis–>编写代码–>测试
1、搭建数据库
CREATE DATABASE `mybatis`;
USE `mybatis`;
CREATE TABLE `user`(
`id` INT(20) NOT NULL PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user` (`id`,`name`,`pwd`) VALUES
(1,'重庆','123456'),
(2,'贵州','123456'),
(3,'遵义','991123')
2、新建一个普通maven项目 3、导入maven依赖
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
4、编写mybatis的核心配置文件(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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="991123"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/like/dao/UserMapper.xml"/>
</mappers>
</configuration>
5、编写mybatis工具类
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
6、编写一个实体类
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
7、Mapper接口
public interface UserDao {
List<User> getUserList();
}
8、接口实现类由原来的UserDaoImpl转变成一个Mapper配置文件。
<?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.like.dao.UserMapper">
<select id="getUserList" resultType="com.like.pojo.User">
select * from mybatis.user
</select>
</mapper>
9.测试 MapperRegistry是什么?:映射注册表 核心配置文件中注册mappers
junit测试:
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
测试CRUD(增删改查) 1、 namespace namespace中的包名要和Mapper接口的包名一致! 2、select 选择,查询语句;
- id:就是对应namespace中的方法名;
- resultType:sql语句执行的返回值;
- parameterType:参数类型!
编写Mapper接口:
public interface UserMapper {
List<User> getUserList();
User getUserId(int id);
int addUser(User user);
int updateUser(User user);
int deleteUser(int id);
}
编写对应的mapper中的sql语句: 查:
<select id="getUserList" resultType="com.like.pojo.User">
select * from mybatis.user
</select>
<select id="getUserId" parameterType="int" resultType="com.like.pojo.User">
select * from mybatis.user where id = #{id};
</select>
增:
<insert id="addUser" parameterType="com.like.pojo.User">
insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd});
</insert>
改:
<update id="updateUser" parameterType="com.like.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id = #{id}
</update>
删:
<delete id="deleteUser" parameterType="int" >
delete from mybatis.user where id = #{id};
</delete>
注意点:增删改需要提交事务!
穿插一个知识点:这么避免sql注入问题:模糊查询怎么写? 1、java代码执行的时候,传递通配符% %
List<User> userList = mapper.getUserLike("%李%");
2、在sql拼接中使用通配符!
select * from mybatis.user where name like "%"#{value}"%"
|