简体   繁体   English

Spring 引导连接到 H2 数据库

[英]Spring Boot Connect to H2 Database

I was creating an application with Spring Boot and I have this problem.我正在使用 Spring Boot 创建一个应用程序,我遇到了这个问题。 When I send JSON with Postman with the data...当我用 Postman 发送 JSON 和数据时......

在此处输入图像描述

...it returns this: ...它返回这个:

在此处输入图像描述

In H2 the values are inserted as null.在 H2 中,值插入为 null。

在此处输入图像描述

Spring starter code. Spring 入门代码。

Springboothdbh2Application.java Springboothdbh2Application.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
    
@SpringBootApplication
public class Springboothdbh2Application {
    public static void main(String[] args) {
        SpringApplication.run(Springboothdbh2Application.class, args);
    }

}

Customer.java客户.java

package com.example.demo.entity;
    
import java.util.Date;
    
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
    
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
    
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
    
@Entity
@Table(name="tbl_customer")
@Setter
@Getter
@ToString
public class Customer {
    
       @Id
       @GeneratedValue(strategy=GenerationType.IDENTITY)
      private Long id;
    
      private String name;
    
      private Long age;
    
      private String location;
    
       @CreationTimestamp
       @Column(name="created_at", nullable=false, updatable=false)
      private Date createdAt;
    
       @UpdateTimestamp
       @Column(name="updated_at")
      private Date updatedAt;
    
}

CustomerController.java CustomerController.java

    package com.example.demo.controller;

    import java.util.List;
    import java.util.Optional;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.DeleteMapping;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.PutMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.example.demo.entity.Customer;
    import com.example.demo.repository.ICustomerRepo;
    
    @RestController
    @RequestMapping("/api")
    public class CustomerController {
        
        @Autowired
        ICustomerRepo customerRepo;
        
        @GetMapping("/customers")
        public ResponseEntity<List<Customer>> getAllCustomers() {
        try {
            List<Customer> list = customerRepo.findAll();
            
            if (list.isEmpty() || list.size() == 0) {
                return new ResponseEntity<>(HttpStatus.NO_CONTENT);
            }
            
            return new ResponseEntity<>(list, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    @GetMapping("/customers/{id}")
    public ResponseEntity<Customer> getCustomer(@PathVariable Long id) {
        Optional<Customer> customer = customerRepo.findById(id);
        
        if (customer.isPresent()) {
            return new ResponseEntity<>(customer.get(), HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
    
    @PostMapping("/customers")
    public ResponseEntity<Customer> saveCustomer(@RequestBody Customer customer) {
        try {
            return new ResponseEntity<>(customerRepo.save(customer), HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    @PutMapping("/customers")
    public ResponseEntity<Customer> updateCustomer(@RequestBody Customer customer) {
        try {
            return new ResponseEntity<>(customerRepo.save(customer), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    @DeleteMapping("/customers/{id}")
    public ResponseEntity<HttpStatus> deleteCustomer(@PathVariable Long id) {
        try {
            Optional<Customer> customer = customerRepo.findById(id);
            if (customer.isPresent()) {
                customerRepo.delete(customer.get());
            }
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

ICustumerRepo.java ICustomerRepo.java

package com.example.demo.repository;
    
import org.springframework.data.jpa.repository.JpaRepository;
    
import com.example.demo.entity.Customer;
    
public interface ICustomerRepo extends JpaRepository<Customer, Long> {
    
}

This is my Spring Boot application properties file:这是我的 Spring 引导应用程序属性文件:

spring.h2.console.enabled=true


spring.datasource.url=jdbc:h2:mem:crm
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
 
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update

to fix the code add setter to getters ta so in Customer.java在 Customer.java 中修复代码添加 setter 到 getter ta

package com.example.demo.entity;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Entity
@Table(name="tbl_customer")
@Setter
@Getter
@ToString
public class Customer {
    
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    
    private String name;
    
private Long age;

private String location;

@CreationTimestamp
@Column(name="created_at", nullable=false, updatable=false)
private Date createdAt;

@UpdateTimestamp
@Column(name="updated_at")
private Date updatedAt;

public Long getAge() {
    return age;
}

public void setAge(Long age) {
    this.age = age;
}

public String getLocation() {
    return location;
}

public void setLocation(String location) {
    this.location = location;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
    }
    
}

在此处输入图像描述

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

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