mybaits接口式编程

来源:互联网 发布:麦克海尔数据 编辑:程序博客网 时间:2024/06/14 10:44

第一步,建工程,在mybaits-config.xml中,建立数据源,

<properties resource="dbconfig.properties"></properties>    <environments default="development">        <environment id="development">            <transactionManager type="JDBC" />            <dataSource type="POOLED">                <property name="driver" value="${jdbc.driver}" />                <property name="url" value="${jdbc.url}" />                <property name="username" value="${jdbc.username}" />                <property name="password" value="${jdbc.password}" />            </dataSource>        </environment>    </environments>        <!-- 将我们写好的sql映射文件(EmployeeMapper.xml)一定要注册到全局配置文件(mybatis-config.xml)中 -->    <mappers>        <mapper resource="EmployeeMapper.xml" />    </mappers>
第二步,写接口,名称和sql映射文件一样。。。
public interface EmployeeMapper {    public Employee getEmpById(Integer id);}

第三步,在sql映射文件中写入

<mapper namespace="com.az.dao.EmployeeMapper"><!-- namespace:名称空间;指定为接口的全类名id:唯一标识resultType:返回值类型#{id}:从传递过来的参数中取出id值public Employee getEmpById(Integer id); -->    <select id="getEmpById" resultType="com.az.bean.Employee">        select id,last_name lastName,email,gender from employee where id = #{id}    </select></mapper>

第四步,测试

//获取SqlSessionFactory对象public SqlSessionFactory getSqlSessionFactory() throws IOException{        String resource = "mybatis-config.xml";         InputStream inputStream =   Resources.getResourceAsStream(resource);         return new SqlSessionFactoryBuilder().build(inputStream);    }/** * 1.0根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象 * @throws Exception */@Testpublic void testName() throws Exception {    //2.0 获取sqlSession实例,能直接执行已经映射的sql语句         //第一个参数:参数的唯一标识         //第二个参数:执行sql的参数    SqlSession openSession = null;    try {         SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();         openSession = sqlSessionFactory.openSession();         Employee selectOne = openSession.selectOne("com.az.dao.EmployeeMapper.getEmpById", 1);    } catch (Exception e) {        // TODO Auto-generated catch block        e.printStackTrace();    }finally{         openSession.close();       }}