MyBatis框架的搭建

MyBatis框架的搭建

在使用Maven的基础上进行MyBatis框架的搭建:

第一步搭建MyBatis 开发环境

1.导入jar包(依赖)
 
    
    
        org.mybatis
        mybatis
        3.4.5
    

      
    
        mysql
        mysql-connector-java
        5.1.6
    

    
    
        junit
        junit
        4.12
    

    
    
        log4j
        log4j
        1.2.17
    


2.在 domain 包下编写实体类:

例如

public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public Date getBirthday() {
    return birthday;
}

public void setBirthday(Date birthday) {
    this.birthday = birthday;
}

public String getSex() {
    return sex;
}

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

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

@Override
public String toString() {
    return "User{" +
            "id=" + id +
            ", username='" + username + '\'' +
            ", birthday=" + birthday +
            ", sex='" + sex + '\'' +
            ", address='" + address + '\'' +
            '}';
}
}
3.在 dao包下编写UseDao接口

例如:

public interface IUserDao {
//查询所有用户
List findAll();
}

第二步编写持久层接口的映射文件 UserDao.xml :

例如:

	


	



注意:

创建位置:

必须和持久层接口在相同的包中。

名称:

必须以持久层接口名称命名文件名,扩展名是.xml
如我的Dao层叫UserDao,所以xml文件是UserDao.xml

建包的时候要一层一层的建立,不要一口气输入com.xxxx.dao

第三步编写MyBatis的核心配置文件 SqlMapConfig.xml

SqlMapConfig.xml的目的是为了去读取UserDao.xml,以及链接数据库,其位置直接放在resources文件夹下;





    
        
        
            
            
            
            
            
        
    




    


测试类Test的编写:

public class TestUserDao {

private SqlSessionFactory factory;
private SqlSession sqlSession;
private InputStream in;

@Before //在@Test注解执行之前调用
public void init() throws IOException {
    //读取MyBatis的核心配置文件
    in = Resources.getResourceAsStream("SqlMapConfig.xml");
    //构建工厂
    factory = new SqlSessionFactoryBuilder().build(in);
    //打开SqlSession
    sqlSession = factory.openSession();
}
	//测试的方法可以添加多个
@Test
public void testFindAll() throws IOException {

    //获取接口的代理对象
    IUserDao userDao = sqlSession.getMapper(IUserDao.class);
    //执行查询操作
    List list = userDao.findAll();
    for (User user : list) {
        System.out.println(user);
    }
    //释放资源
    in.close();
    sqlSession.close();

}

@After //在@Test执行完之后调用
public void destory() throws IOException {
    //释放资源
    in.close();
    sqlSession.close();
}

你可能感兴趣的:(学习)