一、准备工作
详情参考:https://blog.csdn.net/hznb_369/article/details/121039732. 不想引入jar或者找不到jar包可以在pom.xml添加依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
二、实体类的创建
- Employee
import lombok.Data;
@Data
public class Employee {
private Integer id;
private String lastName;
private String gender;
private String email;
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName='" + lastName + '\'' +
", gender='" + gender + '\'' +
", email='" + email + '\'' +
'}';
}
}
- EmployeeMapper
public interface EmployeeMapper {
public Employee getEmpById(Integer id);
}
- 需要映射的配置文件EmployeeMapper.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">
<mapper namespace="com.znb.mapper.EmployeeMapper">
<select id="getEmpById" resultType="employee" databaseId="mysql">
select * from tbl_employee where id = #{id}
</select>
</mapper>
三、测试
public class MybatisTest {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
public MybatisTest() throws IOException {
}
@Test
public void test1(){
try {
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
Employee empById = mapper.getEmpById(1);
System.out.println(empById);
}finally {
sqlSession.close();
}
}
}
测试结果
|