1.SSM学习内容
2.mybatis简介
2.1概念
- MyBatis 是一款优秀的持久层框架
- 它支持自定义 SQL、存储过程、高级映射
- MyBatis 免除了几乎所有的 JDBC 代码、设置参数、获取结果集的工作
- MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO为数据库中的记录
- MyBatis本是apache的一个开源项目iBatis,2010年这个项目由apache software foundation迁移到了google code,并且改名为MyBatis
- 2013年11月迁移到Github
持久化:数据持久化
- 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
- 数据库JDBC,io文件持久化
为什么要持久化?
- 内存:断电即失,有一些对象不能让他丢掉
- 内存过于昂贵
持久层:
- 完成持久化工作的代码块
- 层界限十分明显
2.2如何获取
-
maven仓库
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency>
-
Github:https://github.com/mybatis/mybatis-3/releases
-
中文文档:https://mybatis.net.cn/
2.3为什么需要
-
帮助程序员将数据存入到数据库中
-
方便
-
传统的JDBC代码过于复杂了,简化、框架、自动化
-
不用mybatis也可以,mybatis更容易上手,技术没有高低之分
-
使用的人多
-
优点:
- 简单易学:没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件。
- 灵活:sql写在xml里,便于统一管理和优化。
- 解除sql与程序代码的耦合:sql和代码的分离,提高了可维护性。
- 提供映射标签,支持对象与数据库的orm字段关系映射。
- 提供对象关系映射标签,支持对象关系组建维护。
- 提供xml标签,支持编写动态sql。
3.第一个MyBatis程序
思路:搭建环境–>导入mybatis–>编写代码–>测试!
3.1搭建环境
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,'小','123965'),
(3,'大神','09876')
2.新建项目
-
新建一个普通的maven项目,并且检查一下设置中maven是不是自己下载的
-
删除src目录
-
导入maven依赖
<!--导入依赖--> <dependencies> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.16</version> </dependency> <!--mybatis驱动--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> <!--junit驱动--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> </dependency> </dependencies> <!--在build中配置resources,来防止我们资源导出失败的问题--> <build> <resources> <resource> <directory>src/main/resources</directory> <excludes> <exclude>**/*.properties</exclude> <exclude>**/*.xml</exclude> </excludes> <filtering>false</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
3.2创建一个模块
-
编写mybatis核心配置文件
<?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.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=CTT"/> <property name="username" value="root"/> <property name="password" value="1234"/> </dataSource> </environment> </environments> <!--每一个Mapper.xml都需要在mybatis核心配置文件中注册!--> <mappers> <mapper resource="moli/dao/UserMapper.xml"/> </mappers> </configuration>
并在idea中连接数据库:
-
编写mybatis工具类
SqlSessionFactoryBuilder---->sqlSessionFactory---->SqlSession
package moli.utils; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; //从 SqlSessionFactory 中获取 SqlSession public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { //使用mybatis第一步:获取sqlSessionFactory对象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例 //SqlSession 提供了在数据库执行 SQL 命令所需的所有方法 public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
3.3编写代码
- 实体类
package moli.pojo;
//实体类
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 + '\'' +
'}';
}
}
-
Dao接口
package moli.dao; import moli.pojo.User; import java.util.List; public interface UserDao { List<User> getUserList(); }
-
接口实现类(由原来的DaoImpl转换为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"> <!--namespace=绑定一个对应的Dao/Mapper接口,注意包名一定要写正确--> <!--id:方法名,resultType:返回一个结果,resultMap:返回结果集--> <mapper namespace="moli.dao.UserDao"> <select id="getUserList" resultType="moli.pojo.User"> select * from mybatis.user </select> </mapper>
3.4测试
3.4.1遇到的问题
- 在测试之前关掉maven自带的test
-
org.apache.ibatis.binding.BindingException: Type interface moli.dao.UserDao is not known to the MapperRegistry.
MapperRegistry:就是在核心配置文件中没有注册Mapper。
-
maven由于它的约定大于配置,我们之后可能遇到我们写的配置文件,无法被导出或者生效的问题
<!--在build中配置resources,来防止我们资源导出失败的问题--> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
3.4.2junit测试
package moli.dao;
import moli.pojo.User;
import moli.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test(){
//获取sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//执行sql,方式一:
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
//方式二:不推荐
//List<User> userList = sqlSession.selectList("moli.dao.UserDao.getUserList");
for (User user : userList) {
System.out.println(user);
}
//关闭sqlSession
sqlSession.close();
}
}
测试结果:
4.CRUD
-
改接口:
public interface UserDao { //获取全部用户 List<User> getUserList(); //根据id获取用户 User getUserById(int id); //增加一个用户 int addUser(User user); //删除一个用户 int deleteUser(int id); //修改一个用户 int updateUser(User user); }
-
改Mapper.xml
<select id="getUserById" resultType="moli.pojo.User" parameterType="int"> select * from mybatis.user where id = #{id} </select> <insert id="addUser" parameterType="moli.pojo.User"> insert into mybatis.user values (#{id},#{name},#{pwd}) </insert> <delete id="deleteUser" parameterType="int"> delete from mybatis.user where id=#{id} </delete> <update id="updateUser" parameterType="moli.pojo.User"> update mybatis.user set user.name=#{name},pwd=#{pwd} where id=#{id} </update>
-
测试
@Test public void getUserByIdtest(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); System.out.println(mapper.getUserById(1)); } //增删改需要提交事务 @Test public void addUserTest(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); int res = mapper.addUser(new User(4,"哈哈","1238941")); if (res>0){ System.out.println("插入成功"); } //提交事务 sqlSession.commit(); sqlSession.close(); } @Test public void deleteUserTest(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); mapper.deleteUser(1); //提交事务 sqlSession.commit(); sqlSession.close(); } @Test public void updateUserTest(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); int res = mapper.updateUser(new User(3,"乐乐","19024")); if (res>0){ System.out.println("修改成功"); } //提交事务 sqlSession.commit(); sqlSession.close(); }
5.万能Map
假设我们的实体类,或者数据库中的表,字段或者参数过多,我们应该考虑使用Map!
-
Map传递参数,直接在sql中取出key即可! parameterType=“map”
-
对象传递参数,直接在sql中取对象的属性即可! parameterType=“Object”
-
多个参数用map或者注解
public interface UserDao {
int addUser1(Map<String,Object> map);
}
<insert id="addUser1" parameterType="map">
insert into mybatis.user (id,user.name,pwd) values (#{userid},#{username},#{userpwd})
</insert>
@Test
public void addUser1Test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
HashMap<String, Object> map = new HashMap<>();
map.put("userid",6);
map.put("username","零零");
map.put("userpwd","99999");
mapper.addUser1(map);
//提交事务
sqlSession.commit();
sqlSession.close();
}
6.模糊查询
模糊查询的两种方式:
-
java代码执行的时候传递通配符% %
public interface UserDao { List<User> getUserLike(String value); }
<select id="getUserLike" resultType="moli.pojo.User"> select * from mybatis.user where user.name like #{value} </select>
@Test public void getUserLiketest(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); List<User> like = mapper.getUserLike("%乐%"); for (User user : like) { System.out.println(user); } sqlSession.close(); }
查询结果:
-
在sql拼接的时候使用通配符,但会出现sql注入问题不安全
<select id="getUserLike" resultType="moli.pojo.User"> select * from mybatis.user where user.name like "%" #{value} "%" </select>