<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.10version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.30version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>2.0.0version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-classicartifactId>
<version>1.2.11version>
<scope>testscope>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-coreartifactId>
<version>1.2.11version>
dependency>
dependencies>
在maven项目的resources文件夹下新建一个mybatis-config.xml文件,将以下内容复制进去,同时修改配置信息
${driver}:com.mysql.jdbc.Driver${url}:数据库url${username}:数据库用户名${password}:数据库密码留到下一部分修改
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="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
mappers>
configuration>
mappers 元素包含了一组映射器(mapper),这些映射器的 XML 映射文件包含了 SQL 代码和映射定义信息。
由于在上一篇jdbc的文章中我们创建了一个student表(name: String, age: int),因此我们创建一个StudentMapper.xml。
这是官网的例子
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
select>
mapper>
我们做一些修改:
namespace暂时改为testid修改为selectAll,表示我们将通过这个映射获取表中的全部信息,当然它也可以是其他的名字java/features文件夹中创建一个Student类与我们创建的表对应,然后将resultType值修改为类的路径features.Studentselect * from student;,不再赘述mybatis-config.xml中填我们刚刚挖的坑,将resource的值修改为StudentMapper.xml的路径:
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test">
<select id="selectAll" resultType="features.Student">
select * from student;
select>
mapper>
由于我们的student表中就两列,因此成员变量设置如下:
private String name;
private int age;
然后为该类的所有成员变量设置默认的getter和setter方法即可,最后在添加一个toString()方法。
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
List<Student> students = sqlSession.selectList("test.selectAll");
System.out.println(students);
test:StudentMapper.xml里的namespaceselectAll:查询映射的唯一标识sqlSession.close()
[Student{name='Lily', age=22}, Student{name='Tom', age=23}]