学习MyBatis已经很久了,也一直在使用,今天抽空来总结下MyBatis的基本使用,MyBatis真的是很好入门的,看完这篇文章基本上就能正常使用MyBatis了
首先创建一个Maven项目
如果还有不会使用Maven的同学可以去看我之前写的Maven配置
这是我的项目结构
- 首先引入相应的pom.xml依赖,笔者这里用的是mysql8.0,如果使用的是5.7的同学引入5.7的以来就可以了
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xx</groupId>
<artifactId>Demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</project>
2.撰写MyBatis的配置文件mybatis-config.xml,由于数据库存在时区问题,需要在url后面对时区进行修改
<?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>
<settings>
<!-- 开启驼峰命名去匹配数据库字段 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<environments default="dev">
<environment id="dev">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/next-shop?serverTimezone=GMT%2B8" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="AreaMapper.xml" />
</mappers>
</configuration>
3.创建实体类Area.java
package com.xx.entity;
public class Area {
private Integer areaId;
private String areaName;
private String cityCode;
private String address;
public Integer getAreaId() {
return areaId;
}
public void setAreaId(Integer areaId) {
this.areaId = areaId;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public String getCityCode() {
return cityCode;
}
public void setCityCode(String cityCode) {
this.cityCode = cityCode;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Area [areaId=" + areaId + ", areaName=" + areaName + ", cityCode=" + cityCode + ", address=" + address
+ "]";
}
}
4.这时候我们开始编写映射文件AreaMapper.xml,这里写了6种最常见的情况,其中使用Map是最为强大的,基本上是万能的,适用于任何情况
<?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="AreaMapper">
<select id="findById" parameterType="Integer" resultType="com.xx.entity.Area">
select * from bas_area where area_id = #{areaId}
</select>
<select id="findAll" resultType="com.xx.entity.Area">
select * from bas_area
</select>
<insert id="insert" parameterType="com.xx.entity.Area">
insert into bas_area(city_code,area_name,address) values (#{cityCode},#{areaName},#{address})
<selectKey resultType="Integer" keyProperty="areaId" order="AFTER">
select last_insert_id()<!-- 获取最新插入数据的id -->
</selectKey>
</insert>
<update id="update" parameterType="com.xx.entity.Area">
update bas_area set city_code = #{cityCode},area_name = #{areaName},address = #{address} where area_id = #{areaId}
</update>
<delete id="delete" parameterType="Integer">
delete from bas_area where area_id = #{area_id}
</delete>
<select id="findByMap" resultType="java.util.Map">
select * from bas_area a,bas_dictionary b where a.city_code = b.dic_code and b.dic_type = 'city'
</select>
</mapper>
5.创建JunitDemo.java进行单元测试
package com.xx.junit;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import java.util.Map;
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 com.xx.entity.Area;
public class JunitDemo {
private static SqlSession session = null;
// 静态块
static{
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");// 读取MyBatis配置文件
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);// SqlSessionFactory是很消耗系统资源的一般只创建一次,所以这里将SqlSessionFactory抽取出来放到静态块中初始化
session = factory.openSession();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
// 查询
public void findAll() throws IOException {
List<Area> list = session.selectList("AreaMapper.findAll");
for (Area area : list) {
System.out.println(area);
}
session.close();
}
@Test
// 条件查询
public void findById() {
Area area = session.selectOne("AreaMapper.findById", 1);
System.out.println(area);
}
@Test
// 插入
public void insert() throws IOException {
Area area = new Area();
area.setAreaName("天通苑");
area.setCityCode("bj");
area.setAddress("天通苑");
session.insert("AreaMapper.insert",area);
session.commit();// 提交事务
session.close();
}
@Test
// 修改
public void update() {
Area area = session.selectOne("AreaMapper.findById", 1);
area.setAreaName("铂金时代");
area.setCityCode("hz");
area.setAddress("江南大道");
session.update("AreaMapper.update", area);
session.commit();
session.close();
}
@Test
// 删除
public void delete() {
session.delete("AreaMapper.delete",3);
session.commit();
session.close();
}
@Test
// 无敌的Map
public void findByMap() {
List<Map<String,Object>> list = session.selectList("AreaMapper.findByMap");
for (Map<String, Object> map : list) {
System.out.println(map);
}
session.close();
}
}