Mybatis框架环境搭建

一、创建Maven工程,在pom.xml填写依赖。

    
        org.mybatis
        mybatis
        3.4.5
    

    
    
        mysql
        mysql-connector-java
        5.1.6
    

    
    
        junit
        junit
        4.12
    

    
    
        log4j
        log4j
        1.2.17
        compile
    

二、编写用于连接数据库的工具类SqlSessionFactoryUtils

public class SqlSessionFactoryUilts {

    private static SqlSessionFactory sqlSessionFactory = null;

    //私有化工具类,防止被外部创建
    private SqlSessionFactoryUilts(){}

    private static SqlSessionFactory getSqlSessionFactory(){
        if (sqlSessionFactory != null){
            return sqlSessionFactory;
        }else {
            try {
                sqlSessionFactory = new SqlSessionFactoryBuilder().build( Resources.getResourceAsStream( "mybatis-config.xml" ) );
                return sqlSessionFactory;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;

    }

    public static SqlSession openSqlsession(){
        if (sqlSessionFactory == null){
            getSqlSessionFactory();
        }
        return sqlSessionFactory.openSession();
    }
}

三、编写pojo类Role

public class Role {
    private String roleName;
    private int roleId;
    private String roleDesc;

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public int getRoleId() {
        return roleId;
    }

    public void setRoleId(int roleId) {
        this.roleId = roleId;
    }

    public String getRoleDesc() {
        return roleDesc;
    }

    public void setRoleDesc(String roleDesc) {
        this.roleDesc = roleDesc;
    }

    @Override
    public String toString() {
        return "Role{" +
                "roleName='" + roleName + '\'' +
                ", roleId=" + roleId +
                ", roleDesc='" + roleDesc + '\'' +
                '}';
    }
}

四、编写mybatis的主配置文件以及用于连接数据库properties文件

1.mybatis-config.xml






    




    
    



    
        
        
            
            
            
            
        
    



    


2.jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///cainiao
username=root
password=****

五、编写映射接口和相应的映射文件,注意接口和映射文件的包名必须相同

1、RoleMapper.java

public interface RoleMapper {
     Role getRole(int id);
}

2、RoleMapper.xml



        

   	 
        
        
        
    

    

六、编写测试类

public class Test {

    @org.junit.Test
    public void test(){
        SqlSession session = SqlSessionFactoryUilts.openSqlsession();
        RoleMapper roleMapper = session.getMapper( RoleMapper.class );
        Role role = roleMapper.getRole( 2 );
        System.out.println(role);
    }
}

控制台输出结果:

Role{roleName='总裁', roleId=0, roleDesc='管理整个公司'}

Process finished with exit code 0

源码下载

你可能感兴趣的:(Mybatis框架环境搭建)