一、导入相关的jar
网上百度相关版本即可。
二、在 src 下新建全局配置文件
在全局配置文件中引入 DTD 或 schema,然后具体些mybatis的配置信息(最基本的配置)
主要是:1.配置数据库连接的数据源,相当于在原生的JBDC中的创建Connection对象的过程,所需要的数据源。
2.声明mapper.xml的位置,方便mybatis配置文件的查找和加载。(mapper.xml在mapper层包下,相当于原生MVC的dao层,只是mybatis中不用去手动执行sql语句,只需要在相应的mapper.xml中写好sql语句,mybatis就会自动帮我们去执行相关的操作。)
一个mybatis的全局配置文件的示例。mybatis.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="default">
<!--需要配置的环境-->
<environment id="default">
<!--事务管理选择的是JBDC方式-->
<transactionManager type="JDBC"></transactionManager>
<!--数据源的来源选择数据库连接池即:POOLED-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/my01"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-—声明配置sql语句xml文件的位置-->
<mappers>
<mapper resource="cn/liu/mapper/FlowerMapper.xml"/>
</mappers>
</configuration>
mapper.xml一般是配置sql语句的。
来一个示例:
<?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是命名空间,调用具体SQL命令需要使用namespace,一般是包名+接口名-->
<mapper namespace="a">
<!--id是这条sql语句的名称,resultType是查询得到的结果类型-->
<select id="sellAll" resultType="cn.liu.pojo.Flower">
select * from flower
</select>
<select id ="selByid" resultType="int" >
select count(*) from flower
</select>
<select id="selMap" resultType="cn.liu.pojo.Flower">
select * from flower
</select>
</mapper>