bee
bee

Reputation: 137

How to use Spring Boot CRUD API to insert data in multiple tables using one POST endpoint

How can a data be inserted using single POST endpoint in multiple tables. For example there are two tables

1. Employee
2. Department 

enter image description here

These two tables have a primary key and foreign key relationship.

How to achieve data insertion in two tables using a single POST endpoint ?

Upvotes: 1

Views: 2850

Answers (2)

Vladimir
Vladimir

Reputation: 710

Ok I see what you want.... your entities have to look like this...

You have to create a one to one relationship something like this:

Department entity:

@Entity
@Table
@Data
public class Department {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;
   private String name;
   private String description;
}

Employee entity:

@Entity
@Table
@Data
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    private String email;
    private String address;
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "department_id", referencedColumnName = "id")
    private Department department;
}

And than you can add Data on Startup like this:

@Component
public class DBSeeder implements CommandLineRunner {
    @Autowired
    private EmployeeRepository repository;

    @Override
    public void run(String... args) throws Exception {
        Department dep1 = new Department();
        dep1.setName("Demolition");
        dep1.setDescription("Do demo");

        Employee emp1 = new Employee();
        emp1.setName("John Rambo");
        emp1.setEmail("[email protected]");
        emp1.setAddress("Demolition Av. 5");
        emp1.setDepartment(dep1);

        this.repository.save(emp1);


    }
 }

Upvotes: 1

Vladimir
Vladimir

Reputation: 710

@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Long> {
  Employee save(Employee employee);
}

Do you also ask how the entity objects have to look like?

Upvotes: 0

Related Questions