Mybatis环境搭建及简单实例

一、新建一个web项目、导入mybatis得jar包 mybatis-3.5.4.jar就可以
jar包路径:https://github.com/mybatis/mybatis-3/releases
二、在src同级下建立一个config包
Mybatis环境搭建及简单实例_第1张图片三、配置SqlMapConfig.xml,用来连接数据库





  
  
  
  
  
      
  
    
      
      
          
         
         
         
         
         
         
      
    
  
  
  
  
    
  
  

db.properties文件配

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/java
jdbc.username=root
jdbc.password=123456

注:这两中连接方式选着一种就可以

四、在数据库中添加user表
Mybatis环境搭建及简单实例_第2张图片六、现在开始编写javaBean

package javademo;

public class User {
	private Integer id;
	private String name;
    private String sex;
    private int age;
    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 getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}


    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + "]";
    }

再编写一个UserDao 接口

package db;

import java.util.List;

import javademo.User;

public interface UserDao {
	public void insert(User user);
	public User findUserById (int userId);
	public List findAllUsers();
}

再编写一个userDao-mapping.xml (可随便命名)







    
 


测试代码UserDaoTest

package db;

import java.io.IOException;

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 javademo.User;

public class TestMybatis {
	 //Mybatis 通过SqlSessionFactory获取SqlSession, 然后才能通过SqlSession与数据库进行交互
    private static SqlSessionFactory getSessionFactory() {  
        SqlSessionFactory sessionFactory = null;  
        String resource = "SqlMapConfig.xml";  
        try {  
            sessionFactory = new SqlSessionFactoryBuilder().build(Resources  
                    .getResourceAsReader(resource));
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return sessionFactory;  
    } 
    
    //@Test
    public void findUserById() {
        SqlSession sqlSession = getSessionFactory().openSession();  
        UserDao userMapper = sqlSession.getMapper(UserDao.class);  
        User user = userMapper.findUserById(1);  
        //Assert.assertNotNull("没找到数据", user);
        System.out.println(user);
    }
    
    
	public static void main(String[] args) throws IOException
    {
//        MybatisFirst mybatis = new MybatisFirst();;
//        mybatis.selectUserById(1);
        
        TestMybatis t = new TestMybatis();
        t.findUserById();
    }
	
	
}

你可能感兴趣的:(Mybatis环境搭建及简单实例)