JPA常用注解汇总纪要

注解Column详解

Column的主要属性信息:

  • name 自定义数据库的字段名称
  • nullable 是否为空
  • length: 如果是字符型,可以限定长度
  • unqiue 是否为唯一性
  • precision/scale 对于小数的精度控制
  • insertable/updatable 可插入/可更新设置

@Column用来建立模型对象与数据库表字段之间的映射关系,可以使用在方法和属性上。

在不做声明的情况下,默认会建立与数据库的映射。

详细的信息可以参阅其源代码的说明:

/**
 * Specifies the mapped column for a persistent property or field.
 * If no <code>Column</code> annotation is specified, the default values apply.
 *
 * <blockquote><pre>
 *    Example 1:
 *
 *    &#064;Column(name="DESC", nullable=false, length=512)
 *    public String getDescription() { return description; }
 *
 *    Example 2:
 *
 *    &#064;Column(name="DESC",
 *            columnDefinition="CLOB NOT NULL",
 *            table="EMP_DETAIL")
 *    &#064;Lob
 *    public String getDescription() { return description; }
 *
 *    Example 3:
 *
 *    &#064;Column(name="ORDER_COST", updatable=false, precision=12, scale=2)
 *    public BigDecimal getCost() { return cost; }
 *
 * </pre></blockquote>
 *
 *
 * @since Java Persistence 1.0
 */ 
@Target({METHOD, FIELD}) 
@Retention(RUNTIME)
public @interface Column {

    /**
     * (Optional) The name of the column. Defaults to 
     * the property or field name.
     */
    String name() default "";

    /**
     * (Optional) Whether the column is a unique key.  This is a 
     * shortcut for the <code>UniqueConstraint</code> annotation at the table 
     * level and is useful for when the unique key constraint 
     * corresponds to only a single column. This constraint applies 
     * in addition to any constraint entailed by primary key mapping and 
     * to constraints specified at the table level.
     */
    boolean unique() default false;

    /**
     * (Optional) Whether the database column is nullable.
     */
    boolean nullable() default true;

    /**
     * (Optional) Whether the column is included in SQL INSERT 
     * statements generated by the persistence provider.
     */
    boolean insertable() default true;

    /**
     * (Optional) Whether the column is included in SQL UPDATE 
     * statements generated by the persistence provider.
     */
    boolean updatable() default true;

    /**
     * (Optional) The SQL fragment that is used when 
     * generating the DDL for the column.
     * <p> Defaults to the generated SQL to create a
     * column of the inferred type.
     */
    String columnDefinition() default "";

    /**
     * (Optional) The name of the table that contains the column. 
     * If absent the column is assumed to be in the primary table.
     */
    String table() default "";

    /**
     * (Optional) The column length. (Applies only if a
     * string-valued column is used.)
     */
    int length() default 255;

    /**
     * (Optional) The precision for a decimal (exact numeric) 
     * column. (Applies only if a decimal column is used.)
     * Value must be set by developer if used when generating 
     * the DDL for the column.
     */
    int precision() default 0;

    /**
     * (Optional) The scale for a decimal (exact numeric) column. 
     * (Applies only if a decimal column is used.)
     */
    int scale() default 0;
}

日期类型定义

Date: @Temperal(TemperalType.TIMESTAMP/DATE/TIME)
示例如下:

   @Column(name = "created_time")
   @Temporal(TemporalType.TIMESTAMP)
   private Date createdTime;

枚举类型

定义枚举类, 其有两个值:Male/Female

  public enum Gender {
         Female, Male
  }

领域对象的列定义:

   @Column(name="t_gender", nullable=false)
   @Enumerated(EnumType.ORDINAL)
   private Gender gender;

上述列定义中EnumType支持String/Ordinal类型, String是枚举的字符描述值,Ordinal是其位置信息,例如Female其位置为0, Male的位置为1,其存入数据库的值即为0/1.

如果需要自定义枚举的值,例如Female之时,存入10, Male之时,存入20.该如何来处理呢?

首先重新定义枚举类:

@Getter
public enum Gender {
	Male("Male", 20), Female("Female", 10);

	private String name;
	private Integer index;
	
	private Gender(String name, Integer index) {
        this.name = name;
        this.index = index;
	}
	
	public static Gender fromInteger(Integer indexNum) {
	    Objects.requireNonNull(indexNum);
	    if (indexNum.intValue() == Female.index.intValue()) {
	    	return Female;
	    }
	    else 
	    	return Male;
	}
}

在枚举类中,定义了构造方法和一个静态方法,基于index值获取对应的枚举对象。
自定义Gender类的Coverter转换器:

@Converter
public class GenderConverter implements AttributeConverter<Gender, Integer> {
    @Override
    public Integer convertToDatabaseColumn(Gender attribute) {
        return attribute.getIndex();
    }
 
    @Override
    public Gender convertToEntityAttribute(Integer dbData) {
        return Gender.fromInteger(dbData);
    }
}

注意这里的范型使用<Gender, Integer>,第一个是枚举类,第二个是Index类型。
这个Converter将用来转化Gender的枚举类型。

声明使用Converter来自动转化Gender的Domain对象值,示例如下:

    @Column(nullable=false, name="gender")
    @Convert(converter = GenderConverter.class)
    private Gender gender = Gender.Male;

这里Gender类型的属性设置了缺省值Male,通过@Convert注解来声明使用GenderConverter转化类。

存储空间大的数据类型

@Lob: 用来声明字段需要大的存储空间。
如果声明了String类型, 则在数据库中默认映射为LongText。
对于二进制数据,domain对象使用byte/Byte[], 则数据库中类型映射为LongBlob。

由于此字段比较大,如果直接加载,则会消耗很大内存。如果设置为延迟加载,则会更为人性化,可以通过@Basic(fetch=LAZY/EAGER)设置为延迟加载:
使用示例如下:

  @Lob
  @Basic(fetch=LAZY)
  private Byte[] file;

排除持久化字段声明

@Transient 字段名称
默认使用字段映射, 通过@Transient设置,不用数据库字段的映射。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: JPA是Java Persistence API的简称,是SUN公司引入的ORM规范,用于简化Java应用程序的持久化开发。JPA提供了一系列的注解,用于定义实体类与数据库表之间的映射关系。常用的JPA实体注解包括: 1. @Entity: 将Java类标记为JPA实体类,表示该类与数据库表进行映射。 2. @Table: 指定实体类对应的数据库表的名称。 3. @Id: 标记实体类的主键字段。 4. @GeneratedValue: 指定主键的生成策略,如自增长、UUID等。 5. @Column: 指定实体类属性与数据库表字段的映射关系。 6. @OneToOne: 定义一对一关系,用于关联两个实体类。 7. @OneToMany: 定义一对多关系,用于关联一个实体类与多个实体类。 8. @ManyToOne: 定义多对一关系,用于关联多个实体类与一个实体类。 9. @ManyToMany: 定义多对多关系,用于关联多个实体类与多个实体类。 以上是JPA常用的实体注解,通过使用这些注解,可以方便地定义实体类与数据库表之间的映射关系,简化开发过程。\[1\]\[3\] #### 引用[.reference_title] - *1* *3* [JPA 常用实体注解使用总结](https://blog.csdn.net/swebin/article/details/96458821)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [spring boot jpa学习:1.Model类的注释annatation](https://blog.csdn.net/sandalphon4869/article/details/105519101)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值