新建一个maven项目或spring项目或直接导入jar包,新建一个什么项目不重要,不同的只是引入依赖的方式
(似乎是spring约定大于配置的缘故,同样的配置方法在使用maven时能成功,使用spring就会出错,spring集成mybatis还要再学习一下)
需要的依赖有:mybatis,mysql数据库驱动
在Resource目录下,新建一个conf目录,在conf目录下新建一个mybatis-config.xml文件
<?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/test_mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/EmployeeMapper.xml"/>
</mappers>
</configuration>
注意,使用旧版mysql connector时,需要指定useSSL,且值为false
也可以使用新版,需指定时区
填好数据库连接信息
填好mapper映射文件的路径。据说idea构建的maven项目,只能解析到resource目录下的xml文件,所以mapper映射文件也写在resource目录下
编写mapper映射文件
<?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">
<mapper namespace="a">
<select id="selectAll" resultType="com.mybatis.pojo.Employee">
select *from tbl_employee where id = #{id}
</select>
</mapper>
执行SQL语句的方式是命名空间+SQL语句的id,这里还没用到接口编程,namespace可以随便写
id是sql语句的唯一标识,resultType是Sql语句将返回的resultSet映射成resultType这种类型,映射就体现于此了!
如果没有写resultmap,那这个resultType就要写全。
最后写一下执行sql语句的方法。
public static void test()throws IOException
{
String resource = "conf/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
Employee employee = session.selectOne("a.selectAll",1);
System.out.println(employee);
}finally {
}
}
session.selectOne, 这个session所包含的方法是mybatis规定的,与我们在mapper.xml中定义的sql语句无关,方法名不是id名,我们所设定的id名,作为参数传给session类的方法。
mapper.xml的参数含义:
namespace:在调用sql语句的时候,需要给定sql语句的命名空间,即由命名空间加sql的id来确定调用哪个sql语句。为什么会有命名空间的存在?设想一下,如果不止一个mapper.xml,而他们含有相同的sql id,这个时候就会产生冲突。在不使用接口编程的情况下,命名空间的命名应该是随便的。如果使用了面向接口编程,编写了dao层接口,那应该保持dao层接口名字和命名空间一致。还要保持dao接口方法名与sql id一致。
resultType:将SQL语句查询的结果集映射成resultType的对象,如果没有设置resultmap的话,需要写resultType的全路径。
当使用了resultMap来映射的时候,sql标签里面不应该写resultType,而应该写resultMap
作者:北征愚人