目录

Mybatis下载

环境配置

创建pojo类

主配置文件

输出日志信息

映射文件配置

加载映射文件

 测试程序


Mybatis下载

下载地址:https://github.com/mybatis/mybatis-3/releases

Mybatis入门

 

Mybatis入门

环境配置

加入mybatis核心包、依赖包、数据驱动包

Mybatis入门

创建pojo类

pojo类作为mybatis进行sql映射使用,po类通常与数据库表对应

public class User {
	private int id;
	private String username;// 用户姓名
	private String sex;// 性别
	private Date birthday;// 生日
	private String address;// 地址

    .....
}

主配置文件

在src下创建SqlMapConfig.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>
	<!-- 和spring整合后 environments配置将废除 -->
	<environments default="development">
		<environment id="development">
			<!-- 使用jdbc事务管理 -->
			<transactionManager type="JDBC" />
			<!-- 数据库连接池 -->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url"
					value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
				<property name="username" value="root" />
				<property name="password" value="root" />
			</dataSource>
		</environment>
	</environments>
</configuration>

输出日志信息

在src下创建log4j.properties,mybatis默认使用log4j作为输出日志信息

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# 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

映射文件配置

在sqlmap目录下创建sql映射文件User.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">
<!-- namespace:命名空间,用于隔离sql,还有一个很重要的作用,后面会讲 -->
<mapper namespace="test">
</mapper>

加载映射文件

mybatis框架需要加载Mapper.xml映射文件,将users.xml添加在SqlMapConfig.xml

Mybatis入门

Mybatis入门

 

 测试程序

public class MybatisJunit {
	
	private SqlSessionFactory sqlSessionFactory = null;

	@Before
	public void init() throws Exception {
		// 1. 创建SqlSessionFactoryBuilder对象
		SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

		// 2. 加载SqlMapConfig.xml配置文件
		InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");

		// 3. 创建SqlSessionFactory对象
		this.sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
	}

	@Test
	public void testQueryUserById() throws Exception {
		// 4. 创建SqlSession对象
		SqlSession sqlSession = sqlSessionFactory.openSession();

		// 5. 执行SqlSession对象执行查询,获取结果User
		// 第一个参数是User.xml的statement的id,第二个参数是执行sql需要的参数;
		User user = sqlSession.selectOne("test.findUserById", 10);

		// 6. 打印结果
		System.out.println(user.getAddress());

		// 7. 释放资源
		sqlSession.close();
	}

}

 

相关文章: