xml映射(利用映射完成helloworld)

xml映射(利用映射完成helloworld),第1张

xml映射(利用映射完成helloworld)

    什么是xml映射
    MyBatis提供了注解定义SQL与Mapper接口的映射关系。但是注解不能解决复杂的映射关系,例如sql拼接,所以需要使用xml映射。

    helloWorld程序

    文件结构

someMapper.xml




    
        select 'hello world'
    

namespace对应DemoMapper地址id对应方法名,此处是demomapper中的test方法resultType对应方法的返回值,test返回值为String

DemoMapper

package cn.tedu.mapper;

import org.apache.ibatis.annotations.Select;

public interface DemoMapper {
    @Select("select empno,ename,sal,deptno from emp where empno=1;")
    String hello();

    String test();
}

MybatisConfig.java

//配置SqlSessionFactory的作用是告诉mybatis如何找到目标数据库
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource,
           @Value("${mybatis.mapper.location}") Resource[] mapperLocation)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //将所有的Mapper映射xml文件注入给MyBatis
        bean.setMapperLocations(mapperLocation);
        return bean.getObject();
    }

@Value("${mybatis.mapper.location}") Resource[] mapperLocation获取映射关系xml,从jdbc.properties中获取bean.setMapperLocations(mapperLocation);注入MyBatis

jdbc.properties

db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/newdb3?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
db.username=root
db.password=
db.maxActive=10
db.initialSize=2
mybatis.mapper.location=classpath:mappers/*.xml

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5719324.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存