Spring Data JPA自定义Id生成策略、复合主键配置、Auditing使用
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
@Entity
@Table(name = "customers")
@EntityListeners(AuditingEntityListener.class)
public class Customer implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@CreatedBy
@Column(name = "created_by")
private String createdBy;
@CreatedDate
@Column(name = "created_date")
private Date createdDate;
@LastModifiedBy
@Column(name = "last_modified_by")
private String lastModifiedBy;
@LastModifiedDate
@Column(name = "last_modified_date")
private Date lastModifiedDate;
// 省略getter和setter方法
}
@Embeddable
public class CompoundKey implements Serializable {
private String keyPart1;
private String keyPart2;
// 省略getter和setter方法
}
@Entity
@Table(name = "compound_key_entities")
public class CompoundKeyEntity {
@EmbeddedId
private CompoundKey id;
@Column(name = "data")
private String data;
// 省略getter和setter方法
}
这个代码示例展示了如何在Spring Data JPA中使用自定义的ID生成策略、复合主键配置以及Auditing的使用。在Customer
实体中,我们使用了@GeneratedValue
注解来指定ID的生成策略,并且通过@EntityListeners(AuditingEntityListener.class)
开启了Auditing功能。CompoundKey
是一个复合主键类,使用@Embeddable
注解标记,而CompoundKeyEntity
则通过@EmbeddedId
注解来使用这个复合主键。
评论已关闭