配置MyBatis环境的步骤
1.引入MyBatis依赖(jar包)
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
2.引入数据库依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
3.配置tomcat组件
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<configuration>
<path>/</path>
<port>8080</port>
<uriEncoding>UTF-8</uriEncoding>
</configuration>
</plugin>
4.在resources下配置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">
<!--事务管理器,使用jdbc默认的事务处理-->
<transactionManager type="JDBC"/>
<!--
数据源:
type:数据库连接池(druid,c3p0)
POOLED:是mybatis自带的连接池
-->
<dataSource type="POOLED">
<!-- 配置数据库 -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/2001"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--mapper文件配置(专门写sql)-->
<mappers>
<mapper resource="mapper/UserDao.xml"/>
</mappers>
</configuration>
<environments default="">
存放多个数据库环境
<environment id="">
<!--事务管理器,使用jdbc的事务处理-->
<transactionManger type="JDBC"/>
<!--
数据源:存放连接数据库所需参数
type:数据库连接池的类型(druid,c3p0)
-->
<dataSource type="POOLED">
<!-- 配置数据库 -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/2001"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSouce>
<environment>
</environments>
<mappers>
<mapper resources="Dao接口实现代理的xml文件地址">
<mappers>
5.创建接口的实现类的配置文件
<?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.lqq.dao.UserDao">
<!--
select主要用来查询
id:和接口中的方法名保持一致
resultType:方法返回值类型的全类名
#{id}:动态获取方法的参数
-->
<select id="findUserById" resultType="com.lqq.entity.User">
select * from t_user where id =#{id}
</select>
</mapper>
<mapper namespace="对应所实现接口的全类名">
<select id="接口中的方法名" resultType="返回对象的全类名">
sql 语句 ${传入方法参数名}
</select>
</mapper>