簡體   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