方法一
导入jar包
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency>
创建spring-dao.xml
1,配置数据源
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverMamagerDataSource"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/yhzz?useSSL=true&useUnicode=true&characterEncoding=utf8"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean>
2,绑定mybaits文件数据源
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean>
3,使用构造器注入
<bean id="sqlSession" class="org.mybaits.spirng.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean>
编写接口和实现累
package com.pojo; import com.dao.Usermpil; import java.util.List; public class User implements Usermpil { private SqlSessionTemplate sqlSession; public List<User> query() { User mapper= sqlSession.getMapper(User.class); return mapper.query(); } }
package com.dao; import com.pojo.User; import java.util.List; public interface Usermpil { List<User> query(); }
测试
package text; import com.pojo.User; import sun.tools.java.ClassPath; public class Text { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml"); User user= context.getBean("user", User.class); for (User user:User.query) { System.out.println(user); } } }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。