MyBatis工程搭建 中我们使用的是JDBC 方式执行 SQL 语句连接数据库,但在实际应用中是不会选择 JDBC 来执行 SQL 的,MyBatis 提供了 Mapper 作为 Java 方法和 SQL 语句之间的桥梁,来帮助我们更好地去使用 SQL
Java 接口方法与 SQL 语句以及 mapper 之间的关系如下图所示:
<?xml version="1.0" encoding="UTF-8"?>
<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>org.example</groupId>
<artifactId>zhangyichen4</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.3.0-alpha5</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
添加对应的mapper配置
<?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://localhost:3306/javaweb?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="362522"/>
</dataSource>
</environment>
</environments>
<!-- mapper配置 -->
<mappers>
<mapper class="mapper.UserMapper"/>
</mappers>
</configuration>
package mapper;
import entity.User;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
/**
* 通过用户id查询用户名称
*
* @param id 用户id
* @return 用户名称
*/
@Select("SELECT username FROM user WHERE id = #{id}")
}
import entity.User;
import mapper.UserMapper;
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.sql.SQLException;
@SuppressWarnings({"Duplicates"})
public class UserTest {
public static void main(String[] args) throws IOException , SQLException{
// 读取配置文件
InputStream configuration = Resources.getResourceAsStream("mybatis-config.xml");
// 得到 SqlSessionFactory 核心类
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
// 开始一个 sql 会话
SqlSession session = sqlSessionFactory.openSession();
// 得到 mapper
UserMapper mapper = session.getMapper(UserMapper.class);
// 调用注解的SQL
String username = mapper.selectUsernameById(1);
System.out.println("username: " + username);
// 关闭会话
session.close();
}
}
XML方式是更加强大的一种使用方式,虽然它没有注解那么方便,但是功能更强、更易维护,是 MyBatis 官方推荐的一种方式
在 UserMapper 接口中,我们再新增一个方法selectUserAgeById,该方法的作用是通过用户id查询用户年龄
package mapper;
import entity.User;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
/**
* 通过用户id查询用户名称
*
* @param id 用户id
* @return 用户名称
*/
@Select("SELECT username FROM user WHERE id = #{id}")
String selectUsernameById(Integer id);
/**
* 通过用户id查询用户年龄
*
* @param id 用户id
* @return 用户年龄
*/
Integer selectUserAgeById(Integer 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="mapper.UserMapper">
<select id="selectUserAgeById" resultType="java.lang.Integer">
SELECT age FROM user WHERE id = #{id}
</select>
</mapper>
select 标签中有两个必填属性:
id:对应接口的方法名,即 selectUserAgeById,通过它 MyBatis 才能将二者对应起来
resultType:对应 SQL 语句的返回类型,与接口方法的返回值相同,有时会用到resultMap
import entity.User;
import mapper.UserMapper;
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.sql.SQLException;
@SuppressWarnings({"Duplicates"})
public class UserTest {
public static void main(String[] args) throws IOException , SQLException{
// 读取配置文件
InputStream configuration = Resources.getResourceAsStream("mybatis-config.xml");
// 得到 SqlSessionFactory 核心类
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
// 开始一个 sql 会话
SqlSession session = sqlSessionFactory.openSession();
// 得到 mapper
UserMapper mapper = session.getMapper(UserMapper.class);
// 调用注解的SQL
String username = mapper.selectUsernameById(1);
System.out.println("username: " + username);
// 调用XML的SQL
Integer age = mapper.selectUserAgeById(1);
System.out.println("age: " + age);
// 关闭会话
session.close();
}
}
新增 selectUserById 标签,该 select 标签的作用是:通过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="mapper.UserMapper">
<select id="selectUserAgeById" resultType="java.lang.Integer">
SELECT age FROM user WHERE id = #{id}
</select>
<select id="selectUserById" resultMap="userMap">
SELECT * FROM user WHERE id = #{id}
</select>
<resultMap id="userMap" type="entity.User">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="age" column="age"/>
<result property="score" column="score"/>
</resultMap>
</mapper>
package entity;
public class User {
private Integer id;
private String username;
private Integer age;
private Integer score;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", age=" + age +
", score=" + score +
'}';
}
}
package mapper;
import entity.User;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
/**
* 通过用户id查询用户名称
*
* @param id 用户id
* @return 用户名称
*/
@Select("SELECT username FROM user WHERE id = #{id}")
String selectUsernameById(Integer id);
/**
* 通过用户id查询用户年龄
*
* @param id 用户id
* @return 用户年龄
*/
Integer selectUserAgeById(Integer id);
/**
* 通过用户id查询用户信息
*
* @param id
* @return
*/
User selectUserById(Integer id);
}
import entity.User;
import mapper.UserMapper;
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.sql.SQLException;
@SuppressWarnings({"Duplicates"})
public class UserTest {
public static void main(String[] args) throws IOException , SQLException{
// 读取配置文件
InputStream configuration = Resources.getResourceAsStream("mybatis-config.xml");
// 得到 SqlSessionFactory 核心类
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
// 开始一个 sql 会话
SqlSession session = sqlSessionFactory.openSession();
// 得到 mapper
UserMapper mapper = session.getMapper(UserMapper.class);
// 调用注解的SQL
String username = mapper.selectUsernameById(1);
System.out.println("username: " + username);
// 调用XML的SQL
Integer age = mapper.selectUserAgeById(1);
System.out.println("age: " + age);
// 调用通过用户id查询用户信息的方法
User user = mapper.selectUserById(1);
System.out.println(user);
// 关闭会话
session.close();
}
}