Home > AI > Backend > SpringBoot > mysql-connector-java >

Self-refencing Mysql OneToMany + SpringBoot

For example,

Employee.java

@Getter
@Setter
@NoArgsConstructor
@Entity
@Table(name="EMPLOYEE")
public class Employee {

    @Id
    @Column(name="EMPLOYEE_ID")
    @GeneratedValue
    private Long employeeId;

    @Column(name="FIRSTNAME")
    private String firstname;

    @Column(name="LASTNAME")
    private String lastname;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="manager_id")
    private Employee manager;

    @OneToMany(mappedBy="manager", cascade = CascadeType.ALL)
    private Set<Employee> subordinates = new HashSet<Employee>();


    public Employee(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }


    public void setManager(Employee manager) {
        this.manager = manager;
        manager.getSubordinates().add(this);
    }
}

EmployeeRepository.java

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
    Optional<Employee> findByFirstname(String firstname);

}

EmployeeRepositoryTest.java

@RunWith(SpringRunner.class)
@SpringBootTest
public class EmployeeRepositoryTest {

    @Autowired
    EmployeeRepository repository;


    @Before
    public void init() {
        repository.deleteAll();
    }

    @Test
    public void test_employee() {
        Employee manager1 = new Employee("Chuck", "Norris");

        Employee employee1 = new Employee("Sergey", "Brin");
        Employee employee2 = new Employee("Larry", "Page");

        employee1.setManager(manager1);
        employee2.setManager(manager1);

        Employee e1 = repository.save(employee1);
        Employee e2 = repository.save(employee2);

        assertNotNull(e1);
        assertNotNull(e2);

        assertEquals(repository.findAll().size(), 3);

        Employee e = repository.findByFirstname("Larry").get();
        assertEquals(e.getFirstname(), "Larry");
    }


}

applicaiton.properties

##################
# Mysql
##################
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
spring.jpa.show-sql= false

Same relationship is Category, Location and other tree structures.

There are two attentions

1) both ManyToOne and OneToMany should include CascadeType, or error will happen

2) @SpringBootTest would enable @Autowired @RunWith(SpringRunner.class) makes the test can run, or the green run button will not shown.

Leave a Reply