繁体   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