经过上篇博客,我们已经可以简单的搭建项目了,我们接着上篇博客介绍:
我们这篇博客目的是将数据库的mapper继承进来,让这个spring boot项目看起来更像是web应用;
开始:
既然要查询数据库,肯定要spring支持jdbc啊,我们先在maven中添加jdbc的依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
首先我们按照我们平常的习惯建几个文件:
Mapper文件:
@Repository
public class jdbcMapper {
@Autowired
private JdbcTemplate jdbcTemplate;
@SuppressWarnings("unchecked")
public String getMsg(){
return jdbcTemplate.query("select * from table1",new ResultSetExtractor() {
public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
int id = 0 ;
while (rs.next()) {
id = rs.getInt("id");
}
return Integer.toString(id);
}
});
}
}
Service接口
public interface testService {
public String getMsg();
}
Service实现类
@Service
public class testServiceImpl implements testService{
@Autowired
private jdbcMapper jdbcMapper;
public String getMsg(){
return jdbcMapper.getMsg();
}
}
这样三步是不是建好了呀,controller->service->mapper
这时候启动项目会发现报错了,说datasource注入失败
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
所以你会发现spring boot比你想象的都智能,spring的一套体系都在这儿体现出来了;(mapper)
那我们先解决错误,database没注入,我们就去注入喽;
对啊,连接数据库,怎么可以没有sqlSessionFactory和数据库的配置文件来注入呢?
我们来到强大的Application.properties,【说句题外话,继承各种各样的插件时,个人不建议建各种各样的文件然后再进行手工引入,你可以先查看一下spring boot本身引入这种插件了吗,然后直接在Application.properties配置就Ok了,没必要搞一堆的配置文件,搞得最后部署的时候特别麻烦,】说多了,我们先把数据库的参数加上;
我这儿就先用mysql了;
spring.datasource.url=
spring.datasource.username
spring.datasource.password=
spring.datasource.driver-class-name=
spring boot就会自动帮我们注入进去了,不需要像spring框架的xml文件;
再启动,此时你会发现报错:找不到你的数据库的驱动类,好了,上maven的pom.xml中添加:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.24</version>
</dependency>
在mysql中创建一张table1表
Create table table1(id int);
Insert into table1 value(1);
这时再启动,成功启动;
我们访问:http://localhost:2600/
返回1;
这样的话是不是跟我们的tomcat后台程序一模一样了呢,但是现在谁还会写纯粹的jdbc呢,都是用数据库框架呀,这里我们继承一下mybatis框架;
引入依赖包:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
我们再先建一个mapper
@Mapper
public interface testMapper {
public String getMsg1();
}
在其它的service和controller中添加getMsg1()方法
在src/main/resources中添加mybatis,mybatis中添加user.xml
内容为:
<?xml version="1.0" encoding="UTF-8"?>
<mapper namespace="org.test1.mapper.testMapper">
<select id="getMsg1" resultType="java.lang.Integer">
select id from table1
</select>
</mapper>
注意:namespace为mapper的路径
这样的话是不是和ssm很接近了呢,但是spring框架中该xml的路径尚且需要指定,这儿也不例外啊,不过spring boot只要可以扫描到就OK了,我们用一个扫描的注解@MapperScan
另外将application.java中添加注解
@ComponentScan
@MapperScan("org.test1.mapper");
添加三个@bean即可;
还需要再application中把数据库的sqlSessionFactory重新生成一下,让它去找我们的文件匹配去,spring boot默认情况下可不会那么高级的自动帮我们匹配去。
最后我们看application.java
@ComponentScan
@MapperScan("org.test1.mapper")
@SpringBootApplication
public class Application {
@Bean
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource(){
return new org.apache.tomcat.jdbc.pool.DataSource();
}
@Bean(name="sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() throws Exception{
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean
public PlatformTransactionManager transactionManager(){
return new DataSourceTransactionManager(dataSource());
}
public static void main(String args[]){
SpringApplication.run(Application.class);
}
}
还有一种用mybatis的简单方法:
不用在application中配置,直接在mapper接口中调用mybatis的注解
@Select("select id from table1")
public int getMsg3();
这种方法sql少的情况下还行,多了就不适用了;
附:这篇博客中我们用到了一些注解,玩过spring框架的可能很懂,没玩过的可能不怎么懂,spring boot其实强调抛弃spring的各种配置文件,转化为注解的形式,我们应该更多的了解注解才能玩转spring boot;
spring boot虽然有些在功能上和spring的注解有些区别,但是大体请款还是出自同源的,大同小异,之后我有时间会专门讲一下这些常用注解
@MapperScan
@ComponentScan
@bean