基于Mybatis第一个实验

编写第一个基于mabatis测试的例子

1.添加jar包
在这里插入图片描述
2.创建数据库+表
3.创建配置文件conf.xml



  
      
        
            
            
            
                
                
                
                
            
        
    
    
        
    
  

4.创建实体类

package com.sxau.rjxy.mybatis_test1;

public class User {
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	private int id;
	private String name;
	private int age;
    //get,set方法

	public User(int id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}
	public User() {
		
	}
}

5.创建userMapper.xml映射文件


 



 


6.Test.java

package com.sxau.rjxy.mybatis_test1;

import java.io.IOException;
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;

public class Test {
	public static void main(String[] args) throws IOException {
		String resource = "conf.xml"; 
		//加载mybatis的配置文件(它也加载关联的映射文件)
		Reader reader = Resources.getResourceAsReader(resource); 
		//构建sqlSession的工厂
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
		//创建能执行映射文件中sql的sqlSession
		SqlSession session = sessionFactory.openSession();
		//映射sql的标识字符串
	String statement = "com.sxau.rjxy.mybatis_test1.userMapper"+".getUser";
		//执行查询返回一个唯一user对象的sql
		User user = session.selectOne(statement, 1);
		System.out.println(user);
	}


}

8.结果
基于Mybatis第一个实验_第1张图片

你可能感兴趣的:(mybatis+JDBC)