实体和数据库表的映射方式有两种:

    1. XML文件
    2. 注解

    XML文件相对来讲比较笨重,不易重构,我们选择注解形式。实体上的直接注解违反了单一职责的原则,所以我们引入DTO。

    1. package com.lugew.springbootddd;
    2. import lombok.Getter;
    3. import lombok.Setter;
    4. import javax.persistence.Entity;
    5. import javax.persistence.GeneratedValue;
    6. import javax.persistence.Id;
    7. /**
    8. * @author 夏露桂
    9. * @since 2021/6/10 12:00
    10. */
    11. @Getter
    12. @Setter
    13. @Entity
    14. public class SnackMachineDto {
    15. @Id
    16. @GeneratedValue
    17. private long id;
    18. private int oneCentCount;
    19. private int tenCentCount;
    20. private int quarterCount;
    21. private int oneDollarCount;
    22. private int fiveDollarCount;
    23. private int twentyDollarCount;
    24. private float moneyInTransaction;
    25. }

    同时配置文件设置:

    1. server:
    2. port: 23333
    3. spring:
    4. h2:
    5. console:
    6. enabled: true
    7. datasource:
    8. url: jdbc:h2:mem:testdb
    9. driverClassName: org.h2.Driver
    10. username: sa
    11. password:
    12. jpa:
    13. database-platform: org.hibernate.dialect.H2Dialect
    14. logging:
    15. level:
    16. org:
    17. hibernate:
    18. SQL: debug
    19. type:
    20. descriptor:
    21. sql: trace

    启动项目,访问http://localhost:23333/h2-console
    image.pngimage.png
    最后,我们执行SQL,插入数据:

    1. insert into snack_machine_dto (five_dollar_count, money_in_transaction,one_cent_count, one_dollar_count,quarter_count, ten_cent_count, twenty_dollar_count, id) values (1, 0.0, 1, 1, 1, 1, 1, 1);

    image.pngimage.png
    image.png
    为了避免每次重启都要执行sql,我们为Spring boot配置自动执行:

    1. server:
    2. port: 23333
    3. spring:
    4. h2:
    5. console:
    6. enabled: true
    7. datasource:
    8. data: classpath:sql/init.sql
    9. url: jdbc:h2:mem:testdb;MODE=MYSQL
    10. driverClassName: org.h2.Driver
    11. username: sa
    12. password:
    13. jpa:
    14. database-platform: org.hibernate.dialect.H2Dialect
    15. logging:
    16. level:
    17. org:
    18. hibernate:
    19. SQL: debug
    20. type:
    21. descriptor:
    22. sql: trace

    image.png