繁体   English   中英

Spring Boot MySQL

[英]Spring Boot MySQL

我正在尝试访问我的数据库并返回一些结果。 我看过一堆教程,但每个教程似乎都不多。 现在,@ Autowired发出错误消息“找不到UserRepository类型的Bean。如果有人可以帮助我,将不胜感激。 这是我到目前为止所拥有的。

控制者

package com.rdopler.ecommerceTest.controller;
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(path="/user")
public class UserController {

    @Autowired
    UserRepository userRepository;
    @GetMapping
    public String check() {
        return "Welcome";
    }
@GetMapping(path="/getusernames")
    public List<String>getAllUserNames() {

        return userRepository.getAllUserNames();

    }
}

回购

package com.rdopler.ecommerceTest.repository;

import org.springframework.beans.factory.annotation.Autowired;
import java.util.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class UserRepository {
    @Autowired
    JdbcTemplate jdbcTemplate;
    public List<String> getAllUserNames() {

        List<String> usernameList = new ArrayList<>();
        usernameList.addAll(jdbcTemplate.queryForList("select * from employees ", String.class);
        return usernameList;
    }
}

application.properties

spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=jdbc:mysql://localhost:3306/storeDB?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=*****

主要:

package com.rdopler.ecommerceTest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class EcommerceTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(EcommerceTestApplication.class, args);
    }

}

请尝试在主类中添加@EnableJpaRepositories(“ packagename”)。

在您的主应用程序中,尝试在@SpringBootApplication下面添加此批注

@ComponentScan(basePackages = "com.rdopler.ecommerceTest")

它将帮助您扫描所有组件。 另外,如果您的应用程序中有任何服务,请确保使用@Service注释对该服务进行注释。

将@Component添加到类UserRepository

在UserRepository中添加@Transactional,也在主类中添加@ComponentScan。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM