1.导入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
2.配置类的设置
简述:配置类需要完成的、有关整合的有以下几点:
1.指定 Mapper 接口的位置
2.注册数据源
3.注册 SqlSessionFactory
@Configuration
@PropertySource(value={"classpath:jdbc.properties"})
@MapperScan(basePackages = "com.yuke.mapper")
@ComponentScan(basePackages = "com.yuke")
public class MyConfig {
@Value(value = "${jdbc.driver}")
private String driverClassName;
@Value(value = "${jdbc.username}")
private String username;
@Value(value = "${jdbc.password}")
private String password;
@Value(value = "${jdbc.url}")
private String url;
@Bean
public DataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(this.driverClassName);
dataSource.setUrl(this.url);
dataSource.setUsername(this.username);
dataSource.setPassword(this.password);
return dataSource;
}
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception{
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
factory.setDataSource(dataSource());
factory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/*.xml"));
return factory.getObject();
}
}
3.测试
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {MyConfig.class})
public class Test {
@Autowired
private PersonMapper personMapper;
@org.junit.Test
public void test1() throws Exception{
System.out.println(personMapper.getPersonById(1));
}
}