微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

纯Java MyBatis映射器?

我有一个使用Mybatis(v3.0.5)进行OR /映射的项目.典型(运行)设置如下:

>要映射的POJO-水果
>一个“ MyBatis”映射器XML文件-FruitMapper.xml-所有SQL查询都在其中
>定义所有相同映射器方法的接口映射器-FruitMapper.java
>具有接口映射器参考的DAO-FruitDao
> MyBatis配置文件-mybatis-config.xml
>将所有内容Spring config XML链接在一起-myapp-spring-config.xml

一个示例实现:

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

<mapper namespace="net.me.myapp.FruitMapper">
    <select id="getAllFruits" resultSetType="FORWARD_ONLY">
        SELECT * FROM fruits
    </select>
</mapper>

mybatis-config.xml

<configuration>
    <!-- nothing special here. -->
</configuration>

myapp-spring-config.xml :(这就是我想要摆脱的)

<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的功能.

所以我问:要正确实现FruitMapper.java,以便在运行时将其绑定到FruitMapper.xml,我需要编写哪些“胶水代码” /类?这样,每当我写:

FruitMapperDao dao = new FruitMapperDao();
FruitMapperImpl mapper = new FruitMapperImpl(); // <== this is what I need to implement here
dao.setMapper(mapper);

List<Fruit> allFruits = dao.getAllFruits();

…然后我应该在数据源中获得所有水果记录的清单?提前致谢!

更新

我还应该提到,鉴于以上设置,我在运行时类路径上需要mybatis.jar和mybatis-spring.jar.我想完全摆脱Spring,并且不需要任何Spring jar或类即可使我的纯Java解决方案正常工作!

最佳答案
您需要获取一个sqlSession实例(例如,命名会话),并调用方法session.getMapper(FruitMapper.class).您将获得一个已经实现了mapper接口的对象,然后只需调用它的方法即可从DB获取数据.

附言您可以像这样在没有Spring的情况下获取sqlSession:

InputStream inputStream = Resources.getResourceAsstream("/mybatis-config.xml");
sqlSessionFactory factory = new sqlSessionFactoryBuilder().build(inputStream);
sqlSession session = factory.openSession();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐