纯Java MyBatis映射器?

前端之家收集整理的这篇文章主要介绍了纯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

一个示例实现:

  1. public class Fruit {
  2. private String type = "Orange"; // Orange by default!
  3. // Getters & setters,etc. This is just a VO/POJO
  4. // that corresponds to a [fruits] table in my DB.
  5. }
  6. public interface FruitMapper {
  7. public List<Fruit> getAllFruits();
  8. }
  9. public class FruitDao {
  10. private FruitMapper mapper;
  11. // Getters & setters
  12. public List<Fruit> getAllFruits() {
  13. return mapper.getAllFruits();
  14. }
  15. }

FruitMapper.xml

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

mybatis-config.xml

  1. <configuration>
  2. <!-- Nothing special here. -->
  3. </configuration>

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

  1. <bean id="fruitDao" class="net.me.myapp.FruitDao">
  2. <property name="mapper" ref="fruitMapper" />
  3. </bean>
  4. <bean id="fruitMapper" class="org.mybatis.spring.mapper.Mapperfactorybean">
  5. <property name="mapperInterface" value="net.me.myapp.FruitMapper" />
  6. <property name="sqlSessionFactory" ref="sqlSessionFactory" />
  7. </bean>
  8. <bean id="sqlSessionFactory" class="org.mybatis.spring.sqlSessionfactorybean">
  9. <property name="dataSource" ref="myDatasource" />
  10. <property name="configLocation" value="classpath:mybatis-config.xml" />
  11. <property name="mapperLocations" value="classpath:*Mapper.xml" />
  12. </bean>
  13. <bean id="myDatasource" class="org.springframework.jndi.Jndiobjectfactorybean" lazy-init="true">
  14. <property name="jndiName">
  15. <value>java:/comp/env/jdbc/our-MysqL-database</value>
  16. </property>
  17. </bean>

这很好.但是,我不是Spring的忠实拥护者,并且想知道如何实现自己的纯Java版本的Spring配置文件中所有bean的功能.

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

  1. FruitMapperDao dao = new FruitMapperDao();
  2. FruitMapperImpl mapper = new FruitMapperImpl(); // <== this is what I need to implement here
  3. dao.setMapper(mapper);
  4. List<Fruit> allFruits = dao.getAllFruits();

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

更新

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

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

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

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

猜你在找的Spring相关文章