Mybatis -- MyBatis的Dao层实现(传统方式实现接口代理方式实现)
Posted CodeJiao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis -- MyBatis的Dao层实现(传统方式实现接口代理方式实现)相关的知识,希望对你有一定的参考价值。
预备:准备工作
准备工作 创建一个maven工程:
1.1 添加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">
<parent>
<artifactId>smm_heima</artifactId>
<groupId>com.tian</groupId>
<version>1.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>mybatis_01</artifactId>
<dependencies>
<!-- mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<!-- mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- 单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
<!-- 日志打印-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>
1.2 创建User数据表(搭建数据库环境)
执行下列sql语句
CREATE DATABASE `test`;
USE `test`;
CREATE TABLE `user` (
`id` INT NOT NULL PRIMARY KEY,
`username` VARCHAR ( 30 ) DEFAULT NULL,
`password` VARCHAR ( 30 ) DEFAULT NULL
) ENGINE = INNODB DEFAULT CHARSET = utf8;
INSERT INTO USER (`id`, `username`, `password`) VALUES
(1,'thylove', '123456'),
(2, 'root', '123456'),
(3, 'admin', '123456');
执行结果:
1.3 编写User实体类
User.java
package com.tian.pojo;
public class User {
private int id;
private String username;
private String password;
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\\'' +
", password='" + password + '\\'' +
'}';
}
}
1.4 编写映射文件UserMapper.xml
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="userMapper">
<!--查询操作-->
<select id="findAll" resultType="com.tian.pojo.User">
select *
from user
</select>
</mapper>
1.5 编写核心文件SqIMapConfig.xml
准备工作:编写数据库配置文件:
jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=317525
正式开始:
SqIMapConfig.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标签加载外部properties文件-->
<properties resource="jdbc.properties"/>
<!--数据源环境-->
<environments default="developement">
<environment id="developement">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--加载映射文件-->
<mappers>
<mapper resource="com.tian.mapper/UserMapper.xml"/>
</mappers>
</configuration>
1. 传统方式实现
UserDao.java
package com.tian.dao;
import com.tian.pojo.User;
import java.util.List;
/**
* ClassName: UserDao
* Description: 查询所有用户
*
* @author Tianjiao
* @date 2021/11/5 19:19
*/
public interface UserDao {
List<User> findAll() throws Exception;
}
UserDaoImpl.java
package com.tian.dao.impl;
import com.tian.dao.UserDao;
import com.tian.pojo.User;
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.InputStream;
import java.util.List;
/**
* ClassName: UserDaoImpl
* Description:
*
* @author Tianjiao
* @date 2021/11/5 19:20
*/
public class UserDaoImpl implements UserDao {
@Override
public List<User> findAll() throws Exception {
//获得核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("SqIMapConfig.xml");
//获得session工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获得session回话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行操作 参数:namespace+id
List<User> userList = sqlSession.selectList("userMapper.findAll");
//释放资源
sqlSession.close();
return userList;
}
}
测试代码:
MyBatisTest.java
package com.tian.test;
import com.tian.dao.impl.UserDaoImpl;
import org.junit.Test;
public class MyBatisTest {
@Test
//查询操作
public void test1() throws Exception {
System.out.println(new UserDaoImpl().findAll());
}
}
运行结果:
2. 接口代理方式实现(常用)
说明:
实例:
-
我们先删除dao层的impl的包
-
修改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">
<!--现在的namespace对应UserDao的全限定类名-->
<mapper namespace="com.tian.dao.UserDao">
<!--查询操作 id对象UserDao的方法名-->
<select id="findAll" resultType="com.tian.pojo.User">
select *
from user
</select>
</mapper>
- 测试:
MyBatisTest.java
package com.tian.test;
import com.tian.dao.UserDao;
import com.tian.pojo.User;
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 org.junit.Test;
import java.io.InputStream;
import java.util.List;
public class MyBatisTest {
@Test
//查询操作
public void test1() throws Exception {
// 获取SqlSession
InputStream resourceAsStream = Resources.getResourceAsStream("SqIMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
// 调用dao层方法
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> userList = mapper.findAll();
System.out.println(userList);
}
}
运行结果:
3. 比较2种方式
以上是关于Mybatis -- MyBatis的Dao层实现(传统方式实现接口代理方式实现)的主要内容,如果未能解决你的问题,请参考以下文章