简体   繁体   English

为什么 Spring 引导应用程序实体 ID 不会自动生成

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

In the app Model:-在应用程序 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:- 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;
    }

}

When I tried to test by curl POST request as:-当我尝试通过 curl POST 请求进行测试时:-

curl --location --request POST 'localhost:8080 /employees' curl --location --request POST 'localhost:8080 /employees'
--header 'Content-Type: application/json' --header '内容类型:应用程序/json'
--data-raw '{ --data-raw '{

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

}' }'

I got error as:-我收到错误:-

2020-07-21 14:00:18.938 ERROR 3740 --- [nio-8080-exec-7] oac.c.C.[.[.[/].[dispatcherServlet]: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; 2020-07-21 14:00:18.938 ERROR 3740 --- [nio-8080-exec-7] oac.c.C.[.[.[/].[dispatcherServlet]: Servlet.service() for servlet [带有路径 [] 的上下文中的 dispatcherServlet] 引发异常 [请求处理失败; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: The given id must not be null;.嵌套异常是 org.springframework.dao.InvalidDataAccessApiUsageException: The given id must not be null;. nested exception is java.lang:IllegalArgumentException: The given id must not be null!] with root cause嵌套异常是 java.lang:IllegalArgumentException: The given id must not be null!] 根本原因

java.lang.IllegalArgumentException: The given id must not be null! java.lang.IllegalArgumentException:给定的 id 不能为空!

If I pass id then it works.如果我通过 id 那么它可以工作。 Why id doesn't auto generated?为什么 id 不自动生成? How to fix this issue?如何解决这个问题?

More code:更多代码:

application.properties:- 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

In the resource folder I have:-在资源文件夹中我有: -

Service:-服务:-

@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:- 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
 );

data.sql:-数据.sql:-

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

check your database table configuration and add autoincrement for the id column if it doesn't exist.检查您的数据库表配置并为 id 列添加自动增量(如果不存在)。 You can configure this and include in liquibase xml files as well to be auto configured at startup or when starting in a new database schema in the future.您可以对其进行配置并包含在 liquibase xml 文件中,也可以在启动时或将来在新的数据库模式中启动时自动配置。

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

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