近日要开始MyBatis的学习了,首先第一件事当然是看官方文档啦
创建maven工程
名称任意,创一个最简单的maven工程就好了
引入MyBatis
在pom.xml中加入MyBatis依赖和数据库驱动,我这里用的是mysql1
2
3
4
5
6
7
8
9
10
11<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>x.x.x</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
x.x.x填的是MyBatis的版本号,目前最新稳定版是3.4.6
编写配置文件
由xml构建SqlSessionFactory,首先编写XML配置,以下所有中文均改成自己的配置1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="数据库驱动"/>
<property name="url" value="url地址"/>
<property name="username" value="用户名"/>
<property name="password" value="密码"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper路径"/>
</mappers>
</configuration>
编写mapper配置文件:1
2
3
4
5
6
7
8
9<?xml version="1.0" encoding="UTF-8" ?>
<mapper namespace="org.mybatis.example.BlogMapper">
<select id="selectUser" resultType="com.yhzl.bean.User">
select * from User where id = #{id}
</select>
</mapper>
编写实体类及测试类
实体类:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44package com.yhzl.bean;
/**
* @author chsm
* @date 2018年4月4日上午8:30:32
* @version 1.0
*/
public class User {
private Integer id;
private String username;
private String password;
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString() {
return "User [id=" + id + ", username=" + username + ", password="
+ password + "]";
}
}
测试类:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28package com.yhzl.test;
import java.io.IOException;
import java.io.InputStream;
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 com.yhzl.bean.User;
/**
* @author chsm
* @date 2018年4月4日上午8:33:13
* @version 1.0
*/
public class Test {
public static void main(String[] args) throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sessionFactory.openSession();
User user = session.selectOne("org.mybatis.example.BlogMapper.selectUser", 1);
System.out.println(user);
}
}
对代码的编写已经完成了此时可以运行了,如果出现报错等情况,请检查下代码看看有没有写错