Home > Blockchain >  Spring Boot application is inserting nulls into my mysql table
Spring Boot application is inserting nulls into my mysql table

Time:11-15

I'm trying to create a simple spring boot application that inserts and shows some details about department. I've followed every single step that is needed to create the application.

The Eclipse console shows that it has created the database and table correctly but when it comes to inserting data it simply does not work even though the get one and get all methods work fine after inserting some data manually into the database through mysql workbench.

My application.properties file:

server.port=9001

spring.datasource.url = jdbc:mysql://localhost:3306/department?useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.dbcp2.test-while-idle=true
spring.datasource.dbcp2.validation-query= SELECT 1

# logging.level.org.springframework=DEBUG

# Show or not log for each sql query
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
spring.jpa.hibernate.ddl-auto = create

# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

My Department.java entity class:

package com.micro2.departementservice.department.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;



@Entity
public class Department {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long departmentId;
    @Column(name="name")
    private String deparmentName;
    @Column(name = "address")
    private String deparmentAddress;
    @Column(name = "code")
    private String departmentCode;

    public Department() {
        super();
    }
    public Department(long departmentId, String deparmentName, String deparmentAddress, String departmentCode) {
        super();
        this.departmentId = departmentId;
        this.deparmentName = deparmentName;
        this.deparmentAddress = deparmentAddress;
        this.departmentCode = departmentCode;
    }
    public long getDepartmentId() {
        return departmentId;
    }
    public void setDepartmentId(long departmentId) {
        this.departmentId = departmentId;
    }
    public String getDeparmentName() {
        return deparmentName;
    }
    public void setDeparmentName(String deparmentName) {
        this.deparmentName = deparmentName;
    }
    public String getDeparmentAddress() {
        return deparmentAddress;
    }
    public void setDeparmentAddress(String deparmentAddress) {
        this.deparmentAddress = deparmentAddress;
    }
    public String getDepartmentCode() {
        return departmentCode;
    }
    public void setDepartmentCode(String departmentCode) {
        this.departmentCode = departmentCode;
    }
}

The repository file:

package com.micro2.departementservice.department.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.micro2.departementservice.department.entity.Department;

@Repository
public interface DepartmentRepository extends CrudRepository<Department, Long>{

}

The controller:

package com.micro2.departementservice.department.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.micro2.departementservice.department.entity.Department;
import com.micro2.departementservice.department.repository.DepartmentRepository;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/departments")
@Slf4j
public class DepartmentController {
    
    @Autowired
    private DepartmentRepository repository;
    
    @PostMapping("/")
    public Department saveDepartment(@RequestBody Department department) {
        return repository.save(department);
    }
    
    @GetMapping("/{departmentId}")
    public Department findDepartmentbyId(@PathVariable Long departmentId) {
        return repository.findById(departmentId).get();
    }
    
    @GetMapping("/")
    public List<Department> getAllDepartments() {
        return (List<Department>) repository.findAll();
    }
}

The Eclipse console shows this when I try to insert some data:

Hibernate: 
    insert 
    into
        department
        (address, name, code) 
    values
        (?, ?, ?)

My postman request:

http://localhost:9001/departments/

{
    "name":"AS",
    "address":"123 Street",
    "code":"AS-006"
}

It returns:

{
    "departmentId": 2,
    "deparmentName": null,
    "deparmentAddress": null,
    "departmentCode": null
}

CodePudding user response:

You're using the Department entity class directly in your rest controller.

This class has column names that do not coincide with the member names (for example the column is called name but the member is called departmentName.

When your raw json payload is deserialized into a Department, since the fields don't match, you lose the information you want to insert.

Change your payload to

{
    "departmentName":"AS",
    "departmentAddress":"123 Street",
    "departmentCode":"AS-006"
}

Better still would be to create a DTO object with the fields the way you want them in your rest request and then map that onto your entity. Usually with rest services this is the preferred approach.

For example

public class DepartmentDTO {
    private String name;
    private String address;
    private String code;
    // getters and setters
}

public class Department {
    // your entity as it already is
}

Then create a mapper class somewhere

@Component
public DepartmentMapper {
    public Department toEntity(DepartmentDTO dto) {
        Department entity = new Department();
        entity.setDepartmentName(dto.getName());
        // etc
        return entity;
    }
}

Your controller then becomes

@RestController
@RequestMapping("/departments")
@Slf4j
public class DepartmentController {

    @Autowired
    private DepartmentRepository repository;

    @Autowired
    private DepartmentMapper departmentMapper;

    @PostMapping("/")
    public Department saveDepartment(@RequestBody DepartmentDTO dto) {
        return repository.save(departmentMapper.toEntity(dto));
    }

    // etc

}
  • Related