Mybatis持久层框架初步学习
如何获取Mybatis
maven仓库
<!-- mybatis -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
编写Mybatis程序
搭建环境 -> 导入Mybatis -> 编写代码进行测试第1部分
1.新建普通的Maven项目
2.删除src目录
3.导入maven依赖
1.内嵌新模块,编写mybatis核心配置文件
2.编写mybatis工具类
3.编写代码
实体类 Dao接口 配置文件 注册Mapper 配置资源过滤
编写实体类
package com.bkms.pojo;
public class Info {
private int id;
private String name;
private String email;
public Info() {
}
public Info(int id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
@Override
public String toString() {
return "Info{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
'}'; }
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
编写Dao接口
package com.bkms.dao;
import com.bkms.pojo.Info;
import java.util.List;
public interface InfoDao {
List<Info> getInfoList();
}
编写配置文件
<?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">
<!-- namespace命名空间 绑定对应的Mapper接口 -->
<mapper namespace="com.bkms.dao.InfoDao">
<!--
id对应接口方法名
select标签对应以前实现类实现接口的方法
resultType处理结果集对应实现类的ResultSet
-->
<select id="getInfoList" resultType="com.bkms.pojo.Info">
select * from mydb.info
</select>
</mapper>
注册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.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="140246"/>
</dataSource>
</environment>
</environments>
<!--
每一个Mapper.xml需要在Mybatis核心配置文件里面注册
-->
<mappers>
<mapper resource="com/bkms/dao/InfoMapper.xml"></mapper>
</mappers>
<!--<mappers>-->
<!--<mapper resource="org/mybatis/example/BlogMapper.xml"/>-->
<!--</mappers>-->
</configuration>
手动配置资源过滤操作,为保险起见,父工程与子工程都需要配置
<build>
<resources>
<!-- 资源过滤配置 -->
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/*.properties</exclude>
<exclude>**/*.xml</exclude>
</excludes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
单元测试
注意点:
mybatis-config.xml文件不能有中文注释
资源文件config需要与main目录同级