SpringBoot 连接mysql踩到的坑

首先对于用SpringBoot连接mysql我先说明一下pom文件中需要引入那些jar:


 
 
  1. <dependency>
  2. <groupId>mysql </groupId>
  3. <artifactId>mysql-connector-java </artifactId>
  4. <version>6.0.6 </version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot </groupId>
  8. <artifactId>spring-boot-starter-jdbc </artifactId>
  9. <version>2.0.3.RELEASE </version>
  10. </dependency>

当然版本你可以按照自己的需要进行选择,,然后我们在来看配置文件application.properties:


 
 
  1. spring.datasource.name =shopping
  2. spring.datasource.driver- class-name=com.mysql.jdbc.Driver
  3. spring.datasource.url=jdbc:mysql: //127.0.0.1:3306/shopping?useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT
  4. spring.datasource.username=root
  5. spring.datasource.password= 11111
  6. spring.datasource.max-idle= 10
  7. spring.datasource.max-wait= 10000
  8. spring.datasource.min-idle= 5
  9. spring.datasource.initial-size= 5

 如果在启动的过程中提示这样的错误


 
 
  1. Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

那么你在配置application.properties里面:spring-datasource.driver-class-name=com.mysql.cj.jdbc.Driver

上面算是第一个坑

第二个坑可能是和我的的项目有关系:

前台提示这个错误:


 
 
  1. Whitelabel Error Page
  2. This application has no explicit mapping for /error, so you are seeing this as a fallback.
  3. Sun Jul 29 09:41:17 CST 2018
  4. There was an unexpected error (type=Internal Server Error, status=500).
  5. No DataSource set

到Ecplise的控制台看:


 
 
  1. 2018- 07- 29 09: 41: 17.778 ERROR 4724 --- [nio- 7890-exec- 1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: No DataSource set] with root cause
  2. java.lang.IllegalStateException: No DataSource set
  3. at org.springframework.util.Assert.state(Assert.java: 73) ~[spring-core- 5.0.7.RELEASE.jar: 5.0.7.RELEASE]
  4. at org.springframework.jdbc.support.JdbcAccessor.obtainDataSource(JdbcAccessor.java: 77) ~[spring-jdbc- 5.0.7.RELEASE.jar: 5.0.7.RELEASE]
  5. at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java: 371) ~[spring-jdbc- 5.0.7.RELEASE.jar: 5.0.7.RELEASE]
  6. at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java: 446) ~[spring-jdbc- 5.0.7.RELEASE.jar: 5.0.7.RELEASE]
  7. at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java: 456) ~[spring-jdbc- 5.0.7.RELEASE.jar: 5.0.7.RELEASE]
  8. at org.springframework.jdbc.core.JdbcTemplate.queryForList(JdbcTemplate.java: 484) ~[spring-jdbc- 5.0.7.RELEASE.jar: 5.0.7.RELEASE]
  9. at com.wdg.main.util.CommonDao.findList(CommonDao.java: 126) ~[classes/:na]
  10. at com.wdg.main.controller.HelloWorldController.home(HelloWorldController.java: 26) ~[classes/:na]
  11. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na: 1.8.0_60]

看样子是数据源没有配置,可是我上面在application.properties里面配置了啊,大家也看到了,那是怎么回事,重点在这一个语句:

private JdbcTemplate jdbcTemplate=new JdbcTemplate();

我在service里面用到的jdbc模板居然是new出来的,这样就遇到数据源没有设置

那么怎么修改:

    @Autowired
    private JdbcTemplate jdbcTemplate;

上面算是遇到的第二个坑吧,现在想想自己真的挺傻的,居然用new的方式

那么我们来看看第三个坑,也是上面的我们改成为的注入之后,我们看看 前台报什么错误:


 
 
  1. Whitelabel Error Page
  2. This application has no explicit mapping for /error, so you are seeing this as a fallback.
  3. Sun Jul 29 09: 46: 05 CST 2018
  4. There was an unexpected error (type=Internal Server Error, status=500).
  5. No message available

这个是前台给出的页面的提示,我们看看后台报什么错误:


 
 
  1. 018- 07- 29 09: 49: 32.509 ERROR 9792 --- [nio- 7890-exec- 5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
  2. java.lang.NullPointerException: null
  3. at com.wdg.main.util.CommonDao.findList(CommonDao.java: 126) ~[classes/:na]
  4. at com.wdg.main.controller.HelloWorldController.home(HelloWorldController.java: 26) ~[classes/:na]
  5. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na: 1.8.0_60]
  6. at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java: 62) ~[na: 1.8.0_60]
  7. at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java: 43) ~[na: 1.8.0_60]
  8. at java.lang.reflect.Method.invoke(Method.java: 497) ~[na: 1.8.0_60]
  9. at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java: 209) ~[spring-web- 5.0.7.RELEASE.jar: 5.0.7.RELEASE]
  10. at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java: 136) ~[spring-web- 5.0.7.RELEASE.jar: 5.0.7.RELEASE]

空指针的,就是我前面在自动注入的地方,看到吗,如果采用注入的方式会报空指针,这可如何是好,如果用new的方式提示没有设置数据源,如果采用注入的方式提示空指针,真的的是没法玩了。

别着急我们继续,我们上面说我们这个是输入service层,那么我们这个地方也应该采用注入的方式来引用,在Controller里面我们引用service,service也要进行注入才行

看看那我们在Controller里面怎么引用的service:


 
 
  1. @RestController
  2. public class HelloWorldController {
  3. @RequestMapping( "/home")
  4. String home() {
  5. String sql = "select * from userinfo";
  6. List<UserInfo> list_u = new CommonDao().findList(sql, UserInfo.class);
  7. for (UserInfo user : list_u) {
  8. System.out.println(user.toString());
  9. }
  10. return "I love huanhuan";
  11. }
  12. }

看到了么CommonDao,用的是new,这个当然是不行的,怎么修改,我们要改正自动注入的方式:

修改为:


 
 
  1. @RestController
  2. public class HelloWorldController {
  3. @Autowired
  4. private CommonDao dao;
  5. @RequestMapping( "/home")
  6. String home() {
  7. String sql = "select * from userinfo";
  8. List<UserInfo> list_u = dao.findList(sql, UserInfo.class);
  9. for (UserInfo user : list_u) {
  10. System.out.println(user.toString());
  11. }
  12. return "I love huanhuan";
  13. }
  14. }

那么既然使用service使用注入用没有什么要求,当然是用的:

我们需要在service的类项目上面添加:


 
 
  1. @Component
  2. public class CommonDao {
  3. @Autowired
  4. private JdbcTemplate jdbcTemplate;

@Component这样的一个注解,这样就可以了

上面是第2+1坑了,

然后再送你一个,“”静态方法在慎用“”

希望对你有所帮助

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在Spring Boot中连接MySQL数据库有以下几个步骤: 1. 添加MySQL依赖:在项目的pom.xml文件中添加MySQL相关的依赖,例如: ```xml <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency> ``` 2. 配置数据库连接信息:在项目的application.properties(或者application.yml)文件中配置MySQL数据库的连接信息,例如: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=root spring.datasource.password=your_password ``` 3. 创建数据源:在Spring Boot的配置类中创建数据源,并将其注入到容器中,例如: ```java @Configuration public class DataSourceConfig { @Value("${spring.datasource.url}") private String url; @Value("${spring.datasource.username}") private String username; @Value("${spring.datasource.password}") private String password; @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } } ``` 4. 使用JdbcTemplate或者Spring Data JPA进行数据库操作:可以通过自动注入JdbcTemplate或者编写Repository接口来进行数据库的增删改查操作。例如,使用JdbcTemplate: ```java @Repository public class UserRepository { @Autowired private JdbcTemplate jdbcTemplate; public User findById(Long id) { String sql = "SELECT * FROM users WHERE id = ?"; return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(User.class)); } public void save(User user) { String sql = "INSERT INTO users (id, name) VALUES (?, ?)"; jdbcTemplate.update(sql, user.getId(), user.getName()); } // 其他操作方法... } ``` 这样就可以在Spring Boot应用中连接MySQL数据库并进行数据库操作了。当然,在实际使用中,还可以通过配置文件指定连接池、设置其他数据库相关参数等。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值