实体和数据库表的映射方式有两种:
- 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
@Entity
public class SnackMachineDto {
@Id
@GeneratedValue
private 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: 23333
spring:
h2:
console:
enabled: true
datasource:
url: jdbc:h2:mem:testdb
driverClassName: org.h2.Driver
username: sa
password:
jpa:
database-platform: org.hibernate.dialect.H2Dialect
logging:
level:
org:
hibernate:
SQL: debug
type:
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: 23333
spring:
h2:
console:
enabled: true
datasource:
data: classpath:sql/init.sql
url: jdbc:h2:mem:testdb;MODE=MYSQL
driverClassName: org.h2.Driver
username: sa
password:
jpa:
database-platform: org.hibernate.dialect.H2Dialect
logging:
level:
org:
hibernate:
SQL: debug
type:
descriptor:
sql: trace