一、示例说明
rules\CouponTypeConverter.java
@Converter
public class CouponTypeConverterimplements AttributeConverter<CouponType, String> {@Overridepublic String convertToDatabaseColumn(CouponType couponCategory) {return couponCategory.getCode();}@Overridepublic CouponType convertToEntityAttribute(String code) {return CouponType.convert(code);}
}
entity/CouponTemplate.java
@Entity
@Builder
@EntityListeners(AuditingEntityListener.class)
@Table(name = "coupon_template")
public class CouponTemplate implements Serializable {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name = "id", nullable = false)private Long id;// 状态是否可用@Column(name = "available", nullable = false)private Boolean available;@Column(name = "name", nullable = false)private String name;@Column(name = "description", nullable = false)private String description;// 适用门店-如果为空,则为全店满减券@Column(name = "shop_id")private Long shopId;// 优惠券类型@Column(name = "type", nullable = false)@Convert(converter = CouponTypeConverter.class)private CouponType category;// 创建时间,通过@CreateDate注解自动填值(需要配合@JpaAuditing注解在启动类上生效)@CreatedDate@Column(name = "created_time", nullable = false)private Date createdTime;// 优惠券核算规则,平铺成JSON字段@Column(name = "rule", nullable = false)@Convert(converter = RuleConverter.class)private TemplateRule rule;}
Spring JPA 包的标准注解,对数据库字段进行了映射,我挑几个关键注解说道一下。
1、Entity:声明了“数据库实体”对象,它是数据库 Table 在程序中的映射对象;
2、Table:指定了 CouponTemplate 对应的数据库表的名称;
3、ID/GeneratedValue:ID 注解将某个字段定义为唯一主键,GeneratedValue 注解指定了主键生成策略;
4、Column:指定了每个类属性和数据库字段的对应关系,该注解还支持非空检测、对 update 和 create 语句进行限制等功能;
5、CreatedDate:自动填充当前数据的创建时间;
6、Convert:如果数据库中存放的是 code、string、数字等等标记化对象,可以使用 Convert 注解指定一个继承自 AttributeConverter 的类,将 DB 里存的内容转化成一个 Java 对象。