MyBatis-Spring(一)

1.在lib 包中添加:

主要是添加多一个1.3的 mybatis-spring jar 包
这里写图片描述

2.pojo 实体类–>mapper—>config.xml—>mapper/IMP—>applicationContext.xml

这里写图片描述

其中 config.xml 中省略了连接数据库的操作,只需要保留typeAliases和mappers标签

3.mapper 中的 IMP

1)定义spring给mybatis提供的sqlsession对象:SqlSessionTemplate —> sqlsession
(private定义;public getter&setter )
2)SqlSessionTemplate.getMapper(AccountMapper.class)
3)返回方法

4.Service中的 IMP

1)private AccountMapper mapper;
2)重写方法并返回 mapper.findAll();

5.ApplicationContext.xml

顺序:
1.驱动管理数据源
2.sqlSessionFactoryBean
3.sqlSessionTemplate
4.AccountMapperIMP
5.AccountServiceIMP

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 1.驱动管理数据源 -->
    <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="password" value="123"/>
        <property name="username" value="root"/>
        <property name="url" value="jdbc:mysql://localhost:3306/student?characterEncoding=utf8"/>
    </bean>

    <!-- 2.sqlsessionfatorybean -->
    <bean id="sqlsessionfatorybean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource"/>
        <property name="configLocation">
            <value>classpath:mybatis-config.xml</value>
        </property>
    </bean>

    <!-- 3.sqlsessionTemplate -->
    <!--SqlSessionTemplate sqlSessionTemplate=new SqlSessionTemplate(sqlSessionFactoryBean)-->
    <bean id="sqlsessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg ref="sqlsessionfatorybean"/>
    </bean>

    <!-- 4.AccountMapperImpl -->
    <bean id="AccountMapperIMP" class="com.mapper.IMP.AccountMapperIMP">
        <property name="sqlSessionTemplate" ref="sqlsessionTemplate"/>
    </bean>

    <!-- 5.AccountServiceImpl -->
    <bean id="AccountServiceImpl" class="com.service.IMP.AccountServiceImpl">
        <property name="mapper" ref="AccountMapperIMP"/>
    </bean>

</beans>

6.Test类

// 1.ApplicationContext
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

// 2.AccountServiceImpl
        AccountServiceImpl service = (AccountServiceImpl) ac.getBean("AccountServiceImpl");

// 3.
        List<Account> list = service.queryAccount();
        for(Account account:list){
            System.out.println(account);
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值