Ling2编码规范

来自ling
跳转至: 导航搜索

Hibernate注解详解(超全面不解释)

flag和status

数据实体通过flag来标示是否逻辑删除,flag=1标示没删除=0标示已经已经删除
@Column(name = "flag",  length = 10)
@ModelProperty(comment="是否有效")
String flag;
数据实体通过status来标示数据工作流状态
@Column(name = "status",  length = 10)
@ModelProperty(comment="状态")
String status;
数据实体通过enable来标示数据是否启用
@Column(name = "enable",  length = 10)
@ModelProperty(comment="是否启用")
String enable;
@Version
@Column(name="RECORD_VERSION")
@ModelProperty(comment="记录版本号,每次修改记录时加1")
Integer versionId;
将类注解为@IdClass,并将该实体中所有主键的属性都注解为 @Id

一对多关系的使用

外键不建立索引 @ForeignKey(name = "null") @ForeignKey(name = "k_user_friend_FK",inverseName = "k_user_friend_FK_R")

foreignKey = @javax.persistence.ForeignKey(name="none",value = ConstraintMode.NO_CONSTRAINT)
@ModelProperty(comment="准备单头")
@Column(name="CRVAT_INVOICE_PRE_H_ID")
String tmsCrvatInvoicePreHId;
@ModelProperty(comment="准备单头")
@ManyToOne
@Cascade(CascadeType.REFRESH)
@JoinColumn(name="CRVAT_INVOICE_PRE_H_ID",insertable=false,updatable=false,nullable=true,foreignKey = @javax.persistence.ForeignKey(name="none",value = ConstraintMode.NO_CONSTRAINT))
TmsCrvatInvoicePreH tmsCrvatInvoicePreH;
@ModelProperty(comment="准备单行")
@OneToMany(cascade={CascadeType.REFRESH}, fetch=FetchType.LAZY, mappedBy="tmsCrvatInvoicePreH")
private List<TmsCrvatInvoicePreL> tmsCrvatInvoicePreLs = new ArrayList<TmsCrvatInvoicePreL>(0);
@ManyToOne(cascade=CascadeType.ALL,targetEntity=ComponentDefinition.class,fetch=FetchType.EAGER)
@Fetch(FetchMode.JOIN)
@JoinColumn(name="URL_COMPONENT_ID")
private ComponentDefinition component;


OneToMany
//需要连级更新
@OneToMany(mappedBy="factorSet",orphanRemoval=true)
@org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
@OrderBy("sortOrder")

//不需要连级更新
@OneToMany(mappedBy = "purchase")
@Cascade(CascadeType.REFRESH)
@OrderBy(clause="specificationId desc")
Collection<PurchaseLog> purchaseLogs = new ArrayList<PurchaseLog>();
//通过字段
@OneToMany(orphanRemoval=true)
@JoinColumn(name="HANDLER_ID")
@Cascade(CascadeType.SAVE_UPDATE)
@OrderBy("SORT_ORDER")
ManyToOne
@ModelProperty(comment="组织")
@Column(name="organizationRoleId")
Long organizationRoleId;
@ModelProperty(comment="组织角色(标识)")
@ManyToOne
@Cascade(CascadeType.REFRESH)
@JoinColumn(name="organizationRoleId",insertable=false,updatable=false,nullable=true)
private OrganizationRole organizationRole;

@Where(clause="DEL_FLAG=1")

ManyToMany
OneToOne
@OneToOne
@Cascade(CascadeType.REFRESH)
@JoinColumn(name="brand_id",insertable=false,updatable=false)
@ModelProperty(comment = "商品品牌")
Brand brand;


InParam
Dorado7

hibernate的多关系命名规范为XXXs inparam中多关系命名规范为relXXXs dataType中定义同样的Reference,命名规范为relXXXs,并定义数据加载逻辑. 参考代码如下:

      <Reference name="relPositions">
        <Property name="parameter">$${this.id}</Property>
        <Property name="dataProvider">ling2.deptMaintain#loadPositions</Property>
        <Property name="dataType">[dataTypePosition]</Property>
      </Reference>

数据字典

@Column(name="STATE_",length=12)
@Enumerated(EnumType.STRING)
private JobState state;
  • 大小类维护中创建一个节点,输入名称和代码,将字典数据录入到节点的子节点中.
  • 如果名称需要使用国际化,请在名称值中输入标准的国际化表达式,如${res["core.Security/name"]}
  • 设置datatype的mapping,格式为:

${dorado.getDataProvider("dictionaryView#getdDictionaryEntitiesByCode").getResult("supplyPlace")} ${dorado.getDataProvider("dictionaryView#getdDictionaryEntitiesByCodeWithNull").getResult("supplyPlace")}

model定义

继承关系

  • biz中定义model
  • api中定义VO,VO分entityVO和UIVO 更多阅读VO定义
  • biz中通过Configuration或Application中设置@ComponentScan属性实现model和service等扫描规则

  • core中
@MappedSuperclass
@ModelProperty(comment = "测试Builder")
public class BaseDemo extends BaseEntity {

    public static final String TABLE = "T_DEMO";
    public static final String SEQ = TABLE;

    @Id
    @ModelProperty(comment = "ID")
    @GenericGenerator(name = SEQ + "_GENERATOR", strategy = Ling2UUIDGenerator.STRATEGY_NAME, parameters = {@Parameter(name = "pkColumnValue", value = SEQ)})
    @GeneratedValue(strategy = GenerationType.TABLE, generator = SEQ + "_GENERATOR")
    @Column(name = "SOURCE_ACCOUNT_ID", unique = true, nullable = false, length = 36)
    String id;
}
  • service中,hibernate映射
@Entity
@Table(name = BaseDemo.TABLE)
public class Demo extends BaseDemo {

}

hibernate映射规范

  • 定义表
@Data
@Entity
@Table(name=UserDept.TABLE)
@DynamicInsert(true)
@DynamicUpdate(true)
@ModelProperty(comment = "到用户级别的定义值")
  • 定义表名和seq
public static final String TABLE = TablePreDef.BASEPRE+"USER_DEPT";
public static final String SEQ = TABLE;
  • 定义ID生产规则
  1. Ling2UUIDGenerator uuid生成方式
  2. Ling2IdGenerator 默认方式
@Id
@GenericGenerator(name=SEQ+"_GENERATOR",strategy=Ling2IdGenerator.STRATEGY_NAME,parameters={@Parameter(name="pkColumnValue",value=SEQ)})
@GeneratedValue(strategy = GenerationType.TABLE, generator = SEQ+"_GENERATOR")
@Column(name="ID",length=60)
private String id;
@Id
@GenericGenerator(name=SEQ+"_GENERATOR",strategy= Ling2UUIDGenerator.STRATEGY_NAME)
@GeneratedValue(strategy = GenerationType.TABLE, generator = SEQ+"_GENERATOR")
@Column(name="ID",length=60)
private String id;
  • 定义字段
@ModelProperty(comment = "代码")
@Column(name = "code", length = 150)
private String code;
  • 继承
    • T@MappedSuperclass
    • Table per Class Strategy: the <union-class> element inHibernate 每个类一张表
@Inheritance(strategy= InheritanceType.TABLE_PER_CLASS)

有缺点,如多态查询或关联。Hibernate使用 SQL Union 查询来实现这种策略。这种策略支持双向的一对多关联,但不支持IDENTIFY 生成器策略,因为ID必须在多个表间共享。一旦使用就不能使用AUTO和IDENTIFY生成器。

    • TSingle Table per Class Hierarchy Strategy: the<subclass> element in Hibernate 每个类层次结构一张表
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
    name="planetype",
    discriminatorType=DiscriminatorType.STRING
)
@DiscriminatorValue("Plane")

@Entity @Inheritance(strategy=InheritanceType.JOINED) public class Boatimplements Serializable { ... }


@Entity public class Ferryextends Boat { ... }

@Entity @PrimaryKeyJoinColumn(name="BOAT_ID") public classAmericaCupClass extends Boat { ... }


    • Joined Subclass Strategy: the <joined-subclass>element in Hibernate 连接的子类策略
@Entity
@Inheritance(strategy=InheritanceType.JOINED)
*对象类型字段
 @Embedded
只使用@Embedded和只使用@Embeddable产生的效果是相同的

@AttributeOverrides:里面只包含了@AttributeOverride类型数组;

@AttributeOverride:包含要覆盖的@Embeddable类中字段名name和新增的@Column字段的属性;
    @Embedded
    @AttributeOverrides({@AttributeOverride(name="country", column=@Column(name = "person_country", length = 25, nullable = false)),
                        @AttributeOverride(name="city", column = @Column(name = "person_city", length = 15))})
    private Address address;
  • @Transient

表示该属性并非一个到数据库表的字段的映射,ORM框架将忽略该属性.如果一个属性并非数据库表的字段映射,就务必将其标示为@Transient,否则ORM框架默认其注解为@Basic

  • @Index(name = "IDX_OPERATE")
  • @Enumerated(EnumType.STRING)
  • @JsonIgnore @JsonIgnoreProperties

序列化时忽略

@OneToMany(fetch = FetchType.LAZY, mappedBy = "xuser")
public Set<User> getUsers() {
   return this.users;
}
  • @JsonFormat

此注解用于属性或者方法上(最好是属性上),可以方便的把Date类型直接转化为我们想要的模式,比如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")

  • @JsonSerialize

此注解用于属性或者getter方法上,用于在序列化时嵌入我们自定义的代码,比如序列化一个double时在其后面限制两位小数点。

  • @JsonDeserialize

此注解用于属性或者setter方法上,用于在反序列化时可以嵌入我们自定义的代码,类似于上面的@JsonSerialize

更多参见Hibernate JPA中@Transient、@JsonIgnoreProperties、@JsonIgnore、@JsonFormat、@JsonSerialize等注解解释

@DynamicInsert(true)
@DynamicUpdate(true)

DynamicInsert01.png --> DynamicInsert02.png

mongodb

import org.springframework.data.mongodb.core.mapping.Document;

import javax.persistence.*;

/**
 * Created by builder
 */
@Document(collection=ProgrammeEntity.TABLE)
public class ProgrammeEntity extends Programme {
    public static final String TABLE = "T_PROGRAMME";
    public static final String SEQ = TABLE;

    @Id
    @ModelProperty(comment = "_id")
    String id;

    @Override
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

List<String>类型

更多参见Hibernate实体中List String 字段的处理

    String architectures;

    public String getArchitectures() {
        return architectures;
    }

    public void setArchitectures(String architectures) {
        this.architectures = architectures;
    }

    public List<String> getArchitectureList() {
        return StringUtils.split(architectures, ",");
    }

    public void setArchitectures(List<String> architectures) {
        this.architectures = StringUtils.join(architectures);
    }

系统属性功能

  • 系统属性功能中包含了属性模版的配置功能,通过该功能用户可以为每一个属性定义描述信息、数据类型、编辑方式,并且可以对所有属性进行分组、排序。最终Marmot Framework可以根据这些信息自动的生成供给用户使用的属性维护界面。
  • 属性值包含"系统级值"和"用户级值",在使用属性时"用户级值"的优先级将高于"系统级值"。在属性模版中可以为每一个属性定义是否允许拥有"用户级值"。此外,为了提高系统读取属性的效率,ling2还为属性值提供了缓存功能。