Skip to content

Instantly share code, notes, and snippets.

@madan712
Last active June 29, 2019 12:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madan712/cf93b1d1a60b0afdb73834520b58472a to your computer and use it in GitHub Desktop.
Save madan712/cf93b1d1a60b0afdb73834520b58472a to your computer and use it in GitHub Desktop.
My Sql + Spring Boot JPA - One to many, many to one example
package com.javaxp;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.javaxp.model.Department;
import com.javaxp.model.Employee;
import com.javaxp.repository.DepartmentRepository;
import com.javaxp.repository.EmployeeRepository;
@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
private EmployeeRepository employeeRepository;
@Autowired
private DepartmentRepository departmentRepository;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
public void run(String... args) throws Exception {
System.out.println("---Saving departments..");
Department dept = new Department();
dept.setDepartmentName("Technology");
departmentRepository.save(dept);
System.out.println(dept);
System.out.println("---Saving employees..");
Employee emp1 = new Employee();
emp1.setEmployeeName("Mark");
emp1.setDepartment(dept);
employeeRepository.save(emp1);
System.out.println(emp1);
Employee emp2 = new Employee();
emp2.setEmployeeName("Larry");
emp2.setDepartment(dept);
employeeRepository.save(emp2);
System.out.println(emp2);
System.out.println("---Printing all employees..");
List<Employee> employeeList = employeeRepository.findAll();
employeeList.forEach(employee -> {
System.out.println(employee);
});
System.out.println("---Deleting employee..");
employeeRepository.delete(emp1);
System.out.println("---Again printing all employees");
employeeList = employeeRepository.findAll();
employeeList.forEach(employee -> {
System.out.println(employee);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment