как подключить postgres в проекте gradle

#postgresql #spring-boot

#postgresql #весенняя загрузка

Вопрос:

Я пытаюсь подключить postgres в своем проекте, вот моя конфигурация

application.properties

 spring.jpa.show-sql = true

spring.datasource.username = postgres
spring.datasource.password = password
spring.datasource.driverClassName = org.postgresql.Driver
spring.datasource.url = jdbc:postgresql://localhost:5432/postgres
  

build.gradle

 dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-jdbc'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'org.postgresql:postgresql'
    annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
  

Person.java

 @Entity
@Table
@Data
public class Person {
    @Id
    @NotNull
    private int id;
    @NotNull
    private String name;
    public Person(int id, String name){
        this.setId(id);
        this.setName(name);
    }
}
  

PersonRepository.java

 @Repository
public interface PersonRepository extends JpaRepository<Person, Integer> {
}
  

PersonService.java

 @Service
public class PersonService {
    @Autowired
    private PersonRepository personRepository;
    public Person create(int id, String name){return personRepository.save(new Person(id, name));}
}
  

контроллер

 @RestController
@SpringBootApplication
public class PostgresdemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(PostgresdemoApplication.class, args);
    }
    @GetMapping("/hello")
    public String hello(@RequestParam(value = "name", defaultValue = "world") String name){
        return String.format("Hello, %s", name);
    }
    @GetMapping("/create")
    public Person create(@RequestParam int id, @RequestParam String name){
        return new PersonService().create(id, name);
    }   
}
  

когда я запускаю приложение spring и ввожу http://localhost:8080/create?id=7amp;name=name

есть исключение

 java.lang.NullPointerException: null
        at com.example.postgresdemo.PersonService.create(PersonService.java:12) ~[main/:na]
        at com.example.postgresdemo.PostgresdemoApplication.create(PostgresdemoApplication.java:24) ~[main/:na]
  

Я много искал и не мог найти, в чем проблема. что я могу сделать?

Комментарии:

1. где класс контроллера?

2. добавлен контроллер @hirarqi

Ответ №1:

попробуйте сделать это так

 @RestController
@SpringBootApplication
public class PostgresdemoApplication {

    @Autowired
    private PersonService personService;

    public static void main(String[] args) {
        SpringApplication.run(PostgresdemoApplication.class, args);
    }
    @GetMapping("/hello")
    public String hello(@RequestParam(value = "name", defaultValue = "world") String name){
        return String.format("Hello, %s", name);
    }
    @GetMapping("/create")
    public Person create(@RequestParam int id, @RequestParam String name){
        return new personService.create(id, name);
    }   
}
  

Комментарии:

1. большое вам спасибо. после того, как я напишу таким образом и добавлю конструктор по умолчанию для Person. Это работает!