Mybatis学习日记(一)——初识Mybatis,一个简单demo

最近接触的项目中使用了Mybatis框架,觉得 Mybatis使用起来非常方便,决定从基础开始学习Mybatis。我准备的环境如下:

  • JDK1.5

  • Mybatis 3.3.0版本

  • MySQL数据库

  • Eclipse Neon.3 Release (4.6.3)

  • Apache Maven 构建工具

一.创建Maven项目

首先通过Eclipse创建一个Maven Simple Project,通过配置其pom.xml添加我们所需要的jar包,在这里我添加了Log4j,JUnit和MySQL驱动等依赖。


  4.0.0
  tk.mybatis
  sample
  0.0.1-SNAPSHOT
  
  
  	UTF-8
  
  
  
  	
  		junit
  		junit
  		4.12
  		test
  	
  	
  		org.mybatis
  		mybatis
  		3.3.0
  	
  	
  		mysql
  		mysql-connector-java
  		5.1.38
  	
  	
  		org.slf4j
  		slf4j-api
  		1.7.12
  	
  	
  		org.slf4j
  		slf4j-log4j12
  		1.7.12
  	
  	
  		log4j
  		log4j
  		1.2.17
  	
  
  
  
  	
  		
  			maven-compiler-plugin
  			
  				1.5
  				1.5
  			
  		
  	
  
  

二.配置Mybatis

在这里我通过xml形式对Mybatis进行配置,在src/main/resources下创建mybatis-config.xml配置文件如下:







	



	



	
		
			
		
		
			
			
			
			
		
	



	


  • 中logImpl属性指定使用LOG4J输出日志

  • 下配置包的别名,配置后,在使用类的时候不需要写包名

  • 配置了数据库连接的信息

  • 配置了Mybatis的SQL语句和映射配置文件


三.创建实体类和Mapper.xml文件

在Mybatis中,一个表一般对应一个实体类,用于进行增删改查等操作。这里我在数据库中建的表结构如下

根据表结构,在src/main/java下创建包tk.mybatis.sample.model,在该包下创建实体类Country如下

package tk.mybatis.sample.model;

public class Country {
	private long id;
	private String countryname;
	private String countrycode;
	
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getCountryname() {
		return countryname;
	}
	public void setCountryname(String countryname) {
		this.countryname = countryname;
	}
	public String getCountrycode() {
		return countrycode;
	}
	public void setCountrycode(String countrycode) {
		this.countrycode = countrycode;
	}
	
}

接着在src/main/resources下创建tk/mybatis/sample/mapper目录,在该目录下创建CountryMapper.xml文件如下: