我有一个使用Mybatis(v3.0.5)进行OR /映射的项目。典型(功能)设置如下:
Fruit
FruitMapper.xml
- 所有SQL查询都在哪里FruitMapper.java
FruitDao
mybatis-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>
这很有效。但是,我不是春天的忠实粉丝,并且想知道如何实现我自己的纯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();
...那么我应该得到我的数据源中所有fruit
条记录的列表?提前谢谢!
我还应该提一下,鉴于上面的设置,我在运行时类路径上需要mybatis.jar
和mybatis-spring.jar
。我想完全摆脱Spring,并且不需要任何Spring jar或类来使我的纯Java解决方案工作!
答案 0 :(得分:3)
您需要获取SqlSession
个实例(例如名为session
)并调用方法session.getMapper(FruitMapper.class)
。您将获得一个已经实现mapper接口的对象,然后只需调用它的方法从DB获取数据。
P.S。您可以像这样获得没有Spring的SqlSession:
InputStream inputStream = Resources.getResourceAsStream("/mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = factory.openSession();