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

OneToMany-JpaRepository-save (parent entity)

Customer.java

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "Customer")
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String name;

    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<Number> numbers;


    public void addNumber(Number number) {
        if (number == null){
            return;
        }

        if (this.numbers == null) {
            this.numbers = new HashSet<>();
        }

        this.numbers.add(number);
        number.setCustomer(this);
    }
}

Number.java

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "Number")
public class Number {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String number;
    private String type;

    @ManyToOne
    @JoinColumn(name = "customer_id")
    private Customer customer;
}

CustomerRepository.java

@Repository
public interface CustomerRepository extends JpaRepository<Customer, Long> {
}

NumberRepository.java

@Repository
public interface NumberRepository extends JpaRepository<Number, Long> {
}

TestRepository.java

@Slf4j
@SpringBootTest
public class TestRepository {


    @Autowired
    CustomerRepository customerRepository;
    @Autowired
    NumberRepository numberRepository;


    @BeforeEach
    public void init() {
        customerRepository.deleteAll();
        numberRepository.deleteAll();
    }

    @Test
    public void testCreateCustomer() {
        Customer customer = new Customer();
        customer.setName("Mert");

        Number p1 = new Number();
        p1.setNumber("111");
        p1.setType("cell");

        Number p2 = new Number();
        p2.setNumber("222");
        p2.setType("home");


        customer.addNumber(p1);
        customer.addNumber(p2);

        // both entities are saved, but
        customerRepository.save(customer);

    }
}

Attention

  • You need to let both entity add the other entity, dealing with addNumber by yourself.
  • Cannot use @Data, otherwise the embedded @ToString would cause the loop to cause Stackoverflow error.

You need to replace @Data with @Getter and @Setter

Leave a Reply