mybatis 配置及应用

maven 构建项目

1. 添加依赖

spring-webmvc
mybatis
mysql-connector-java
mybatis-spring
junit

pom.xml 文件内容如下:
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5     <parent>
 6         <artifactId>springStudy</artifactId>
 7         <groupId>org.example</groupId>
 8         <version>1.0-SNAPSHOT</version>
 9     </parent>
10     <modelVersion>4.0.0</modelVersion>
11 
12     <artifactId>mybatis-01</artifactId>
13 
14     <properties>
15         <maven.compiler.source>8</maven.compiler.source>
16         <maven.compiler.target>8</maven.compiler.target>
17     </properties>
18 
19     <dependencies>
20 
21         <dependency>
22             <groupId>org.springframework</groupId>
23             <artifactId>spring-webmvc</artifactId>
24             <version>5.3.7</version>
25         </dependency>
26 
27         <dependency>
28             <groupId>org.mybatis</groupId>
29             <artifactId>mybatis</artifactId>
30             <version>3.4.6</version>
31         </dependency>
32 
33         <dependency>
34             <groupId>mysql</groupId>
35             <artifactId>mysql-connector-java</artifactId>
36             <version>5.1.49</version>
37         </dependency>
38 
39         <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
40         <dependency>
41             <groupId>org.mybatis</groupId>
42             <artifactId>mybatis-spring</artifactId>
43             <version>1.3.2</version>
44         </dependency>
45         <dependency>
46             <groupId>junit</groupId>
47             <artifactId>junit</artifactId>
48             <version>RELEASE</version>
49             <scope>test</scope>
50         </dependency>
51 
52     </dependencies>
53 
54     <build>
55         <!-- 定义classpath -->
56         <resources>
57             <!-- resources文件 -->
58             <resource>
59                 <directory>src/main/resources</directory>
60                 <!-- 是否被过滤,如果被过滤则无法使用 -->
61                 <filtering>false</filtering>
62             </resource>
63             <!-- java文件夹 -->
64             <resource>
65                 <directory>src/main/java</directory>
66                 <!-- 引入映射文件等 -->
67                 <includes>
68                     <include>**/*.xml</include>
69                     <include>**/*.properties</include>
70                 </includes>
71             </resource>
72         </resources>
73     </build>
74 
75 </project>
pom.xml

其中<build><resource>中内容为过滤项目中 xml 文件和 properties 文件的设置,否则运行时项目中 xml 文件或 properties 文件会加载不到。

2. 创建实体类

以 User 为例,代码如下:

 1 package com.xsmile.pojo;
 2 
 3 import java.util.List;
 4 
 5 public class User {
 6     private int id;
 7     private String name;
 8     private String password;
 9 
10     public User() {
11     }
12 
13     public User(int id, String name, String password) {
14         this.id = id;
15         this.name = name;
16         this.password = password;
17     }
18 
19     public int getId() {
20         return id;
21     }
22 
23     public void setId(int id) {
24         this.id = id;
25     }
26 
27     public String getName() {
28         return name;
29     }
30 
31     public void setName(String name) {
32         this.name = name;
33     }
34 
35     public String getPassword() {
36         return password;
37     }
38 
39     public void setPassword(String password) {
40         this.password = password;
41     }
42 
43     @Override
44     public String toString() {
45         return "User{" +
46                 "id=" + id +
47                 ", name='" + name + '\'' +
48                 ", password='" + password + '\'' +
49                 '}';
50     }
51 }
User

3. 数据库准备

创建项目使用的数据库如 mybatis,User 对应的表 user。如图所示,实体类中变量名与数据库中列明一一对应。

 

4. 配置mybatis-config文件

通用模板,只需根据自身数据库、表、用户名及密码进行修改即可。

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4         "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6     <environments default="development">
 7         <environment id="development">
 8             <transactionManager type="JDBC"/>
 9             <dataSource type="POOLED">
10                 <property name="driver" value="com.mysql.jdbc.Driver"/>
11                 <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=UTF-8"/>
12                 <property name="username" value="root"/>
13                 <property name="password" value="xjw123456"/>
14             </dataSource>
15         </environment>
16     </environments>
17     <mappers>
18         <mapper resource="com/xsmile/dao/UserMapper.xml"/>
19     </mappers>
20 </configuration>
mybatis-config.xml

值得注意的是最后 <mapper> resource 中需要添加指定的接口实现类 xml 文件

5. 创建接口UserMapper

接口包含查询方法,获取表中所有用户信息。

1 public interface UserMapper {
2     public List<User> getUsers();
3 }
UserMapper

6. 创建实现类

实现类转由 xml 文件进行配置实现

1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE mapper
3         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
4         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
5 <mapper namespace="com.xsmile.dao.UserMapper">
6     <select id="getUsers" resultType="com.xsmile.pojo.User">
7         select * from user
8     </select>
9 </mapper>
UserMapper.xml

命名空间 namespace 指向接口全路径,id 为要实现接口的方法名对应,resultType 为结果对象全类名的形式。

7. sqlSession 工具类

由于 sqlSession 代码统一,编写为一个工具类,方便以后使用。

 1 package com.xsmile.util;
 2 
 3 import org.apache.ibatis.io.Resources;
 4 import org.apache.ibatis.session.SqlSession;
 5 import org.apache.ibatis.session.SqlSessionFactory;
 6 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 7 
 8 import java.io.IOException;
 9 import java.io.InputStream;
10 
11 public class MybatisUtil {
12     private static SqlSessionFactory sqlSessionFactory;
13         static {
14             String resource = "mybatis-config.xml";
15             InputStream inputStream;
16             try {
17                 inputStream = Resources.getResourceAsStream(resource);
18                 sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
19             } catch (IOException e) {
20                 e.printStackTrace();
21             }
22         }
23 
24 
25     public static SqlSession getSqlSession(){
26         return sqlSessionFactory.openSession();
27     }
28 
29 }
MybatisUtil

后续使用只需调用类方法即可获取 sqlSession,即:

MybatisUtil.getSqlSession()

8. 编写测试类

 1 package com.xsmile.dao;
 2 
 3 import com.xsmile.pojo.User;
 4 import com.xsmile.util.MybatisUtil;
 5 import org.apache.ibatis.session.SqlSession;
 6 import org.junit.Test;
 7 
 8 import java.util.List;
 9 
10 public class UserMapperTest {
11 
12     @Test
13     public void test(){
14 
15         SqlSession sqlSession = MybatisUtil.getSqlSession();
16 
17         UserMapper mapper = sqlSession.getMapper(UserMapper.class);
18 
19         List<User> users = mapper.getUsers();
20 
21         for (User user : users) {
22             System.out.println(user);
23         }
24 
25 
26     }
27 }
UserMapperTest

其中 sqlSession.getMapper() 为官方推荐方法,它不依赖于字符串字面值,会更安全一点。另外方法如:

List<User> users1 = sqlSession.selectList("com.xsmile.dao.UserMapper.getUsers");

执行结果如下:

1 User{id=1, name='xsmile', password='123456'}
2 User{id=2, name='sophia', password='123456'}
3 User{id=3, name='alex', password='123456'}
4 User{id=4, name='jerry', password='123456'}
5 User{id=5, name='俊伟君', password='123456'}
result

 

posted @ 2021-08-17 17:10  x_smile  阅读(253)  评论(1编辑  收藏  举报