Mybatis+spring2.5配置

首先maven项目的话,需要增加如下依赖,虽然官方文档介绍的spring3.x的整合,但是2.5目前看也能用哦

	<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis</artifactId>
		    <version>3.0.5</version>
		</dependency>
	    <dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis-spring</artifactId>
		    <version>1.0.1</version>
        </dependency>
 

 

sqlSessionFactory交给spring去管理,同时保持了单例,这就是spring控制的好处呀

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:MybatisConfiguration.xml"></property>
    </bean>

	<bean id="eventFlagMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
		<property name="mapperInterface" value="com.ice.stat.online.dao.mybatis.EventFlagMapper" />
		<property name="sqlSessionFactory" ref="sqlSessionFactory" />
	</bean>  

 

Mybatis的配置文件,这里只配置了别名

<?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>
	<typeAliases>
	   <typeAlias type="com.ice.stat.online.model.EventFlag" alias="EventFlag"/>
	</typeAliases>

    <mappers>
	   <mapper resource="com/ice/stat/online/model/hbm/EventFlagMapper.xml"/>
	</mappers>
	
</configuration>

 

EventFlagMapper.xml,这里配置了查询的sql,注意select节点的ID和一会儿提到的mapper接口里的方法同名

<?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="com.ice.stat.online.dao.mybatis.EventFlagMapper">

	<resultMap type="EventFlag" id="EventFlagMap">
	    <id column="id" property="id"/>
	    <result property="logtime" column="logtime"/>
	    <result property="eventDetail" column="event_detail"/>
	</resultMap>


    <select id="selectAllEvent" resultMap="EventFlagMap">
        select * from event_flag
    </select>

</mapper>
 

Mapper接口,只有声明,没有任何实现类,这个接口相当于我们用hibernate时候的dao,当然也可以省去上面的sql配置文件,采用注解的方式,不过我不太喜欢这种方式

package com.ice.stat.online.dao.mybatis;

import java.util.List;

import com.ice.stat.online.model.EventFlag;

public interface EventFlagMapper {

    public List<EventFlag> selectAllEvent();
}
 

测试类

    public static  void test3(){
        ClassPathXmlApplicationContext cac = new ClassPathXmlApplicationContext(new String[]{"applicationContext-dataSource.xml","applicationContext-mybatis.xml"});
        EventFlagMapper mapper = (EventFlagMapper)cac.getBean("eventFlagMapper");
        List<EventFlag> events =  mapper.selectAllEvent();
        for(EventFlag event: events){
            System.out.println(event.getId());
            System.out.println(event.getEventDetail());
            System.out.println(event.getLogtime());
            System.out.println("-------------------------------------");
        }
         
    }
 

 

你可能感兴趣的:(mybatis)