Spring整合mybatis

1 .导入相关jar包
2 .编写配置文件
spring配置文件 ,将mybatis交给spring管理

    <!--配置数据源  -->
    <bean id="dataSource"  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>    
        <property name="url" value="jdbc:mysql://localhost:3306/test"/> 
        <property name="username" value="root"/>    
        <property name="password" value="123456"/>  
    </bean>

    <!-- 配置sqlSessionFactory -->
    <bean id="sqlSessionFactory"  class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource"  ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis.cfg.xml"/>         
    </bean>
    <bean id="sqlSessionTemplate"  class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0"  ref="sqlSessionFactory"></constructor-arg>  
    </bean>

    <bean id="userDao"  class="cn.sxt.dao.impl.UserDaoImpl">
        <property  name="sqlSession"    ref="sqlSessionTemplate"></property>
    </bean>
<configuration>
    <typeAliases>
        <package name="cn.sxt.vo"/>
    </typeAliases>
<mappers>
<mapper resource="cn/sxt/vo/user.mapper.xml"/>
</mappers> 
</configuration>
<mapper namespace="cn.sxt.entity.user.mapper">
    <select id="selectAll" parameterType="int" resultType="User">
        select * from User 
    </select>

</mapper>

Dao接口

public interface UserDao {
    public  List<User>  selectUser();
 }

Dao实现

public class UserDaoImpl implements UserDao{
    private SqlSessionTemplate  sqlSession;
    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }
    @Override
    public List<User> selectUser() {

        return sqlSession.selectList("cn.sxt.entity.user.mapper.selectAll");
    }

}

测试

public class Test {
    public static void main(String[] args) {
        ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
        UserDao userDao=(UserDao)ac.getBean("userDao");
        System.out.println(userDao.selectUser().size());
    }
}

总结:

  1. spring管理mybatis,配置了数据源,本来是mybatis里面的,现在交给spring管理,mybatis里面的就不用配置了
  2. sqlSession同理,Dao里面只需要定义sqlSessionTemplate,不再手动创建,也交给spring管理,先配置sqlSessionFactory,里面要定义数据源引用和mybatis配置文件的路径。然后配置sqlSessionTemplate,里面构造方法注入sqlSessionFactory(之所以用构造方法,因为里面没有相应的set方法)。之后并可以配置相对应的bean。
  3. 最后读取只需要读取beans.xml,所以下列的核心语句要记住。
ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值