首页 > 其他 > 详细

helloWorld程序

时间:2020-10-25 17:41:03      阅读:37      评论:0      收藏:0      [点我收藏+]

总结:

技术分享图片

 

 

 技术分享图片

测试方法

    public static void main(String[] args) throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);//解析全局配置文件
        //根据全局配置文件生成sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try{
            //传入接口EmployeeMapper.class,根据EmployeeMapper.xml的配置,可以得到接口的实现类对象,传统的dao需要我们自己写实现类
            //也就是说,mybatis会为接口创建一个代理对象,代理对象去执行具体的crud
            EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
            System.out.println(mapper.getClass());//Proxy
            employee e = mapper.getEmpById(1);
            System.out.println(e);
        }finally {
            sqlSession.close();
        }
    }

EmployeeMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.EmployeeMapper"><!-- dao.EmployeeMapper是dao的接口类-->
    <select id="getEmpById" resultType="bean.employee"><!--返回值的类型,包装为bean对象-->
            <!--id为接口类中的抽象方法名-->
            <!--以下为该方法要执行的具体操作-->
        select * from tbl_employee where id = #{id}
        <!-- #{id}:从传递过来的参数id中取值-->
    </select>
</mapper>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8"/><!--serverTimezone=GMT%2B8解决了时区不匹配问题-->
                <property name="username" value="root"/>
                <property name="password" value="xxx"/>
            </dataSource>
        </environment>
    </environments>
    <mappers><!-- sql映射文件,要注册到全局配置文件中-->
        <mapper resource="mappers/EmployeeMapper.xml"/>
    </mappers>
</configuration>

 

helloWorld程序

原文:https://www.cnblogs.com/xxxxxiaochuan/p/13873628.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!