簡體   English   中英

為什么 Spring 引導應用程序實體 ID 不會自動生成

[英]Why Spring Boot app entity id doesn't auto generate

在應用程序 Model 中:-

    @Entity
@Table(name="TBL_EMPLOYEES")
public class EmployeeEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(name="first_name")
    private String firstName;
    
    @Column(name="last_name")
    private String lastName;
    
    @Column(name="email", nullable=false, length=200)
    private String email;

    public EmployeeEntity() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "EmployeeEntity [id=" + id + ", firstName=" + firstName + 
                ", lastName=" + lastName + ", email=" + email   + "]";
    }
}

Controller:-

    @RestController
@RequestMapping("/employees")
public class EmployeeController {
    @Autowired
    EmployeeService service;

    @GetMapping
    public ResponseEntity<List<EmployeeEntity>> getAllEmployees() {
        List<EmployeeEntity> list = service.getAllEmployees();

        return new ResponseEntity<List<EmployeeEntity>>(list, new HttpHeaders(), HttpStatus.OK);
    }

    @GetMapping("/{id}")
    public ResponseEntity<EmployeeEntity> getEmployeeById(@PathVariable("id") Long id)
            throws RecordNotFoundException {
        EmployeeEntity entity = service.getEmployeeById(id);

        return new ResponseEntity<EmployeeEntity>(entity, new HttpHeaders(), HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity<EmployeeEntity> createOrUpdateEmployee(@RequestBody EmployeeEntity employee)
            throws RecordNotFoundException {
        EmployeeEntity updated = service.createOrUpdateEmployee(employee);
        return new ResponseEntity<EmployeeEntity>(updated, new HttpHeaders(), HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public HttpStatus deleteEmployeeById(@PathVariable("id") Long id)
            throws RecordNotFoundException {
        service.deleteEmployeeById(id);
        return HttpStatus.OK;
    }

}

當我嘗試通過 curl POST 請求進行測試時:-

curl --location --request POST 'localhost:8080 /employees'
--header '內容類型:應用程序/json'
--data-raw '{

"firstName": "firstName",
"lastName": "lastName",
"email": "xxx@test.com"

}'

我收到錯誤:-

2020-07-21 14:00:18.938 ERROR 3740 --- [nio-8080-exec-7] oac.c.C.[.[.[/].[dispatcherServlet]: Servlet.service() for servlet [帶有路徑 [] 的上下文中的 dispatcherServlet] 引發異常 [請求處理失敗; 嵌套異常是 org.springframework.dao.InvalidDataAccessApiUsageException: The given id must not be null;. 嵌套異常是 java.lang:IllegalArgumentException: The given id must not be null!] 根本原因

java.lang.IllegalArgumentException:給定的 id 不能為空!

如果我通過 id 那么它可以工作。 為什么 id 不自動生成? 如何解決這個問題?

更多代碼:

application.properties:-

spring.datasource.url=jdbc:h2:c:/temp/tempdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
# Enabling H2 Console
spring.h2.console.enabled=true
# Custom H2 Console URL
spring.h2.console.path=/h2
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto=update
# Show all controller mapping
logging.level.org.springframework.web.servlet.mvc.method.annotation=trace
#Turn Statistics on and log SQL stmts
spring.jpa.properties.hibernate.format_sql=true
#If want to see very extensive logging
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.generate_statistics=true
logging.level.org.hibernate.type=trace
logging.level.org.hibernate.stat=debug
log4j.category.org.springframework.web=INFO
logging.level.org.hibernate.SQL=DEBUG

在資源文件夾中我有: -

服務:-

@Service
public class EmployeeService {

@Autowired
EmployeeRepository repository;

public List<EmployeeEntity> getAllEmployees() {
    List<EmployeeEntity> employeeList = repository.findAll();

    if (employeeList.size() > 0) {
        return employeeList;
    } else {
        return new ArrayList<EmployeeEntity>();
    }
}

public EmployeeEntity getEmployeeById(Long id) throws RecordNotFoundException {
    Optional<EmployeeEntity> employee = repository.findById(id);

    if (employee.isPresent()) {
        return employee.get();
    } else {
        throw new RecordNotFoundException("No employee record exist for given id");
    }
}

public EmployeeEntity createOrUpdateEmployee(EmployeeEntity entity) throws RecordNotFoundException {
    return repository.save(entity);
}

public void deleteEmployeeById(Long id) throws RecordNotFoundException {
    Optional<EmployeeEntity> employee = repository.findById(id);

    if (employee.isPresent()) {
        repository.deleteById(id);
    } else {
        throw new RecordNotFoundException("No employee record exist for given id");
    }
}

}

schema.sql:-

DROP TABLE IF EXISTS TBL_EMPLOYEES;

 CREATE TABLE TBL_EMPLOYEES (
 id INT AUTO_INCREMENT  PRIMARY KEY,
 first_name VARCHAR(250) NOT NULL,
 last_name VARCHAR(250) NOT NULL,
 email VARCHAR(250) DEFAULT NULL
 );

數據.sql:-

INSERT INTO 
TBL_EMPLOYEES (first_name, last_name, email) 
VALUES
('Lokesh', 'Gupta', 'howtodoinjava@gmail.com'),
('John', 'Doe', 'xyz@email.com');

檢查您的數據庫表配置並為 id 列添加自動增量(如果不存在)。 您可以對其進行配置並包含在 liquibase xml 文件中,也可以在啟動時或將來在新的數據庫模式中啟動時自動配置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM