pom.xml:
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.20</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
log4j.properties:
#全局配置
log4j.rootLogger=DEBUG,console
#debug 测试阶段使用
#控制台日志输出
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%p] %m %n
jdbc.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.username=root
jdbc.password=123456
mybatisConfig.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">
<!--mybatis的主配置文件-->
<configuration>
<properties resource="jdbc.properties"/>
<typeAliases>
<!--用于指定别名-->
<!--<typeAlias type="com.wance.entity.Person" alias="Person"/>-->
<!--用于指定注册别名的包,当指定后,该包下的实体类都会注册别名,并且类名就是别名,-->
<!--不再区分大小写-->
<package name="com.wance.entity"/>
</typeAliases>
<!--配置环境-->
<environments default="mysql">
<environment id="mysql">
<!--配置事务类型-->
<transactionManager type="JDBC"></transactionManager>
<!--配置数据源-->
<dataSource type="POOLED">
<!--配置数据库的4个基本信息-->
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--<mapper resource="PersonMapper.xml"/>-->
<!--<mapper class="com.wance.Mapper.PersonMapper"/>-->
<package name="com.wance.Mapper"/>
</mappers>
</configuration>
整体配置完成
自己写mapper.xml文件:
<?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="com.wance.Mapper.PersonMapper">
<select id="findAll" resultType="Person">
select * from person
</select>
</mapper>
测试类:
public class TestPersonMapper {
@Test
public void test() throws IOException {
//读取配置文件
InputStream in= Resources.getResourceAsStream("SqlMapperConfig.xml");
//创建SqlSessionFactory工厂
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);
//使用工厂产生SqlSession对象
SqlSession session=factory.openSession();
//产生Person对象
PersonMapper personMapper=session.getMapper(PersonMapper.class);
System.out.println(personMapper.findAll());
}
}