1.第一个MyBatis程序
5.在工具类中,通过4中的配置文件参数生成的SqlSessionFactory获得SqlSession
9.解决Type interface XXX is not known to the MapperRegistry错误问题
10.解决Could not find resource XXX.xml错误问题
create database MyBatis; use MyBatis; create table student( sno char(12) primary key not null, sname varchar(20), age int, sex char(2), address varchar(50) )
插入以下数据

jdbc:mysql://localhost:3306/MyBatis

<!--导入依赖-->
<dependencies>
<!--MySql驱动架包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--MyBatis架包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--单元测试架包-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
</dependencies>

XML 配置文件中包含了MyBatis 系统的核心设置,包括获取数据库连接实例的数据源(DataSource)以及决定事务作用域和控制方式的事务管理器(TransactionManager)。
<?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核心配置文件--> <!-- 配置文件的根元素 --> <configuration> <settings> <!-- 使全局的映射器启用或禁用缓存。 --> <setting name="cacheEnabled" value="true"/> <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 --> <setting name="lazyLoadingEnabled" value="true"/> <!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载。 --> <setting name="aggressiveLazyLoading" value="true"/> <!-- 是否允许单条sql 返回多个数据集 (取决于驱动的兼容性) default : true --> <setting name="multipleResultSetsEnabled" value="true"/> <!-- 是否可以使用列的别名 (取决于驱动的兼容性) default : true --> <setting name="useColumnLabel" value="true"/> <!-- 允许JDBC 生成主键。需要驱动器支持。如果设为了 true ,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。 default : false --> <setting name="useGeneratedKeys" value="true"/> <!-- 指定 MyBatis 如何自动映射 数据基表的列 NONE:不隐射 PARTIAL:部分 FULL:全部 --> <setting name="autoMappingBehavior" value="PARTIAL"/> <!-- 这是默认的执行类型 (SIMPLE: 简单; REUSE: 执行器可能重复使用prepared statements语句;BATCH: 执行器可以重复执行语句和批量更新) --> <setting name="defaultExecutorType" value="SIMPLE"/> <!-- 使用驼峰命名法转换字段。 --> <setting name="mapUnderscoreToCamelCase" value="true"/> <!-- 设置本地缓存范围 session:就会有数据的共享 statement:语句范围 (这样就不会有数据的共享 ) defalut:session --> <setting name="localCacheScope" value="SESSION"/> <!-- 设置但JDBC类型为空时,某些驱动程序 要指定值, default :OTHER,插入空值时不需要指定类型 --> <setting name="jdbcTypeForNull" value="NULL"/> <!-- 启动什么日志 --> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <!--配置别名--> <typeAliases> </typeAliases> <!-- 和spring整合后 environments配置将废除 --> <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/mybatis?useSSL=false"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> </configuration>

5.在工具类中,通过4中的配置文件参数生成的SqlSessionFactory获得SqlSession
构建SqlSessionFactory实例
从XML 文件中构建 SqlSessionFactory 的实例
每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的
SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得
SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例
MyBatis 包含一个名叫 Resources 的工具类,使得从类路径或其它位置加载资源文件更加容易。
package com.user102; 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; public class Utils { private static SqlSessionFactory sqlSessionFactory; static{ try { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }


以上代码SqlSessionFactoryBuilder为局部变量,静态代码块执行完毕后xml解析资源将被释放,给其他需要的程序,SqlSessionFactory采用了饿汉单例模式,类初始化的时候创建一次,不会重复创建。getSqlSession拿到SqlSession使用完后应尽快关闭SqlSession

package com.user102.pojo; public class Student { private String sno; private String sname; private int age; private String sex; private String address; @Override public String toString() { return "Student{" + "sno='" + sno + '\'' + ", sname='" + sname + '\'' + ", age=" + age + ", sex='" + sex + '\'' + ", address='" + address + '\'' + '}'; } public void setSno(String sno) { this.sno = sno; } public void setSname(String sname) { this.sname = sname; } public void setAge(int age) { this.age = age; } public void setSex(String sex) { this.sex = sex; } public void setAddress(String address) { this.address = address; } public String getSno() { return sno; } public String getSname() { return sname; } public int getAge() { return age; } public String getSex() { return sex; } public String getAddress() { return address; } }

package com.user102.dao; import com.user102.pojo.Student; import java.util.List; public interface StudentMapper { public List <Student> getAllStudent(); }

<?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.user102.dao.StudentMapper"> <!--select查询语句--> <select id="getAllStudent" resultType="com.user102.pojo.Student"> select * from mybatis.student </select> </mapper>

package com.user102; import com.user102.dao.StudentMapper; import com.user102.pojo.Student; import org.apache.ibatis.session.SqlSession; import java.util.List; public class Test { @org.junit.Test public void test(){ SqlSession sqlSession = Utils.getSqlSession(); StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); List <Student> allStudent = mapper.getAllStudent(); System.out.println(allStudent); } }
Type interface XXX is not known to the MapperRegistry错误
9.解决Type interface XXX is not known to the MapperRegistry错误问题
核心配置文件中未注册 mapper,在mybatis-config.xml中加入以下代码
<mappers>
<mapper resource="com/user102/dao/StudentMapper.xml"></mapper>
</mappers>

再次测试,出现以下错误

10.解决Could not find resource XXX.xml错误问题
未找到资源文件,由于Maven可能存在资源过滤的问题,我们将配置如下完善,在pom.xml中加入以下配置
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>

再次测试:

文件目录:


浙公网安备 33010602011771号