第一步、加入所需要的依赖
我们可以去官网下载MyBatis的jar包也可以直接在maven里面引入
这边直接选择在maven里面引入的方式
在新建好的项目里面的pom.xml文件里面添加依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
我这边使用的是3.5.10版本,也可以在maven仓库里面找Maven 存储库:搜索/浏览/探索https://mvnrepository.com/
我们还需要MySQL依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
这边我们还需要用到日志和测试的依赖
<!--测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>compile</scope>
</dependency>
<!--日志依赖-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.11</version>
<scope>test</scope>
</dependency>
添加好刷新一下可以看到我们的maven仓库里面就有我们所需要的依赖了
第二步、添加日志文件
我们将logback.xml设置为日志的名字,在里面添加好以下代码,要把文件放入resources文件里面
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!--定义⽇志⽂件的存储地址-->
<property name="LOG_HOME" value="/home"/>
<!--控制台输出-->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示⽇期,%thread表示线程名,%-5level:级别从左显示5个字符度%msg:⽇志消息,%n是换⾏符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!--按照每天⽣成⽇志⽂件-->
<!--⽇志⽂件输出的⽂件名-->
<!--mybatis log configure-->
<logger name="com.apache.ibatis" level="TRACE"/>
<logger name="java.sql.Connection" level="DEBUG"/>
<logger name="java.sql.Statement" level="DEBUG"/>
<logger name="java.sql.PreparedStatement" level="DEBUG"/>
<!--⽇志输出级别,logback⽇志级别包括五个:TRACE < DEBUG < INFO < WARN < ERROR -->
<root level="DEBUG">
<appender-ref ref="STDOUT"/>
<appender-ref ref="FILE"/>
</root>
</configuration>
这样我们的日志文件就生效了
第三步、创建MyBatis核心配置文件
我们将mybatis-config.xml设置为Mybatis核心配置文件名,同样把他放到resources文件里面
添加以下代码
<configuration>
<properties resource="jdbc.properties"/>
<environments default="dev">
<environment id="dev">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--sql
映射⽂件创建好之后,需要将该⽂件路径配置到这⾥-->
<mapper resource="CarMapper.xml"/>
</mappers>
</configuration>
-
<configuration>
-
MyBatis 配置文件的根元素,所有配置都包含在此标签内。
-
-
<properties resource="jdbc.properties"/>
-
引入外部属性文件
jdbc.properties
,用于解耦敏感配置(如数据库连接信息)。 -
文件中的键值(如
jdbc.driver
)可在后续配置中通过${key}
语法引用。
-
-
<environments default="dev">
-
定义多个环境配置(如开发、测试、生产),
default
指定默认使用的环境 ID(此处为dev
)。
-
-
<environment id="dev">
-
定义一个具体环境配置,ID 为
dev
,与default
匹配,表示默认使用此环境。
-
-
<transactionManager type="JDBC"/>
-
设置事务管理器类型为
JDBC
,表示使用 JDBC 原生事务管理(手动提交/回滚)。 -
另一可选值为
MANAGED
(依赖容器管理事务,如 JavaEE 应用服务器)。
-
-
<dataSource type="POOLED">
-
配置数据源类型为
POOLED
,表示使用连接池管理数据库连接,提高性能。 -
其他可选类型:
UNPOOLED
(无连接池)、JNDI
(从容器获取数据源)。
-
-
<property name="driver" value="${jdbc.driver}"/>
-
数据库驱动类名,值从
jdbc.properties
的jdbc.driver
键获取(如com.mysql.cj.jdbc.Driver
)。
-
-
<property name="url" value="${jdbc.url}"/>
-
数据库连接 URL,值从
jdbc.properties
的jdbc.url
键获取(如jdbc:mysql://localhost:3306/mydb
)。
-
-
<property name="username" value="${jdbc.user}"/>
-
数据库用户名,值来自
jdbc.properties
的jdbc.user
键。
-
-
<property name="password" value="${jdbc.password}"/>
-
数据库密码,值来自
jdbc.properties
的jdbc.password
键。
-
-
</dataSource>
-
结束数据源配置。
-
-
</environment>
-
结束环境配置。
-
-
</environments>
-
结束所有环境配置。
-
-
<mappers>
-
定义 SQL 映射文件(Mapper XML)的位置,MyBatis 通过这些文件将 Java 接口方法与 SQL 语句绑定。
-
-
<mapper resource="CarMapper.xml"/>
-
指定类路径下的
CarMapper.xml
文件作为映射文件,通常包含<select>
,<insert>
等 SQL 语句配置。
-
-
</mappers>
-
结束映射文件配置。
-
-
</configuration>
这边再把jdbc.properties准备好同样放到
resources文件里面
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/后面添加要连接的数据库
jdbc.user=这边设置自己的数据库名字
jdbc.password=密码
第四步、创建CarMapper.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"> 这个是指定这个配置的名字,后面Java代码中要用 <mapper namespace="bzd"> 这里面可以写sql语句 </mapper>
我们在<mapper namespace="bzd"> </mapper>标签里面添加sql语句
<insert id="insertCar"> 设置id名字后面Java代码要用 insert into t_cat(car_num, brand, guide_price, produce_time, car_type) VALUES(#{num},#{brand},#{price},#{date},#{type}) 把Java代码里面的数据传过来用#{}接收,括号里面写Java发过来的属性名 </insert> resultType后面写查询出来的类的全路径类名 <select id="sc" resultType="org.example.cat"> select * from t_cat where id = #{c} 当只有一个#{}的时候括号里面的名字随意 </select> <update id="up"> update t_cat set car_num = #{num}, brand = #{brand}, guide_price = #{price}, produce_time = #{date}, car_type = #{type} where id = #{id} </update>
完整代码
<?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="bzd">
<insert id="insertCar">
insert into t_cat(car_num, brand, guide_price, produce_time, car_type)
VALUES(#{num},#{brand},#{price},#{date},#{type})
</insert>
<select id="sc" resultType="org.example.Cat">
select * from t_cat where id = #{c}
</select>
<update id="up">
update t_cat set
car_num = #{num}, brand = #{brand},
guide_price = #{price}, produce_time = #{date},
car_type = #{type}
where id = #{id}
</update>
</mapper>
第五步、编写Java代码
@Test
public void test01() throws IOException {
//创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//获取mybatis-config.xml核心文件内容
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
//获取SqlSessionFactory,获取CarMapper.xml里面的sql语句,注意这里面要是#{}里面没有东西会报错
SqlSessionFactory build = builder.build(reader);
//获取数据库操作对象
SqlSession sqlSession = build.openSession();
//添加cat对象
Cat cat = new Cat( "cac", "ryc", 10.0, "2001-12-5", "ryc");
//运行sql语句bzd.up是我们之前在CarMapper.xml文件里面设置的,这样可以让Mybatis知道我们要运行哪一行代码,Cat是我们传入要添加的数据
int o = sqlSession.update("insertCar",cat);
//上传数据
sqlSession.commit();
//刷新
sqlSession.close();
System.out.println(o);
}
Cat.class
package org.example;
import java.sql.Date;
public class Cat {
private Long id;
private String num;
private String brand;
private Double price;
private String date;
private String type;
public Cat() {
}
public Cat(Long id, String num, String brand, Double price, String date, String type) {
this.id = id;
this.num = num;
this.brand = brand;
this.price = price;
this.date = date;
this.type = type;
}
public Cat(String num, String brand, Double price, String date, String type) {
this.num = num;
this.brand = brand;
this.price = price;
this.date = date;
this.type = type;
}
@Override
public String toString() {
return "cat{" +
"id=" + id +
", num='" + num + '\'' +
", brand='" + brand + '\'' +
", price=" + price +
", date=" + date +
", type='" + type + '\'' +
'}';
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}