@[toc]首先创建一个供查询的数据库和表
create database mybatis;
use mybatis;
drop table if exists mybatis;
create table tb_users(
id int primary key auto_increment,
username varchar(20),
password varchar(20),
gender char(1),
address varchar(30)
);
insert into tb_users values (1,'马大帅', '1234','M','莲花乡马家堡子');
insert into tb_users values (2,'范德彪', '5678','M','开原维多利亚玉乐广场');
insert into tb_users values (3,'罗翔', '9876','M','厚大法考');
select *
from tb_users;
结果如图
新建一个名为mybatis_demo的maven模块
给pom.xml文件添加依赖
<dependencies>
<dependency>
<!--mybatis的依赖-->
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.20</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.11</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.11</version>
</dependency>
</dependencies>
在main\resources文件夹里新建一个logback.xml文件,内容如下
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<!--
CONSOLE :表示当前的日志信息是可以输出到控制台的。
-->
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>【%level】 %blue(%d{HH:mm:ss.SSS}) %cyan(【%thread】) %boldGreen(%logger{15}) - %msg %n</pattern>
</encoder>
</appender>
<logger name="com.diy" level="DEBUG" additivity="false">
<appender-ref ref="Console"/>
</logger>
<root level="DEBUG">
<appender-ref ref="Console"/>
</root>
</configuration>
同样的方法建一个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:///mybatis?useSSl=false"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--此处加载sql的映射文件-->
<mapper resource="tb_usersMapper.xml"/>
</mappers>
</configuration>
mappers标签下是sql语句的映射文件,配置sql映射文件后将路径复制进去
创建本例要用的user类,在main\java路径下
package com.diy.pojo;
public class User {
private int id;
private String username;
private String password;
private char gender;
private String address;
public User() {
}
public User(int id, String username, String password, char gender, String address) {
this.id = id;
this.username = username;
this.password = password;
this.gender = gender;
this.address = 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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", gender=" + gender +
", address='" + address + '\'' +
'}';
}
}
创建sql映射文件,示例也在mybatsi官网有,修改命名空间,随意
修改标签id,结果类型改成刚才创建的类的全名
<?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="mybatis.TestMapper">
<select id="queryAll" resultType="com.diy.pojo.User">
select * from tb_users
</select>
</mapper>
因为本xml和核心配置文件在一个路径下,平级,所以将本文件名复制到核心配置文件的mappers标签里即可
最后写执行程序main方法,在main\java路径下
第一步的三行代码在官网复制后修改
package com.diy.mybatis;
import com.gable.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.IOException;
import java.io.InputStream;
import java.util.List;
public class Demo {
public static void main(String[] args) throws IOException {
//1.加载mybatis核心配置文件,获取SqlSessionFactory对象
String resource = "mybatis-config.xml";//在resources根目录下,直接写名字就可以
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.用获取到的工厂来获取SqlSession对象,就能执行sql语句了
SqlSession sqlsess = sqlSessionFactory.openSession();
//3.执行sql
List<User> users = sqlsess.selectList("mybatis.TestMapper.queryAll");
System.out.println(users);
//4.释放资源,关掉session即可
sqlsess.close();
}
}
执行效果如下
我的idea控制台输出中文有乱码,无法完美解决
总结本例思路
1.创建maven项目,或者模块mybatis,maven的pom.xml配置文件例导入相关依赖,尤其是mybatis的依赖
2.编写配置文件,日志logback的,mybatis的核心配置文件
3.编写执行程序要用到的sql语句映射文件Mapper.xml
4.创建返回结果类
5.写主程序,思路见代码
6.报错根据提示修改相关依赖的版本