接下来我们为新实体创建映射:

    1. package com.lugew.springbootddd;
    2. import lombok.Getter;
    3. import lombok.Setter;
    4. import javax.persistence.Entity;
    5. import javax.persistence.Id;
    6. @Entity
    7. @Setter
    8. @Getter
    9. public class SnackDto {
    10. @Id
    11. private long id;
    12. private String name;
    13. public Snack convertToSnack() {
    14. if (id == 0) return Snack.None;
    15. else if (id == 1) return Snack.Chocolate;
    16. else if (id == 2) return Snack.Soda;
    17. else return Snack.Gum;
    18. }
    19. }

    SnackDto类很简单,只包含id和name,SlotDto则复杂一些:

    1. package com.lugew.springbootddd;
    2. import lombok.Getter;
    3. import lombok.Setter;
    4. import javax.persistence.Entity;
    5. import javax.persistence.*;
    6. @Entity
    7. @Getter
    8. @Setter
    9. public class SlotDto {
    10. @Id
    11. @GeneratedValue
    12. private long id;
    13. private int quantity;
    14. private float price;
    15. @OneToOne(cascade = CascadeType.ALL)
    16. private SnackDto snackDto;
    17. private int position;
    18. public Slot convertToSlot() {
    19. Slot slot = new Slot();
    20. slot.setId(id);
    21. slot.setPosition(position);
    22. slot.setSnackPile(new SnackPile(snackDto.convertToSnack(), quantity, price));
    23. return slot;
    24. }
    25. }
    1. package com.lugew.springbootddd;
    2. import com.lugew.springbootddd.snackmachine.Money;
    3. import com.lugew.springbootddd.snackmachine.SnackMachine;
    4. import lombok.Getter;
    5. import lombok.Setter;
    6. import javax.persistence.Entity;
    7. import javax.persistence.*;
    8. import java.util.ArrayList;
    9. import java.util.List;
    10. /**
    11. * @author 夏露桂
    12. * @since 2021/6/10 12:00
    13. */
    14. @Getter
    15. @Setter
    16. @Entity
    17. public class SnackMachineDto {
    18. @Id
    19. @GeneratedValue
    20. private long id;
    21. private int oneCentCount;
    22. private int tenCentCount;
    23. private int quarterCount;
    24. private int oneDollarCount;
    25. private int fiveDollarCount;
    26. private int twentyDollarCount;
    27. private float moneyInTransaction;
    28. @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    29. @JoinColumn(name = "snackMachineId")
    30. private List<SlotDto> slotDtoList;
    31. public SnackMachine convertToSnackMachine() {
    32. SnackMachine snackMachine = new SnackMachine();
    33. snackMachine.setId(id);
    34. snackMachine.setMoneyInTransaction(moneyInTransaction);
    35. snackMachine.setMoneyInside(new
    36. Money(oneCentCount, tenCentCount, quarterCount,
    37. oneDollarCount, fiveDollarCount, twentyDollarCount));
    38. List<Slot> slotList = new ArrayList<>();
    39. for (SlotDto slotDto : slotDtoList) {
    40. slotList.add(slotDto.convertToSlot());
    41. }
    42. snackMachine.setSlots(slotList);
    43. return snackMachine;
    44. }
    45. }

    重启系统后,Springboot会自动创建数据库表。
    image.png