MyBatis学习笔记1

最近想尝试下Struts2+Spring3+MyBatis3的架构,所以特地学习了下MyBatis3。把学习的过程记录了下来,留给自己和后来者参考。

到目前为止,MyBatis的最新版本是3.1.0,本文中采用的也就是这一版本。

首先就是下载MyBatis,MyBatis是放在Google Code上面托管的,地址是http://code.google.com/p/mybatis/,遗憾的是,MyBatis官方提供的示例不是很多,只有一个和Spring集成的项目例子jpetstore,想玩一下的话,也可以下下来跑一下看看。

由于是第一次使用MyBatis,所以在这个实例中没有集成任何的框架,仅仅结合使用了一个日志记录的框架log4j,但这并不是重点。下面就来讲述一下步骤:

1.首先创建一个java project:


MyBatis学习笔记1

 

2.然后在MySQL中新建一个数据库名为mybatis,相关建表语句如下:
 

 

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', 'zhangsan', '123');
INSERT INTO `user` VALUES ('2', 'lisi', '456');
INSERT INTO `user` VALUES ('3', 'wangwu', '789');

 

 

3.在工程中导入相关jar包,文件组织结构如下:


MyBatis学习笔记1

 

4.工程源码如下:

User.java

 

package com.mybatis_test.domain;

public class User {

	private Integer id;
	private String name;
	private String password;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

 

  UserMapper.java

 

package com.mybatis_test.mapper;

import com.mybatis_test.domain.User;

public interface UserMapper {

	User selectUser(Integer id);
}

  UserMapper.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.mybatis_test.mapper.UserMapper">
	<select id="selectUser" parameterType="int" resultType="com.mybatis_test.domain.User">
		select * from User where id = #{id}
	</select>
</mapper>

 

  Test.java

 

package com.mybatis_test.test;

import java.io.IOException;

public class Test {

	public static void main(String[] args) {
		String resource = "mybatis-config.xml";
		try {
			Reader reader = Resources.getResourceAsReader(resource);
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
			SqlSession session = sqlSessionFactory.openSession();
			
			UserMapper mapper = session.getMapper(UserMapper.class);
			User user = mapper.selectUser(2);
			
			System.out.println(user.getId());
			System.out.println(user.getName());
			System.out.println(user.getPassword());
			
			session.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

  log4j.properties

 

# Rules reminder:
# DEBUG < INFO < WARN < ERROR < FATAL

# Global logging configuration
log4j.rootLogger=DEBUG, stdout

# My logging configuration...
log4j.logger.org.mybatis.jpetstore=DEBUG

## Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n

 

  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="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost:9906/mybatis" />
				<property name="username" value="root" />
				<property name="password" value="root" />
			</dataSource>
		</environment>
	</environments>
	
	<mappers>
		<mapper resource="com/mybatis_test/mapper/UserMapper.xml" />
	</mappers>
</configuration>

 

 4.运行上面的测试方法就可以看到下面的结果:

 

DEBUG 2012-03-16 16:08:39,825 org.apache.ibatis.logging.slf4j.Slf4jImpl: Logging initialized using 'org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG 2012-03-16 16:08:40,374 org.apache.ibatis.logging.slf4j.Slf4jImpl: PooledDataSource forcefully closed/removed all connections.
DEBUG 2012-03-16 16:08:40,375 org.apache.ibatis.logging.slf4j.Slf4jImpl: PooledDataSource forcefully closed/removed all connections.
DEBUG 2012-03-16 16:08:40,375 org.apache.ibatis.logging.slf4j.Slf4jImpl: PooledDataSource forcefully closed/removed all connections.
DEBUG 2012-03-16 16:08:40,375 org.apache.ibatis.logging.slf4j.Slf4jImpl: PooledDataSource forcefully closed/removed all connections.
DEBUG 2012-03-16 16:08:40,816 org.apache.ibatis.logging.slf4j.Slf4jImpl: Openning JDBC Connection
DEBUG 2012-03-16 16:08:41,635 org.apache.ibatis.logging.slf4j.Slf4jImpl: Created connection 7579563.
DEBUG 2012-03-16 16:08:41,655 org.apache.ibatis.logging.slf4j.Slf4jImpl: ooo Using Connection [com.mysql.jdbc.JDBC4Connection@73a7ab]
DEBUG 2012-03-16 16:08:41,655 org.apache.ibatis.logging.slf4j.Slf4jImpl: ==>  Preparing: select * from User where id = ? 
DEBUG 2012-03-16 16:08:41,706 org.apache.ibatis.logging.slf4j.Slf4jImpl: ==> Parameters: 2(Integer)
DEBUG 2012-03-16 16:08:41,736 org.apache.ibatis.logging.slf4j.Slf4jImpl: <==    Columns: id, name, password
DEBUG 2012-03-16 16:08:41,737 org.apache.ibatis.logging.slf4j.Slf4jImpl: <==        Row: 2, lisi, 456
2
lisi
456
DEBUG 2012-03-16 16:08:41,743 org.apache.ibatis.logging.slf4j.Slf4jImpl: Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@73a7ab]
DEBUG 2012-03-16 16:08:41,745 org.apache.ibatis.logging.slf4j.Slf4jImpl: Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@73a7ab]
DEBUG 2012-03-16 16:08:41,745 org.apache.ibatis.logging.slf4j.Slf4jImpl: Returned connection 7579563 to pool.

5.但实际应用中我们不可能有这样简单的示例,会有和其他框架集成,集成的示例将在后续的文章中继续介绍。

6.本示例中的类中的关系较为简单,为使代码片段较为简洁,没有加上相关注释。

7.工程源码放在附件中。

 

 

 

你可能感兴趣的:(mybatis)