12
Mybatis 快速入门(XML方式)第一天
source link: http://www.cnblogs.com/chenyanbin/p/12895291.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
导读
架构原理图
说明
mybatis配置文件
- SqlMapConfig.xml,此文件为mybatis的全局配置文件,配置了mybatis的运行环境等信息
- XXXMapper.xml,此文件作为mybatis的sql映射文件,文件中配置了操作数据库的CRUD语句。需要在SqlMapConfig.xml中加载
SqlSessionFactory
- 通过mybatis环境等配置信息构造SqlSessionFactory,既会话工厂
***跟底层源码查看创建SqlSessionFactory流程***
注:底层如何获取标签值,请自行研究( 剧透:for循环遍历XML获取标签中的值,然后放入Map )!~
SqlSession
- 通过会员工厂创建SqlSession即会话,程序通过SqlSession会话接口对数据库进行CRUD操作。
Executor执行器
mybatis底层自定义了Executor执行器接口来具体操作数据库,Executor接口有两个实现,一个是基本执行器(默认),一个缓存执行器,SqlSession底层是通过executor接口操作数据库
Mapped Statement
他是mybatis一个底层封装对象,包装了mybatis配置信息及XXXMapper.xml映射文件等。XXXMapper.xml文件中一个个 select/insert/update/delete标签对应一个Mapped Statement对象 。
原始JDBC代码
原始JDBC和mybatis操作数据库数据,与上面架构图流程相对应。
public class JDBCTest { public static void main(String[] args) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { // 加载数据库驱动 Class.forName("com.mysql.jdbc.Driver"); // 通过驱动管理类获取数据库链接connection = DriverManager connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "root" ); // 定义sql语句 ?表示占位符 String sql = "select * from user where username = ?"; // 获取预处理 statement preparedStatement = connection.prepareStatement(sql); // 设置参数,第一个参数为 sql 语句中参数的序号(从 1 开始),第二个参数为设置的 preparedStatement.setString(1, "王五"); // 向数据库发出 sql 执行查询,查询出结果集 resultSet = preparedStatement.executeQuery(); // 遍历查询结果集 while (resultSet.next()) { System.out.println( resultSet.getString("id") + " " + resultSet.getString("username") ); } } catch (Exception e) { e.printStackTrace(); } finally { // 释放资源 if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
Mybatis 入门基础
表结构
表数据
Mybatis环境搭建
添加依赖
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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cyb</groupId> <artifactId>mybatis</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>mybatis Maven Webapp</name> <url>http://maven.apache.org</url> <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>8.0.20</version> </dependency> <!-- 单元测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> <build> <finalName>mybatis</finalName> </build> </project>
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>
db.properties
db.driver=com.mysql.jdbc.Driver db.url=jdbc:mysql://127.0.0.1:3306/cyb db.username=root db.password=root
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:为了分类管理映射文件中的MappedStatement --> <mapper namespace="test"> <select id="queryUserById" parameterType="int" resultType="com.cyb.mybatis.demo.User"> select * from user where id = #{id} </select> </mapper>
User.java
package com.cyb.mybatis.demo; import java.util.Date; public class User { private int id; private String username; private Date birthday; private int 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 int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", birthday=" + birthday + ", sex=" + sex + ", address=" + address + "]"; } }
MybatisDemo.java
package com.cyb.mybatis.demo; import java.io.InputStream; 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.Before; import org.junit.Test; public class MybatisDemo { private SqlSessionFactory sqlSessionFactory; @Before public void init() throws Exception { //指定全局配置文件路径 String resource = "SqlMapConfig.xml"; //加载资源文件(包括全局文件和映射文件) InputStream inputStream = Resources.getResourceAsStream(resource); //使用构建者模式创建SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } @Test public void testSelect() { //由SqlSessionFactory工厂去创建SqlSession(会话) SqlSession sqlSession = sqlSessionFactory.openSession(); //调用SqlSession接口,去实现数据库的CRUD User user = sqlSession.selectOne("test.queryUserById", 1); System.out.println(user); //释放资源 sqlSession.close(); } }
项目结构
测试
功能实现
根据用户id查询一个用户信息
根据用户名称模糊查询用户信息列表
添加用户
更新用户
删除用户
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK