简介:
JDBC缺点:
Mybatis简化JDBC
Mybatis免除了几乎所有的JDBC代码以及设置参数和结果集的工作。
需求:查询user表中所有数据
mybatis
,再建一个表,表名为tb_user
,创建代码如下:create database mybatis;
use mybatis;
drop table if exists tb_user;
create table tb_user(
id int primary key auto_increment,
username varchar(20),
password varchar(20),
gender char(1),
addr varchar(30)
);
INSERT INTO tb_user VALUES (1, 'zhangsan', '123', '男', '北京');
INSERT INTO tb_user VALUES (2, '李四', '234', '女', '天津');
INSERT INTO tb_user VALUES (3, '王五', '11', '男', '西安');
pom.xml
内的坐标pom.xml
文件中,即如下代码:
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.13version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.32version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>1.7.20version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-classicartifactId>
<version>1.2.3version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-coreartifactId>
<version>1.2.3version>
dependency>
logback.xml
将它放在resources
目录下,内容如下:
<configuration>
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%level] %blue(%d{HH:mm:ss.SSS}) %cyan([%thread]) %boldGreen(%logger{15}) - %msg %npattern>
encoder>
appender>
<logger name="com.practice" level="DEBUG" additivity="false">
<appender-ref ref="Console"/>
logger>
<root level="DEBUG">
<appender-ref ref="Console"/>
root>
configuration>
resources
目录下,文件中的内容在官网中的示例如下,我们需要修改其中的内容:
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
mappers>
configuration>
value="${driver}"
中value
的值为"com.mysql.jdbc.Driver"
value="${url}"
中value
的值为"jdbc:mysql:///数据库名?useSSL=false"
,注意,这里一定要仔细输入,写错任何一个字符都有可能运行失败value="${username}"
中value
的值为自己数据库的登录名(一般为root
)value="${password}"
中value
的值为自己数据库的登录密码resource="org/mybatis/example/BlogMapper.xml"
的值为对应的sql的映射文件,之后我们再回来修改UserMapper.xml
,添加到resources
目录下,官网提供如下写法:
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
select>
mapper>
namespace
为命名空间,作为sql映射的唯一标识,在这里我们取名为test
select
表示的是查询的sql,对应还有添加、修改、删除等的写法,这里我们用的是查询,id可以定义为id="selectAll"
resultType
表示返回值的类型,这里由于我们要查找tb_user表中的全部数据,所以返回的可以是一个User集合,即resultType="com.practice.pojo.User"
,关于"com.practice.pojo.User"
在下面定义pojo类中讲解select * from Blog where id = #{id}
位置写入sql语句select * from tb_user;
即可resource="UserMapper.xml"
"com.practice.pojo.User"
,是在src.main.java
目录中的,最后的java文件User.java
中与对应mysql数据库的tb_user
表的字段值相同,只是将它们以java类的方式封装了起来,对应如下代码:package com.practice.pojo;
/**
* @Author YJ
* @Date 2023/7/24 10:47
* Description:User
*/
public class User {
private Integer id;
private String userName;
private String password;
private String gender;
private String addr;
public User() {
}
public User(Integer id, String userName, String password, String gender, String addr) {
this.id = id;
this.userName = userName;
this.password = password;
this.gender = gender;
this.addr = addr;
}
/**
* 获取
*
* @return id
*/
public Integer getId() {
return id;
}
/**
* 设置
*
* @param id
*/
public void setId(Integer id) {
this.id = id;
}
/**
* 获取
*
* @return userName
*/
public String getUserName() {
return userName;
}
/**
* 设置
*
* @param userName
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* 获取
*
* @return password
*/
public String getPassword() {
return password;
}
/**
* 设置
*
* @param password
*/
public void setPassword(String password) {
this.password = password;
}
/**
* 获取
*
* @return gender
*/
public String getGender() {
return gender;
}
/**
* 设置
*
* @param gender
*/
public void setGender(String gender) {
this.gender = gender;
}
/**
* 获取
*
* @return addr
*/
public String getAddr() {
return addr;
}
/**
* 设置
*
* @param addr
*/
public void setAddr(String addr) {
this.addr = addr;
}
public String toString() {
return "User{id = " + id + ", userName = " + userName + ", password = " + password + ", gender = " + gender + ", addr = " + addr + "}";
}
}
src.main.java
下创建一个测试类取名为(随意的)MybatisDemo.java
,放在com.practice
包下String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
resource
的值就是之前配置的mybatis文件"mybatis-config.xml"
SqlSession sqlSession = sqlSessionFactory.openSession();
//这里就是调用的`UserMapper.xml`中的sql语句,通过test查找到selectAll执行sql语句
List<Object> users = sqlSession.selectList("test.selectAll");
System.out.println(users);
sqlSession.close();
package com.practice;
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;
import java.util.List;
/**
* @Author YJ
* @Date 2023/7/24 10:53
* Description:Mybatis快速入门
*/
public class MybatisDemo {
public static void main(String[] args) throws IOException {
//1.加载mybatis的核心配置文件,获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取SqlSession对象,执行SQL
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.执行sql语句
List<Object> users = sqlSession.selectList("test.selectAll");
System.out.println(users);
//4.释放资源
sqlSession.close();
}
}
通过这篇文章,我们可以对Mybatis有了基本的认识,并能初步掌握Mybatis的用法与特性,欢迎各位小伙伴三连+关注!!!