嗨呀,好气!!!今天在用springboot整合mybatis时,连踩数坑,摔得我头昏脑涨嗡嗡直响,所有的坑都被我踩了一遍,下面就记录一下令人崩溃的三个小时- - -
先是来个UserDao找不到:
Field userDao in com.dec14.service.UserService required a bean of type 'com.dec14.dao.UserDao' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
那我不服,先给你required改成false,先运行再说嘛
//
@Service
public class UserService {
@Autowired(required = false)
UserDao userDao;
public User findUserById(int id){
User user = userDao.findById(id);
return user;
}
}
好家伙,它也闹脾气了
来个空指针异常:
java.lang.NullPointerException: null
at com.dec14.service.UserService.findUserById(UserService.java:14) ~[classes/:na]
意思就是userdao对象没注册到ioc容器中,强行注入调方法,那肯定空指针异常了
赶紧去百度,去查,在启动类加上了@MapperScan注解:
正常启动了。
兴高采烈的去访问,结果是:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Dec 14 17:13:24 CST 2020
There was an unexpected error (type=Internal Server Error, status=500).
500嘛,就说明页面没错,错的是服务器端
看了看编译后的发现classes文件夹下没有我写的xml映射文件啊,spring默认是不编译xml文件的,原来是忘记在pom添加这段了:
// 把xml文件编译了
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
内个,我也加上了这段配置文件,这时候给爷来了这么一出:
绑定异常:无效的绑定:
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.dec14.dao.UserDao.findById
好像说我绑定异常,找不到方法。经过多方查询,似乎是我配置文件写的有丶问题
//
#映射文件位置
mybatis.mapper-locations=classpath:/com.dec14.dao/*.xml
我把目录里那个 . 都改成了/
//
#映射文件位置
mybatis.mapper-locations=classpath:/com/dec14/dao/*.xml
改完了再启动运行,访问地址:
数据库sql语法错误:
//
java.sql.SQLSyntaxErrorException: Unknown database 'localhost:3306/miaosha
而且项目还在一直转圈尝试连接。
重新排查了一遍,终于发现:
我大意了!!!
在配置文件声明数据源时,数据源的url写的有丶问题:
spring.datasource.url=jdbc:mysql:/localhost:3306/miaosha?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
jdbc:mysql:少写了一个 / 有没有!!!
赶紧加上再来一次
spring.datasource.url=jdbc:mysql://localhost:3306/miaosha?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
-----------终于成功了----------
总结:
1、经验不足
2、粗心大意
3、springboot不讲武德
==================================================================================================
为了梦想,为了鸣鸣,冲冲冲冲咿呀咿呀哟😃😃😃😃😃