因为想看一下mybatis-Spring项目的代码,所有从github上将源码下载下来了,我看了一下,可能是测试类太多了,就没有细找入口类,所以自己写了一个主入口类,特此记录(我本地已经安装Mysql数据库)
首先项目没有数据库驱动,所以添加一下
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </dependency>
然后添加mapper接口类
package org.mybatis.spring.demo.mapper; public interface DemoMapper { String getById(); }
添加对应的xml文件,在resource/mapper/目录下
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="org.mybatis.spring.demo.mapper.DemoMapper"> <select id="getById" resultType="String"> SELECT stu_id FROM record WHERE id = 1 </select> </mapper>
最后添加一个配置类
package org.mybatis.spring.demo; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.jdbc.datasource.DriverManagerDataSource; import javax.sql.DataSource; @Configuration @MapperScan("org.mybatis.spring.demo.mapper") public class DemoConfig { ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(); @Bean public SqlSessionFactoryBean getSqlSessionFactoryBean(@Autowired DataSource dataSource) throws Exception{ SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); Resource[] resources = resourceResolver.getResources("mapper/*.xml"); bean.setMapperLocations(resources); return bean; } @Bean public DataSource dataSource(){ DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/test"); dataSource.setUsername("root"); dataSource.setPassword("root"); return dataSource; } }
添加一个主类做一下测试即可
package org.mybatis.spring; import org.mybatis.spring.demo.DemoConfig; import org.mybatis.spring.demo.mapper.DemoMapper; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class); DemoMapper bean = context.getBean(DemoMapper.class); System.out.println(bean.getById()); System.out.println(bean.toString()); } }
整体添加的目录结构是这样的
结束。