1、先创建日志文件
在工程的src目录下创建log4j.properties文件
内容可在mybatis文件夹下的mybatis-3.4.5.pdf手册中找到:
# Global logging configuration**
log4j.rootLogger=ERROR, stdout
**# MyBatis logging configuration...**
log4j.logger.com.mybatis=DEBUG
**# Console output...**
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
2、创建一个持久化对象
添加成员变量属性,同时为了方便查看结果,重写tostring方法
3、创建映射文件
在src目录下创建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="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
4、创建配置文件MyBatis
在src目录下创建MyBatis的核心配置文件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="${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>
5、创建控制层中的测试类
在src目录下的控制层的包中创建测试类:
public class MyBatisTest {
public static void main(String[] args) {
try {
//读取配置文件mybatis-config.xml
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//根据配置文件构建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//通过SessionFactory创建sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
MyUser myUser = sqlSession.selectOne("com.mybatis.mapper.UserMapper.selectUserById",1);
System.out.println(myUser);
} catch (IOException e) {
e.printStackTrace();
}
}
}