1.添加mybatis的依赖,目前版本是3.4.6,除此之外还有junit和mysql的驱动依赖分别引入进来
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
2.在resources目录下新增一个mybatis的配置文件,mybatis.xml
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
3.在com.zy.pojo的包下创建User.java文件
package com.zy.pojo;
public class User {
private int uid;
private String username;
private String password;
private int age;
private String addr;
@Override
public String toString() {
return "User{" +
"uid=" + uid +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
", addr='" + addr + '\'' +
'}';
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
}
4.在com/zy/pojo的目录下创建UserMapper.xml文件
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
select * from user
5.TestUser.java
package com.zy.test;
import com.zy.pojo.User;
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 org.junit.Test;
import java.io.IOException;
import java.sql.Connection;
import java.util.List;
public class TestUser {
@Test
public void testGetAllUsers(){
/**
* 1. 使用mybatis的配置文件以及SqlSessionFactoryBuilder建造者模式创建SqlSessionFactory对象
* 2. 使用SqlSessionFactory对象的openSession()方法来得到一个SqlSession对象,用该对象即可完成对象的所有的crud操作
* 3. 使用SqlSession对象来完成crud操作
* 4. 关闭资源
*
*/
try {
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
SqlSession session = sf.openSession();
/**
* session的crud方法("namespace.id");整个项目中的namespace.id必须唯一
*/
List
for (User u : users) {
System.out.println(u);
}
if(session != null){
session.close();
session = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}