为什么Spring Boot应用程序实体ID无法自动生成

时间:2020-07-21 13:03:41

标签: java spring-boot post

在应用程序模型中:-

    @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   + "]";
    }
}

控制器:-

    @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'Content-Type:application / json'
--data-raw'{

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

}'

我收到以下错误消息:-

2020-07-21 14:00:18.938错误3740-[nio-8080-exec-7] oaccC [。[。[/]。[dispatcherServlet]:Servlet [dispatcherServlet]的Servlet.service()在路径为[]的情况下引发异常[请求处理失败;嵌套的异常是org.springframework.dao.InvalidDataAccessApiUsageException:给定的ID不能为null!嵌套的异常是java.lang.IllegalArgumentException:给出的ID不能为null!],其根本原因是

java.lang.IllegalArgumentException:给定的ID不能为null!

如果我通过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
 );

data.sql:-

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

1 个答案:

答案 0 :(得分:0)

检查数据库表配置,并为id列添加自动增量(如果不存在)。您可以对其进行配置并包括在liquibase xml文件中,以便在启动时或将来在新的数据库模式中启动时自动进行配置。