简体   繁体   中英

Why Spring Boot app entity id doesn't auto generate

In the app 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;
    }

}

When I tried to test by curl POST request as:-

curl --location --request POST 'localhost:8080 /employees'
--header 'Content-Type: application/json'
--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; nested exception is 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!

If I pass id then it works. Why id doesn't auto generated? How to fix this issue?

More code:

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:-

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');

check your database table configuration and add autoincrement for the id column if it doesn't exist. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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