• 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()); } } }
  • 相关阅读:
    关于基本的线程的生命周期
    HTML Response ContentType 大全
    IE与Firefox的CSS兼容大全
    文件上传代码
    C#.NET里面抽象类和接口有什么区别
    用SQL命令创建数据库
    JS根据生日算岁数
    改变Iframe的Src
    JS做加法精度问题
    真正的问题应该在我身上……
  • 原文地址:https://www.cnblogs.com/cainame/p/10339390.html
Copyright © 2020-2023  润新知