我有一个使用Mybatis(v3.0.5)进行OR /映射的项目.典型(运行)设置如下:@H_502_2@
>要映射的POJO-水果
>一个“ MyBatis”映射器XML文件-FruitMapper.xml-所有SQL查询都在其中
>定义所有相同映射器方法的接口映射器-FruitMapper.java
>具有接口映射器参考的DAO-FruitDao
> MyBatis配置文件-mybatis-config.xml
>将所有内容与Spring config XML链接在一起-myapp-spring-config.xml@H_502_2@
一个示例实现:@H_502_2@
@H_502_2@
public class Fruit {
private String type = "Orange"; // Orange by default!
// Getters & setters,etc. This is just a VO/POJO
// that corresponds to a [fruits] table in my DB.
}
public interface FruitMapper {
public List<Fruit> getAllFruits();
}
public class FruitDao {
private FruitMapper mapper;
// Getters & setters
public List<Fruit> getAllFruits() {
return mapper.getAllFruits();
}
}
FruitMapper.xml@H_502_2@
@H_502_2@
<mapper namespace="net.me.myapp.FruitMapper">
<select id="getAllFruits" resultSetType="FORWARD_ONLY">
SELECT * FROM fruits
</select>
</mapper>
mybatis-config.xml@H_502_2@
@H_502_2@
<configuration>
<!-- Nothing special here. -->
</configuration>
myapp-spring-config.xml :(这就是我想要摆脱的)@H_502_2@
@H_502_2@
<bean id="fruitDao" class="net.me.myapp.FruitDao">
<property name="mapper" ref="fruitMapper" />
</bean>
<bean id="fruitMapper" class="org.mybatis.spring.mapper.Mapperfactorybean">
<property name="mapperInterface" value="net.me.myapp.FruitMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.sqlSessionfactorybean">
<property name="dataSource" ref="myDatasource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="mapperLocations" value="classpath:*Mapper.xml" />
</bean>
<bean id="myDatasource" class="org.springframework.jndi.Jndiobjectfactorybean" lazy-init="true">
<property name="jndiName">
<value>java:/comp/env/jdbc/our-MysqL-database</value>
</property>
</bean>
这很好.但是,我不是Spring的忠实拥护者,并且想知道如何实现自己的纯Java版本的Spring配置文件中所有bean的功能.@H_502_2@
所以我问:要正确实现FruitMapper.java,以便在运行时将其绑定到FruitMapper.xml,我需要编写哪些“胶水代码” /类?这样,每当我写:@H_502_2@
@H_502_2@
FruitMapperDao dao = new FruitMapperDao();
FruitMapperImpl mapper = new FruitMapperImpl(); // <== this is what I need to implement here
dao.setMapper(mapper);
List<Fruit> allFruits = dao.getAllFruits();
…然后我应该在数据源中获得所有水果记录的清单?提前致谢!@H_502_2@
更新@H_502_2@
我还应该提到,鉴于以上设置,我在运行时类路径上需要mybatis.jar和mybatis-spring.jar.我想完全摆脱Spring,并且不需要任何Spring jar或类即可使我的纯Java解决方案正常工作!@H_502_2@
附言您可以像这样在没有Spring的情况下获取sqlSession:@H_502_2@
@H_502_2@
InputStream inputStream = Resources.getResourceAsStream("/mybatis-config.xml");
sqlSessionFactory factory = new sqlSessionFactoryBuilder().build(inputStream);
sqlSession session = factory.openSession();