3

我必须按照代码检查我的实体在字段上是否modelnullable=false或类似的注释。

import javax.persistence.Column;
import .....

private boolean isRequired(Item item, Object propertyId) {
        Class<?> property = getPropertyClass(item, propertyId);

        final JoinColumn joinAnnotation = property.getAnnotation(JoinColumn.class);
        if (null != joinAnnotation) {
            return !joinAnnotation.nullable();
        }

        final Column columnAnnotation = property.getAnnotation(Column.class);
        if (null != columnAnnotation) {
            return !columnAnnotation.nullable();
        }

        ....
        return false;
    }

这是我的模型的一个片段。

import javax.persistence.*;
import .....

@Entity
@Table(name="m_contact_details")
public class MContactDetail extends AbstractMasterEntity implements Serializable {

    @Column(length=60, nullable=false)
    private String address1;

对于那些不熟悉@Column注释的人,这里是标题:

@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface Column {

我希望它会时不时isRequired地返回true,但它永远不会。我已经在我的项目上做了一个mvn cleanmvn install,但这没有帮助。

Q1:我做错了什么?

Q2:有没有更简洁的编码方式isRequired(也许更好地利用泛型)?

4

2 回答 2

4
  1. property代表一个类(它是 a Class<?>
  2. @Column并且@JoinColumn只能注释字段/方法。

因此,您永远不会在property.

稍微修改过的代码版本,打印出是否需​​要 Employee 实体的 email 属性:

public static void main(String[] args) throws NoSuchFieldException {
      System.out.println(isRequired(Employee.class, "email"));
}

private static boolean isRequired(Class<?> entity, String propertyName) throws NoSuchFieldException {
    Field property = entity.getDeclaredField(propertyName);

    final JoinColumn joinAnnotation = property.getAnnotation(JoinColumn.class);
    if (null != joinAnnotation) {
        return !joinAnnotation.nullable();
    }

    final Column columnAnnotation = property.getAnnotation(Column.class);
    if (null != columnAnnotation) {
        return !columnAnnotation.nullable();
    }

    return false;
}

请注意,这是一个半生不熟的解决方案,因为 JPA 注释可以位于字段或方法上。还要注意反射方法(如getFiled()/ )之间的区别getDeclaredField()。前者也返回继承的字段,而后者只返回特定类的字段,而忽略从其父类继承的内容。

于 2013-02-19T18:57:37.987 回答
0

以下代码有效:

    @SuppressWarnings("rawtypes")
    private boolean isRequired(BeanItem item, Object propertyId) throws SecurityException {

        String fieldname = propertyId.toString();

        try {
            java.lang.reflect.Field field = item.getBean().getClass().getDeclaredField(fieldname);
            final JoinColumn joinAnnotation = field.getAnnotation(JoinColumn.class);
            if (null != joinAnnotation) {
                return !joinAnnotation.nullable();
            }

            final Column columnAnnotation = field.getAnnotation(Column.class);
            if (null != columnAnnotation) {
                return !columnAnnotation.nullable();
            }



        } catch (NoSuchFieldException e) {
            //not a problem no need to log this event.
            return false;
        } 
    }
于 2013-02-19T19:56:18.790 回答