Как посмотреть данные моей базы данных H2, почему localhost: 8080 / h2_console не работает? - PullRequest
2 голосов
/ 04 мая 2019

Я хочу видеть данные в моей базе данных h2. Я не знаю в чем я не прав У меня есть эта конфигурация в файле .properties

spring.h2.console.enabled=true
spring.h2.console.path=/h2_console
spring.datasource.url=jdbc:h2:file:~/test
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
#spring.jpa.hibernate.ddl-auto=create
spring.jpa.hibernate.ddl-auto = update

#spring.jpa.hibernate.hbm2ddl.auto:validate

когда я делаю запрос в Chrome http://localhost:8080/h2_console я получаю эту ошибку:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Fri May 10 00:37:28 BOT 2019
There was an unexpected error (type=Not Found, status=404).
No message available

это мой контроллер:

package com.example.demo.controller;

import com.example.demo.model.Friendship;
import com.example.demo.model.User;
import com.example.demo.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.logging.Logger;

@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
@RestController
@RequestMapping({"/user"})
public class UserController {

    @Autowired
    UserServiceImpl userServiceImpl;
    static Logger log = Logger.getLogger(UserController.class.getName());

   @GetMapping(path = {"/"})
public Meet getBook() {
    log.info("HELLO WORDL");
    return null;
} 
    @PostMapping("/create")
    public ResponseEntity<User> createUser(@RequestBody User user) {
        log.info("CREATE");
        return new ResponseEntity<User>(userServiceImpl.createUser(user), HttpStatus.OK);
    }


    @PostMapping("/addFriend")
    public ResponseEntity<User> getUser(@RequestParam("owner") Long ownerId, @RequestParam("friend") Long friendId) {
        return new ResponseEntity<User>(userServiceImpl.createLinkWithFriends(ownerId, friendId), HttpStatus.OK);
    }

    @GetMapping("/owner/{id}/friends")
    public ResponseEntity<List<User>> getFriendsOf(@PathVariable("id") Long ownerId) {
        return new ResponseEntity<List<User>>(userServiceImpl.getFriendsOf(ownerId), HttpStatus.OK);
    }

    @GetMapping("/getUsers")
    public ResponseEntity<List<User>> getUsers() {
        log.info("getUser");
        return new ResponseEntity<>(userServiceImpl.getUsers(), HttpStatus.OK);
    }

    @GetMapping("/showFriends/{id}")
    public ResponseEntity<List<User>> getUsers(@PathVariable("id")  int id) {
        log.info("showFriends"+id);
        return new ResponseEntity<>(userServiceImpl.getUsers(), HttpStatus.OK);
    }

}

Когда я использую это http://localhost:8080/user/ Я получаю это сообщение от контроллера Hello World!

это мой путь моего проекта:

C:\Users\DELL\Desktop\txts\aquiesta\springTeam\traslateInClick\src\main\resources\application.properties

это мой репо https://github.com/hubmanS/traslateInClick

это моя зависимость.

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>

Ответы [ 2 ]

2 голосов
/ 10 мая 2019

Согласно приведенному ниже коду, ваш контекстный путь также является "" (пустым).

@RestController
@RequestMapping({"/"})
public class MeetController{
...
}

И в соответствии с кодом в классе контроллера проблема связана только с отображением вашего URL.Ваш URL /h2_console конфликтует с /{id} URL метода getBook.

@GetMapping(path = {"/{id}"})
    public Meet getBook(@PathVariable("id") int id) {
        return null;
    }

Я бы предложил вам добавить правильный контекстный путь для вашего приложения, чтобы URL вашего приложения не конфликтовал сh2-console URL.Вышеуказанные конфигурации иногда работают и терпят неудачу в других случаях.Ваша консоль откроется, если URL-адрес контекста базы данных h2 будет зарегистрирован, если он не получит регистрацию, вы получите страницу с ошибкой, которую вы получаете прямо сейчас.

Рекомендуемое решение:

приложениеСвойства*

Чтобы получить книгу: http://localhost:8080/book/{id}/

Чтобы создать книгу: http://localhost:8080//create/{name}/author/{id}/

Чтобы позвонить домой: http://localhost:8080/book/

Для доступаКонсоль h2 DB: http://localhost:8080/h2_console/login.jsp

2 голосов
/ 04 мая 2019

У вас есть конфликт сопоставления URL, вызванный одним из ваших методов GET

@GetMapping(path = {"/{id}"})
public Meet getBook(@PathVariable("id") int id) {
    return null;
}

h2_console будет преобразован в метод getBook в виде строки и выдает исключение, поскольку ваш метод принимает только int. Имея в виду стратегию именования RESTful , вы должны изменить свое отображение на:

@GetMapping(path = {"/books/{id}"})
public Meet getBook(@PathVariable("id") int id) {
    return null;
}
...