什么是Mybatis
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录
Mybatis获得方法
-
maven仓库:
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency>
-
Github : https://github.com/mybatis/mybatis-3/releases
-
中文文档:https://mybatis.org/mybatis-3/zh/index.html
数据持久化
- 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
- 内存数据特点:断电即失
为什么需要需要持久化?
- 相关数据需要长久保存,如:财务支出,会员信息等
- 内存价格昂贵
持久层
即完成持久化操作的代码块
MyBatis优点
- 简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件易于学习,易于使用,通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
- 灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
- 解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
- 提供映射标签,支持对象与数据库的orm字段关系映射
- 提供对象关系映射标签,支持对象关系组建维护
- 提供xml标签,支持编写动态sql。
使用MyBatis原因
- 可以简化JDBC操作
- 简单,方便,易操作
MyBatis:代码实操(查询数据库)
- 创建数据库,并且插入数据
CREATE DATABASE `mybatis`;
USE `mybatis`;
CREATE TABLE `user`(
`id` INT(20) PRIMARY KEY NOT NULL,
`username` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE =INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user` (`id`,`username`,`pwd`) VALUES (1,'张三','123456');
INSERT INTO `user` (`id`,`username`,`pwd`) VALUES (2,'李四','123456');
INSERT INTO `user` (`id`,`username`,`pwd`) VALUES (3,'王五','123456');
- 新建项目
新建一个普通的maven项目、删除src目录、导入maven依赖
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
- 书写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核心配置文件-->
<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="123456"/>
</dataSource>
</environment>
</environments>
</configuration>
- 编写mybatis工具类
public class MyBatisUtils {
private static SqlSessionFactory build;
static {
try {
//使用Mybatis第一步:获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
build = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return build.openSession();
}
}
- 编写用户对象实体类
public class User {
private int id;
private String username;
private String pwd;
public User() {
}
public User(int id, String username, String pwd) {
this.id = id;
this.username = username;
this.pwd = pwd;
}
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 String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
- 编写Dao接口
public interface UserDao {
List<User> getUserList();
}
- 编写接口的实现Mapper配置文件(UserMapper.xml)
注:namespace为接口所在的全路径
id:为需要执行的方法名
resultType:查询完后返回的类型:对应实体类的全路径
<?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接口-->
<mapper namespace="Dao.UserDao">
<!--select查询语句-->
<select id="getUserList" resultType="pojo.User">
select * from mybatis.user
</select>
</mapper>
- 在MyBatis核心配置文件中注册:UserMapper.xml
<mappers>
<mapper resource="Dao/UserMapper.xml" />
</mappers>
- 编写测试类
public class UserDaoTest {
@Test
public void test(){
//获取sqlSession对象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//通过getMapper方法获取UserDao接口对象
UserDao UserDao = sqlSession.getMapper(UserDao.class);
//获得查询结果
List<User> userList = UserDao.getUserList();
//打印结果
for (User user : userList) {
System.out.println(user);
}
}
}
- 为避免写在/src/main/java目录下资源文件无法导出问题,在子项目与父项目的pom.xml中,添加如下配置
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
结果展示
MyBatis:代码实操(增、删、改)
注:增、删、改一定要提交事务
注:是在上面的代码中进行功能的增加
- UserDao接口中的增加
//通过ID查询用户
User getUserById(int id);
//添加用户
int addUser(User user);
//更改用户信息
int updateUser(User user);
//删除用户
int deleteUser(int id);
- UserMapper.xml中的增加
<select id="getUserById" parameterType="int" resultType="pojo.User">
select * from mybatis.user where id=#{id};
</select>
<insert id="addUser" parameterType="pojo.User" >
insert into mybatis.user(id, username, pwd) values(#{id},#{username},#{pwd});
</insert>
<update id="updateUser" parameterType="pojo.User">
update mybatis.user set username=#{username},pwd=#{pwd} where id=#{id} ;
</update>
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=#{id};
</delete>
- 测试类的增加
@Test
public void getById(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserDao userdao = sqlSession.getMapper(UserDao.class);
User user = userdao.getUserById(2);
System.out.println(user);
}
@Test
public void adduser(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserDao userdao = sqlSession.getMapper(UserDao.class);
int i = userdao.addUser(new User(4, "赵柳", "123456"));
sqlSession.commit();
if(i>0){
System.out.println("添加成功");
}
sqlSession.close();
}
@Test
public void updateuser(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserDao userdao = sqlSession.getMapper(UserDao.class);
int i = userdao.updateUser(new User(4, "赵六", "111111"));
sqlSession.commit();
if(i>0){
System.out.println("添加成功");
}
sqlSession.close();
}
@Test
public void deleteUser(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserDao userdao = sqlSession.getMapper(UserDao.class);
int i = userdao.deleteUser(4);
sqlSession.commit();
if(i>0){
System.out.println("删除成功");
}
sqlSession.close();
}
MyBatis:使用Map集合作为参数,以及模糊查询实现
- 接口定义方法
//获得用户通过Map集合
User getUserByMap(Map<String,Object> map);
//模糊chaxun
List<User> getUserLike(String name);
- UserMapper.xml中的增加
<select id="getUserByMap" parameterType="Map" resultType="pojo.User">
select * from mybatis.user where id=#{id} and username=#{lala};
</select>
<select id="getUserLike" resultType="pojo.User">
select * from mybatis.user where username like "%"#{name}"%";
</select>
- 测试类实现
@Test
public void getByMap(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserDao userdao = sqlSession.getMapper(UserDao.class);
Map<String, Object> map = new HashMap<>();
map.put("id",1);
map.put("lala","张三");
User user = userdao.getUserByMap(map);
System.out.println(user);
}
@Test
public void getByLike(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserDao userdao = sqlSession.getMapper(UserDao.class);
List<User> list = userdao.getUserLike("王");
for (User user : list) {
System.out.println(user);
}
}