实体和数据库表的映射方式有两种:
- XML文件
- 注解
XML文件相对来讲比较笨重,不易重构,我们选择注解形式。实体上的直接注解违反了单一职责的原则,所以我们引入DTO。
package com.lugew.springbootddd;import lombok.Getter;import lombok.Setter;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;/*** @author 夏露桂* @since 2021/6/10 12:00*/@Getter@Setter@Entitypublic class SnackMachineDto {@Id@GeneratedValueprivate long id;private int oneCentCount;private int tenCentCount;private int quarterCount;private int oneDollarCount;private int fiveDollarCount;private int twentyDollarCount;private float moneyInTransaction;}
同时配置文件设置:
server:port: 23333spring:h2:console:enabled: truedatasource:url: jdbc:h2:mem:testdbdriverClassName: org.h2.Driverusername: sapassword:jpa:database-platform: org.hibernate.dialect.H2Dialectlogging:level:org:hibernate:SQL: debugtype:descriptor:sql: trace
启动项目,访问http://localhost:23333/h2-console

最后,我们执行SQL,插入数据:
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);



为了避免每次重启都要执行sql,我们为Spring boot配置自动执行:
server:port: 23333spring:h2:console:enabled: truedatasource:data: classpath:sql/init.sqlurl: jdbc:h2:mem:testdb;MODE=MYSQLdriverClassName: org.h2.Driverusername: sapassword:jpa:database-platform: org.hibernate.dialect.H2Dialectlogging:level:org:hibernate:SQL: debugtype:descriptor:sql: trace

