JPA及部分Hibernate注解学习

(1)JPA & Hibernate的[字段相关注解]添加在[实体类字段的get方法]上

(2)dodo的[字段相关的注解]添加在[实体类的字段]上

  1. 学习这几个JPA & Hibernate注解,足够了

@DynamicInsert

  1. org.hibernate.annotations.DynamicInsert

注解在实体类上,默认为true,设置为true,表示insert对象的时候,生成动态的insert语句,如果这个字段的值是null就不会加入到insert语句当中。

@OneToOne

  1. javax.persistence.OneToOne
  1. // 例子,一个城市唯一归属一个省份
  2. // 那么城市和省份是一对一(OneToOne)的关系
  3. @DynamicInsert
  4. public class City extends BaseEntity{
  5. private Province province;
  6. @OneToOne(fetch = FetchType.LAZY)
  7. public Province getProvince() {
  8. return province;
  9. }
  10. }

@OneToMany & @ManyToOne

  1. javax.persistence.OneToMany
  2. javax.persistence.ManyToOne
  1. // 例子,一个实体类(Entity)包含多个字段(Field)
  2. // 实体类和字段是一对多(OneToMany)的关系
  3. // 字段和实体类时多对一(ManyToOne)的关系
  4. @DynamicInsert
  5. public class Entity extends BaseEntity{
  6. private Set<Field> allFields;
  7. @OneToMany(cascade = { CascadeType.ALL }, mappedBy = "entity")
  8. @Fetch(FetchMode.SUBSELECT)
  9. @OrderBy("sortSeq asc")
  10. public Set<Field> getAllFields() {
  11. return allFields;
  12. }
  13. }
  14. @DynamicInsert
  15. public class Field extends BaseEntity{
  16. private Entity entity;
  17. @ManyToOne
  18. public Entity getEntity() {
  19. return entity;
  20. }
  21. }

@ManyToMany

  1. javax.persistence.ManyToMany
  1. // 例子,一个角色(Role)包含多个权限(Right)
  2. // 一个权限(Right)也可以被多个角色(Role)引用
  3. // 角色和权限是(ManyToMany)的关系
  4. @DynamicInsert
  5. public class Role extends BaseEntity {
  6. private Set<Right> allRights;
  7. @ManyToMany(fetch = FetchType.LAZY)
  8. @OrderBy("sortSeq asc")
  9. public Set<Right> getAllRights() {
  10. return allRights;
  11. }
  12. }
  13. @DynamicInsert
  14. public class Right extends BaseEntity{
  15. private Set<Role> roles;
  16. // 指定由角色表来维护关系,则roles无须加@DodoField注解
  17. @ManyToMany(mappedBy = "allRights", fetch = FetchType.LAZY)
  18. public Set<Role> getRoles() {
  19. return roles;
  20. }
  21. }

@Column

  1. 一般用来配置,字段的非空、长度、索引、精度以及范围
  1. // 设置字段长度128
  2. @Column(length = 128)
  3. public String getRightRemark() {
  4. return rightRemark;
  5. }
  6. // 设置字段长度8,非空,唯一性索引
  7. @Column(nullable = false, length = 8, unique = true)
  8. public String getRightCode() {
  9. return this.rightCode;
  10. }
  11. // 设置金额精度为15,保留小数点后2位
  12. @Column(precision = 15, scale = 2)
  13. public BigDecimal getAmount() {
  14. return amount;
  15. }

@Convert

  1. javax.persistence.Convert

dodo中特指将@Convert用于枚举类型字段

  1. /**
  2. * 实体类中使用
  3. **/
  4. public class BaseTypeDemo extends BaseEntity {
  5. @DodoField(sortSeq = 13, name = "枚举类型字段")
  6. private DemoEnum enumField;
  7. //......
  8. // 指定属性值转换器
  9. @Convert(converter = DemoEnum.Converter.class)
  10. public DemoEnum getEnumField() {
  11. return enumField;
  12. }
  13. //......