mybatis学习笔记(一)—实例实现

1入门
1.1数据库环境搭建
1.1.1建立数据库
在mysql下建立数据库
create database mybatis;

建立对应的表结构


create table user(id int(11) not null auto_increment,
userName varchar(50) default null,
userAge int(11) default null,
useraddress varchar(200) default null,
primary key(id));

插入数据

insert into user values(1,'summer','100','shagnhai');

1.2开发环境搭建

1.2.1引用的jar包

 

1.2.2配置mybatis配置文件

mybatis配置文件

mybatis-config.xml配置文件




     
         
     

    
        
        
            
            
            
            
            
            
        
    
    
    
        
    

1.3建立与数据库对应的java class类和映射文件

1.3.1class类

package com.lienquan.javaee.mybatis.study01;

public class User {
	private int id;	
	private String userName;	
	private String userAge;	
	private String userAddress;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserAge() {
		return userAge;
	}
	public void setUserAge(String userAge) {
		this.userAge = userAge;
	}
	public String getUserAddress() {
		return userAddress;
	}
	public void setUserAddress(String userAddress) {
		this.userAddress = userAddress;
	}	
}

1.3.2映射文件

User.xml





    


1.4代码测试

package com.lienquan.javaee.mybatis.study01test;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.lienquan.javaee.mybatis.study01.User;
public class Test {
	private static SqlSessionFactory sqlSessionFactory;	
	private static Reader reader;	
	static{
		try{
			reader = Resources.getResourceAsReader("mybatis-config.xml");
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		}catch(Exception e){
			e.printStackTrace();
		}
	}	
	public static SqlSessionFactory getSession(){
		return sqlSessionFactory;
	}	
	public static void main(String[] args) {		
		SqlSession session = sqlSessionFactory.openSession();
		try{	
			User user = (User) 
			session.selectOne("com.lienquan.javaee.mybatis.study01.UserMapper.selectUserByID",1);
			System.out.println(user.getUserName());
			System.out.println(user.getUserAddress());			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			session.close();
		}		
	}
}


这样,一个基本的mybatis实例完成。可以总结如下(当前理解总结):

1需要有mybatis配置文件配置相应的数据库链接,映射类,以及映射文件;

2需要对每一个数据库表配置对应的POJO类,以及映射类。


你可能感兴趣的:(mybatis学习笔记(一)—实例实现)