1.编写持久化对象
public class User { private String id;//用户编号 private String username;//用户名 private String password;//用户密码 public String getId() { return id; } public void setId(String id) { this.id = id; } 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; } }
2.编写数据协议层
public interface UserDao { public List<User> getAllUser();//得到所有的用户 }
3.编写数据层
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="dao.UserDao"> <select id="getAllUser" resultType="User"> select * from user_inf </select> </mapper>
4.编写工具类
public class SqlSessionFactorytest { //定义参数 public static SqlSessionFactory sqlSessionFactory=null; //定义配置文件 public static String resource="mybatis-config.xml"; public static InputStream inputStream; //构建SesseionFactory public static SqlSessionFactory getSqlSessionFactoryBuider() { try { //读取配置文件 inputStream=Resources.getResourceAsStream(resource); System.out.println("配置文件加载成功!!"); //SqlSessionFactoryBuilder通过输入流的相关配置得到sqlSessionFactory }catch(IOException e) { e.printStackTrace(); } sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); System.out.println("sqlSessionFactory创造成功!!"); return sqlSessionFactory; } }
这个工具主要是获得SqlSessionFactory
5.编写主类
public class test { public static void main(String[] args) {
//有工具类获得SqlSessionFactory SqlSessionFactory sqlSessionFactory=SqlSessionFactorytest.getSqlSessionFactoryBuider(); //由SqlSessionFactoty获得SqlSession
SqlSession sqlSession=sqlSessionFactory.openSession();
//获得Mapper接口 UserDao userDao=sqlSession.getMapper(UserDao.class); List<User> user=userDao.getAllUser(); for(int x=0;x<user.size();x++) { User u=user.get(x); System.out.println(u.getId()); System.out.println(u.getUsername()); System.out.println(u.getPassword()); } } }