Spring基础,整合mybatis, java中路径什么时候用‘点’什么时候用‘斜杠’问题(坑)

前言:

  再刚刚开始接触到框架时,首先让我产生疑惑的就是路径表达问题,为什么用到路径用斜杠去表达,有的用点呢?

  答:‘点’ 的作用是寻找java包时用到的,‘斜杠’是找除java包以外的文件用到的,如常用到的xml文件


正题:Spring整合Mybatis,Mybatis-spring

    1.编写数据源配置

    <!--DataSource:用Spring的数据源代替mybatis的配置,此外还有:c3p0,dbcp,druid
        这里使用Spring的jdbc
    -->
    <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    2.绑定mybatis-config、3.sqlSessionFactory

    <!--    配置sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource"/>
        <!--绑定Mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--mapper注册器-->
        <property name="mapperLocations" value="classpath:com/king/map/*.xml"/>
    </bean>

    

    4.sqlSessionFactoryTemplate

    <!--SqlSessionTemplate,sqlSession的模板类-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能用构造器注入sqlSessionFactory,因为它没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    5.给接口加实现类

public class UserMapperImpl implements UserMapper {

    //以前所有操作都使用sqlSession来执行,现在使用SqlSeeionTemplate(模板)
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession){
        this.sqlSession = sqlSession;
    }

    public List<User> selectUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}

    6.将实现类注册到Spring中

    <!--注册接口实现类-->
    <bean id="userMapper" class="com.king.map.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

    7.测试使用即可

    @Test
    public void test1() throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        for (User user : userMapper.selectUser()) {
            System.out.println(user);
        }
    }

扩展:还有简化版:本质就是不需要再自己去配置sqlSessionFactoryTemplate来生产sqlSession,通过调用sqlsessionDaoSupport这个包中的getSession方法就可生成sqlSession,节省了方式一步骤4.(sqlSessionFactoryTemplate)配置部分

小结:spring-Mybatis(Spring整合Mybatis)流程

    1,首先要写一个接口,根据接口要实现的功能写一个相关xml(mybatis)配置

    2,写spring整合mybatis基础配置文件<sqslSessionFactory>,(配置连接数据库的数据源<dataSources>,绑定mybatis核心配置文件<configLocation>,配置注册器<mapperLocations>)

    3,编写实现类,因为mybatis的数据要注入到spring中,所以要再写一个是实现类(相当于mybatis的业务层)去注入

    4.最后测试

原文地址:https://www.cnblogs.com/CL-King/p/13936405.html