Domanda

Hai una classe base comune per le entità di ibernazione, ovvero una MappedSuperclass con ID, versione e altre proprietà comuni? Ci sono degli svantaggi?

Esempio:

@MappedSuperclass()
public class BaseEntity {

    private Long id;
    private Long version;
    ...

    @Id @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {return id;}

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

    @Version
    public Long getVersion() {return version;}
    ...

    // Common properties
    @Temporal(TemporalType.TIMESTAMP)
    public Date creationDate() {return creationDate;}
    ...
}

@Entity
public class Customer extends BaseEntity {
    private String customerName;
    ...
}
È stato utile?

Soluzione

Questo funziona bene per noi. Oltre all'ID e alla data di creazione, abbiamo anche una data modificata. Abbiamo anche un TaggedBaseEntity intermedio che implementa un'interfaccia Taggable , perché alcune entità della nostra applicazione web hanno tag, come domande su Stack Overflow.

Altri suggerimenti

Quello che uso è principalmente per implementare hashCode () e equals (). Ho anche aggiunto un metodo per stampare piuttosto l'entità. In risposta a DR sopra, la maggior parte di questo può essere sovrascritta, ma nella mia implementazione sei bloccato con un ID di tipo Long.

public abstract class BaseEntity implements Serializable {

    public abstract Long getId();
    public abstract void setId(Long id);

    /**
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
        return result;
    }

    /**
     * @see java.lang.Object#equals(Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        BaseEntity other = (BaseEntity) obj;
        if (getId() == null) {
            if (other.getId() != null)
                return false;
        } else if (!getId().equals(other.getId()))
            return false;
        return true;
    }

    /**
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return new StringBuilder(getClass().getSimpleName()).append(":").append(getId()).toString();
    }

    /**
     * Prints complete information by calling all public getters on the entity.
     */
    public String print() {

        final String EQUALS = "=";
        final String DELIMITER = ", ";
        final String ENTITY_FORMAT = "(id={0})";

        StringBuffer sb = new StringBuffer("{");

        PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(this);
        PropertyDescriptor property = null;
        int i = 0;
        while ( i < properties.length) {

            property = properties[i];
            sb.append(property.getName());
            sb.append(EQUALS);

            try {
                Object value = PropertyUtils.getProperty(this, property.getName());
                if (value instanceof BaseEntity) {
                    BaseEntity entityValue = (BaseEntity) value;
                    String objectValueString = MessageFormat.format(ENTITY_FORMAT, entityValue.getId());
                    sb.append(objectValueString);
                } else {
                    sb.append(value);
                }
            } catch (IllegalAccessException e) {
                // do nothing
            } catch (InvocationTargetException e) {
                // do nothing
            } catch (NoSuchMethodException e) {
                // do nothing
            }

            i++;
            if (i < properties.length) {
                sb.append(DELIMITER);
            }
        }

        sb.append("}");

        return sb.toString();
    }
}

Non esiterei a usare una classe base comune, dopo tutto questo è il punto della mappatura O / R.

Uso anche le classi di base comuni, ma solo se le entità condividono almeno alcune proprietà comuni. Non lo userò, se l'ID è l'unica proprietà comune. Fino ad ora non ho riscontrato alcun problema.

Funziona bene anche per me.

Nota che in questa entità puoi anche aggiungere alcuni ascoltatori / intercettori di eventi come Hibernate Envers o uno personalizzato in base alle tue necessità in modo da poter: - Tieni traccia di tutte le modifiche - Conoscere quale utente ha apportato l'ultima modifica - Aggiorna automaticamente l'ultima modifica - Imposta automaticamente la prima data di inserimento E cose del genere ...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top