zoukankan      html  css  js  c++  java
  • mybtis入门

    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()); } } }
  • 相关阅读:
    容器技术问题
    URL和URL
    容器和注入技术
    云计算应用开发与实践读书 笔记(三)
    云计算应用开发与实践读书 笔记 (二 )
    云计算应用开发与实践读书 笔记
    C++学习之DLL注入
    c语言学习,模拟栈操作
    领悟百分比定位
    强大的第三方工具autoPrefixer
  • 原文地址:https://www.cnblogs.com/cainame/p/10339390.html
Copyright © 2011-2022 走看看