下面列出了javax.persistence.MapKeyColumn#org.hibernate.mapping.Property 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 将数据字典解析成Hibernate的字段,不支持级联,不支持一对多
*/
public void parse(MetaProperty property, PersistentClass pclazz) {
// feature
HibernatePropertyFeature feature = property
.getFeature(HibernatePropertyFeature.class);
if (feature == null) {
feature = new HibernatePropertyFeature();
}
// value
Value value;
if (property.isCollection()) {
value = buildCollectionValue(property, feature, pclazz);
} else {
value = buildElement(pclazz, property, feature, pclazz.getTable());
}
// property
Property prop = buildProperty(property, feature, pclazz);
prop.setValue(value);
pclazz.addProperty(prop);
// version
if (feature.isVersion()) {
handleVersion(prop, pclazz);
}
}
/**
* 构造Hibernate的Property
*/
private Property buildProperty(MetaProperty property,
HibernatePropertyFeature feature,
PersistentClass pclazz) {
Property prop = new Property();
prop.setName(property.getName());
if (property.isDynamic()) {
prop.setPropertyAccessorName(
DynamicPropertyAccessStrategy.class.getName());
} else {
prop.setPropertyAccessorName(
ExtendPropertyAccessStrategy.class.getName());
}
prop.setValueGenerationStrategy(NoValueGeneration.INSTANCE);
prop.setLazy(property.isLazy());
prop.setOptional(property.isNotNull());
return prop;
}
public void addProperty(Property prop, XClass declaringClass) {
if ( prop.getValue() instanceof Component ) {
//TODO handle quote and non quote table comparison
String tableName = prop.getValue().getTable().getName();
if ( getJoinsPerRealTableName().containsKey( tableName ) ) {
final Join join = getJoinsPerRealTableName().get( tableName );
addPropertyToJoin( prop, declaringClass, join );
}
else {
addPropertyToPersistentClass( prop, declaringClass );
}
}
else {
addPropertyToPersistentClass( prop, declaringClass );
}
}
private void addPropertyToJoin(Property prop, XClass declaringClass, Join join) {
if ( declaringClass != null ) {
final InheritanceState inheritanceState = inheritanceStatePerClass.get( declaringClass );
if ( inheritanceState == null ) {
throw new AssertionFailure(
"Declaring class is not found in the inheritance state hierarchy: " + declaringClass
);
}
if ( inheritanceState.isEmbeddableSuperclass() ) {
join.addMappedsuperclassProperty(prop);
addPropertyToMappedSuperclass( prop, declaringClass );
}
else {
join.addProperty( prop );
}
}
else {
join.addProperty( prop );
}
}
private static void applyMin(Property property, ConstraintDescriptor<?> descriptor, Dialect dialect) {
if ( Min.class.equals( descriptor.getAnnotation().annotationType() ) ) {
@SuppressWarnings("unchecked")
ConstraintDescriptor<Min> minConstraint = (ConstraintDescriptor<Min>) descriptor;
long min = minConstraint.getAnnotation().value();
@SuppressWarnings("unchecked")
final Iterator<Selectable> itor = property.getColumnIterator();
if ( itor.hasNext() ) {
final Selectable selectable = itor.next();
if ( Column.class.isInstance( selectable ) ) {
Column col = (Column) selectable;
String checkConstraint = col.getQuotedName(dialect) + ">=" + min;
applySQLCheck( col, checkConstraint );
}
}
}
}
private static void applyMax(Property property, ConstraintDescriptor<?> descriptor, Dialect dialect) {
if ( Max.class.equals( descriptor.getAnnotation().annotationType() ) ) {
@SuppressWarnings("unchecked")
ConstraintDescriptor<Max> maxConstraint = (ConstraintDescriptor<Max>) descriptor;
long max = maxConstraint.getAnnotation().value();
@SuppressWarnings("unchecked")
final Iterator<Selectable> itor = property.getColumnIterator();
if ( itor.hasNext() ) {
final Selectable selectable = itor.next();
if ( Column.class.isInstance( selectable ) ) {
Column col = (Column) selectable;
String checkConstraint = col.getQuotedName( dialect ) + "<=" + max;
applySQLCheck( col, checkConstraint );
}
}
}
}
private Property createAnyAssociationAttribute(
MappingDocument sourceDocument,
SingularAttributeSourceAny anyMapping,
Any anyBinding,
String entityName) {
final String attributeName = anyMapping.getName();
bindAny( sourceDocument, anyMapping, anyBinding, anyMapping.getAttributeRole(), anyMapping.getAttributePath() );
prepareValueTypeViaReflection( sourceDocument, anyBinding, entityName, attributeName, anyMapping.getAttributeRole() );
anyBinding.createForeignKey();
Property prop = new Property();
prop.setValue( anyBinding );
bindProperty(
sourceDocument,
anyMapping,
prop
);
return prop;
}
/**
* create a property copy reusing the same value
*/
public static Property shallowCopy(Property property) {
Property clone = new Property();
clone.setCascade( property.getCascade() );
clone.setInsertable( property.isInsertable() );
clone.setLazy( property.isLazy() );
clone.setName( property.getName() );
clone.setNaturalIdentifier( property.isNaturalIdentifier() );
clone.setOptimisticLocked( property.isOptimisticLocked() );
clone.setOptional( property.isOptional() );
clone.setPersistentClass( property.getPersistentClass() );
clone.setPropertyAccessorName( property.getPropertyAccessorName() );
clone.setSelectable( property.isSelectable() );
clone.setUpdateable( property.isUpdateable() );
clone.setValue( property.getValue() );
return clone;
}
public void addProperty(Property prop, Ejb3Column[] columns, XClass declaringClass) {
//Ejb3Column.checkPropertyConsistency( ); //already called earlier
/*
* Check table matches between the component and the columns
* if not, change the component table if no properties are set
* if a property is set already the core cannot support that
*/
if (columns != null) {
Table table = columns[0].getTable();
if ( !table.equals( component.getTable() ) ) {
if ( component.getPropertySpan() == 0 ) {
component.setTable( table );
}
else {
throw new AnnotationException(
"A component cannot hold properties split into 2 different tables: "
+ this.getPath()
);
}
}
}
addProperty( prop, declaringClass );
}
/**
* Retrieves a PropertyAccessor instance based on the given property definition and
* entity mode.
*
* @param property The property for which to retrieve an accessor.
* @param mode The mode for the resulting entity.
* @return An appropriate accessor.
* @throws MappingException
*/
public static PropertyAccessor getPropertyAccessor(Property property, EntityMode mode) throws MappingException {
//TODO: this is temporary in that the end result will probably not take a Property reference per-se.
if ( null == mode || EntityMode.POJO.equals( mode ) ) {
return getPojoPropertyAccessor( property.getPropertyAccessorName() );
}
else if ( EntityMode.MAP.equals( mode ) ) {
return getDynamicMapPropertyAccessor();
}
else if ( EntityMode.DOM4J.equals( mode ) ) {
//TODO: passing null here, because this method is not really used for DOM4J at the moment
// but it is still a bug, if we don't get rid of this!
return getDom4jPropertyAccessor( property.getAccessorPropertyName( mode ), property.getType(), null );
}
else {
throw new MappingException( "Unknown entity mode [" + mode + "]" );
}
}
private <X> void applyIdMetadata(MappedSuperclass mappingType, MappedSuperclassTypeImpl<X> jpaMappingType) {
if ( mappingType.hasIdentifierProperty() ) {
final Property declaredIdentifierProperty = mappingType.getDeclaredIdentifierProperty();
if ( declaredIdentifierProperty != null ) {
jpaMappingType.getBuilder().applyIdAttribute(
attributeFactory.buildIdAttribute( jpaMappingType, declaredIdentifierProperty )
);
}
}
//a MappedSuperclass can have no identifier if the id is set below in the hierarchy
else if ( mappingType.getIdentifierMapper() != null ) {
@SuppressWarnings("unchecked")
Iterator<Property> propertyIterator = mappingType.getIdentifierMapper().getPropertyIterator();
Set<SingularAttribute<? super X, ?>> attributes = buildIdClassAttributes(
jpaMappingType,
propertyIterator
);
jpaMappingType.getBuilder().applyIdClassAttributes( attributes );
}
}
@SuppressWarnings({"unchecked"})
public <X, Y> SingularAttributeImpl<X, Y> buildVersionAttribute(
AbstractIdentifiableType<X> ownerType,
Property property) {
LOG.trace( "Building version attribute [ownerType.getTypeName()" + "." + "property.getName()]" );
final AttributeContext<X> attributeContext = wrap( ownerType, property );
final SingularAttributeMetadata<X, Y> attributeMetadata =
(SingularAttributeMetadata<X, Y>) determineAttributeMetadata( attributeContext, versionMemberResolver );
final Type<Y> metaModelType = getMetaModelType( attributeMetadata.getValueContext() );
return new SingularAttributeImpl.Version(
property.getName(),
attributeMetadata.getJavaType(),
ownerType,
attributeMetadata.getMember(),
metaModelType,
attributeMetadata.getPersistentAttributeType()
);
}
public static LazyAttributeDescriptor from(
Property property,
int attributeIndex,
int lazyIndex) {
String fetchGroupName = property.getLazyGroup();
if ( fetchGroupName == null ) {
fetchGroupName = property.getType().isCollectionType()
? property.getName()
: "DEFAULT";
}
return new LazyAttributeDescriptor(
attributeIndex,
lazyIndex,
property.getName(),
property.getType(),
fetchGroupName
);
}
private static Getter getGetter(Property mappingProperty) {
if ( mappingProperty == null || !mappingProperty.getPersistentClass().hasPojoRepresentation() ) {
return null;
}
final PropertyAccessStrategyResolver propertyAccessStrategyResolver =
mappingProperty.getPersistentClass().getServiceRegistry().getService( PropertyAccessStrategyResolver.class );
final PropertyAccessStrategy propertyAccessStrategy = propertyAccessStrategyResolver.resolvePropertyAccessStrategy(
mappingProperty.getClass(),
mappingProperty.getPropertyAccessorName(),
EntityMode.POJO
);
final PropertyAccess propertyAccess = propertyAccessStrategy.buildPropertyAccess(
mappingProperty.getPersistentClass().getMappedClass(),
mappingProperty.getName()
);
return propertyAccess.getGetter();
}
private boolean hasPartialUpdateComponentGeneration(Component component) {
Iterator subProperties = component.getPropertyIterator();
while ( subProperties.hasNext() ) {
Property prop = ( Property ) subProperties.next();
if ( prop.getGeneration() == PropertyGeneration.ALWAYS ) {
return true;
}
else if ( prop.getValue() instanceof Component ) {
if ( hasPartialUpdateComponentGeneration( ( Component ) prop.getValue() ) ) {
return true;
}
}
}
return false;
}
private static void bindVersioningProperty(Table table, Element subnode, Mappings mappings,
String name, RootClass entity, java.util.Map inheritedMetas) {
String propertyName = subnode.attributeValue( "name" );
SimpleValue val = new SimpleValue( table );
bindSimpleValue( subnode, val, false, propertyName, mappings );
if ( !val.isTypeSpecified() ) {
// this is either a <version/> tag with no type attribute,
// or a <timestamp/> tag
if ( "version".equals( name ) ) {
val.setTypeName( "integer" );
}
else {
if ( "db".equals( subnode.attributeValue( "source" ) ) ) {
val.setTypeName( "dbtimestamp" );
}
else {
val.setTypeName( "timestamp" );
}
}
}
Property prop = new Property();
prop.setValue( val );
bindProperty( subnode, prop, mappings, inheritedMetas );
// for version properties marked as being generated, make sure they are "always"
// generated; aka, "insert" is invalid; this is dis-allowed by the DTD,
// but just to make sure...
if ( prop.getGeneration() == PropertyGeneration.INSERT ) {
throw new MappingException( "'generated' attribute cannot be 'insert' for versioning property" );
}
makeVersion( subnode, val );
entity.setVersion( prop );
entity.addProperty( prop );
}
private boolean hasPartialInsertComponentGeneration(Component component) {
Iterator subProperties = component.getPropertyIterator();
while ( subProperties.hasNext() ) {
Property prop = ( Property ) subProperties.next();
if ( prop.getGeneration() == PropertyGeneration.ALWAYS || prop.getGeneration() == PropertyGeneration.INSERT ) {
return true;
}
else if ( prop.getValue() instanceof Component ) {
if ( hasPartialInsertComponentGeneration( ( Component ) prop.getValue() ) ) {
return true;
}
}
}
return false;
}
private boolean hasAnyMutableNaturalIdProps() {
final Iterator itr = rootEntityDescriptor.getDeclaredPropertyIterator();
while ( itr.hasNext() ) {
final Property prop = (Property) itr.next();
if ( prop.isNaturalIdentifier() && prop.isUpdateable() ) {
return true;
}
}
return false;
}
protected AbstractComponentTuplizer(Component component) {
propertySpan = component.getPropertySpan();
getters = new Getter[propertySpan];
setters = new Setter[propertySpan];
Iterator iter = component.getPropertyIterator();
boolean foundCustomAccessor=false;
int i = 0;
while ( iter.hasNext() ) {
Property prop = ( Property ) iter.next();
getters[i] = buildGetter( component, prop );
setters[i] = buildSetter( component, prop );
if ( !prop.isBasicPropertyAccessor() ) {
foundCustomAccessor = true;
}
i++;
}
hasCustomAccessors = foundCustomAccessor;
String[] getterNames = new String[propertySpan];
String[] setterNames = new String[propertySpan];
Class[] propTypes = new Class[propertySpan];
for ( int j = 0; j < propertySpan; j++ ) {
getterNames[j] = getters[j].getMethodName();
setterNames[j] = setters[j].getMethodName();
propTypes[j] = getters[j].getReturnType();
}
instantiator = buildInstantiator( component );
}
@SuppressWarnings("unchecked")
private static boolean applyNotNull(Property property, ConstraintDescriptor<?> descriptor) {
boolean hasNotNull = false;
if ( NotNull.class.equals( descriptor.getAnnotation().annotationType() ) ) {
// single table inheritance should not be forced to null due to shared state
if ( !( property.getPersistentClass() instanceof SingleTableSubclass ) ) {
//composite should not add not-null on all columns
if ( !property.isComposite() ) {
final Iterator<Selectable> itr = property.getColumnIterator();
while ( itr.hasNext() ) {
final Selectable selectable = itr.next();
if ( Column.class.isInstance( selectable ) ) {
Column.class.cast( selectable ).setNullable( false );
}
else {
LOG.debugf(
"@NotNull was applied to attribute [%s] which is defined (at least partially) " +
"by formula(s); formula portions will be skipped",
property.getName()
);
}
}
}
}
hasNotNull = true;
}
return hasNotNull;
}
private PropertyAccessor buildPropertyAccessor(Property mappedProperty) {
if ( mappedProperty.isBackRef() ) {
return mappedProperty.getPropertyAccessor(null);
}
else {
return PropertyAccessorFactory.getDom4jPropertyAccessor(
mappedProperty.getNodeName(),
mappedProperty.getType(),
getEntityMetamodel().getSessionFactory()
);
}
}
@SuppressWarnings("unchecked")
protected String[] getColumnNames(Class<?> peristentClass, String[] includedFields) throws MappingException {
Collection<String> columns = new ArrayList<String>();
for (int i = 0; i < includedFields.length; i++) {
String propertyName = includedFields[i];
Property property = getMapping(peristentClass).getProperty(propertyName);
for (Iterator<Column> it = property.getColumnIterator(); it.hasNext(); ) {
Column col = it.next();
columns.add(col.getName());
}
}
return columns.toArray(new String[columns.size()]);
}
/**
* Builds the <code>Join</code> instance for the mapped by side of a <i>OneToOne</i> association using
* a join tables.
* <p>
* Note:<br/>
* <ul>
* <li>From the mappedBy side we should not create the PK nor the FK, this is handled from the other side.</li>
* <li>This method is a dirty dupe of EntityBinder.bindSecondaryTable</i>.
* </p>
*/
private Join buildJoinFromMappedBySide(PersistentClass persistentClass, Property otherSideProperty, Join originalJoin) {
Join join = new Join();
join.setPersistentClass( persistentClass );
//no check constraints available on joins
join.setTable( originalJoin.getTable() );
join.setInverse( true );
SimpleValue key = new DependantValue( buildingContext, join.getTable(), persistentClass.getIdentifier() );
//TODO support @ForeignKey
join.setKey( key );
join.setSequentialSelect( false );
//TODO support for inverse and optional
join.setOptional( true ); //perhaps not quite per-spec, but a Good Thing anyway
key.setCascadeDeleteEnabled( false );
Iterator mappedByColumns = otherSideProperty.getValue().getColumnIterator();
while ( mappedByColumns.hasNext() ) {
Column column = (Column) mappedByColumns.next();
Column copy = new Column();
copy.setLength( column.getLength() );
copy.setScale( column.getScale() );
copy.setValue( key );
copy.setName( column.getQuotedName() );
copy.setNullable( column.isNullable() );
copy.setPrecision( column.getPrecision() );
copy.setUnique( column.isUnique() );
copy.setSqlType( column.getSqlType() );
copy.setCheckConstraint( column.getCheckConstraint() );
copy.setComment( column.getComment() );
copy.setDefaultValue( column.getDefaultValue() );
key.addColumn( copy );
}
persistentClass.addJoin( join );
return join;
}
private static Getter getGetter(Property mappingProperty) {
if ( mappingProperty == null || !mappingProperty.getPersistentClass().hasPojoRepresentation() ) {
return null;
}
PropertyAccessor pa = PropertyAccessorFactory.getPropertyAccessor( mappingProperty, EntityMode.POJO );
return pa.getGetter( mappingProperty.getPersistentClass().getMappedClass(), mappingProperty.getName() );
}
private static void matchColumnsByProperty(Property property, Map<Column, Set<Property>> columnsToProperty) {
if ( property == null ) {
return;
}
if ( "noop".equals( property.getPropertyAccessorName() )
|| "embedded".equals( property.getPropertyAccessorName() ) ) {
return;
}
// FIXME cannot use subproperties becasue the caller needs top level properties
// if ( property.isComposite() ) {
// Iterator subProperties = ( (Component) property.getValue() ).getPropertyIterator();
// while ( subProperties.hasNext() ) {
// matchColumnsByProperty( (Property) subProperties.next(), columnsToProperty );
// }
// }
else {
Iterator columnIt = property.getColumnIterator();
while ( columnIt.hasNext() ) {
//can be a Formula so we don't cast
Object column = columnIt.next();
//noinspection SuspiciousMethodCalls
if ( columnsToProperty.containsKey( column ) ) {
columnsToProperty.get( column ).add( property );
}
}
}
}
/**
* Generates an IdentifierProperty representation of the for a given entity mapping.
*
* @param mappedEntity The mapping definition of the entity.
* @param generator The identifier value generator to use for this identifier.
* @return The appropriate IdentifierProperty definition.
*/
public static IdentifierProperty buildIdentifierProperty(PersistentClass mappedEntity, IdentifierGenerator generator) {
String mappedUnsavedValue = mappedEntity.getIdentifier().getNullValue();
Type type = mappedEntity.getIdentifier().getType();
Property property = mappedEntity.getIdentifierProperty();
IdentifierValue unsavedValue = UnsavedValueFactory.getUnsavedIdentifierValue(
mappedUnsavedValue,
getGetter( property ),
type,
getConstructor(mappedEntity)
);
if ( property == null ) {
// this is a virtual id property...
return new IdentifierProperty(
type,
mappedEntity.hasEmbeddedIdentifier(),
mappedEntity.hasIdentifierMapper(),
unsavedValue,
generator
);
}
else {
return new IdentifierProperty(
property.getName(),
property.getNodeName(),
type,
mappedEntity.hasEmbeddedIdentifier(),
unsavedValue,
generator
);
}
}
private <X> void applyIdMetadata(PersistentClass persistentClass, EntityTypeImpl<X> jpaEntityType) {
if ( persistentClass.hasIdentifierProperty() ) {
final Property declaredIdentifierProperty = persistentClass.getDeclaredIdentifierProperty();
if ( declaredIdentifierProperty != null ) {
jpaEntityType.getBuilder().applyIdAttribute(
attributeFactory.buildIdAttribute( jpaEntityType, declaredIdentifierProperty )
);
}
}
else if ( persistentClass.hasIdentifierMapper() ) {
@SuppressWarnings("unchecked")
Iterator<Property> propertyIterator = persistentClass.getIdentifierMapper().getPropertyIterator();
Set<SingularAttribute<? super X, ?>> attributes = buildIdClassAttributes( jpaEntityType, propertyIterator );
jpaEntityType.getBuilder().applyIdClassAttributes( attributes );
}
else {
final KeyValue value = persistentClass.getIdentifier();
if ( value instanceof Component ) {
final Component component = (Component) value;
if ( component.getPropertySpan() > 1 ) {
//FIXME we are an Hibernate embedded id (ie not type)
}
else {
//FIXME take care of declared vs non declared property
jpaEntityType.getBuilder().applyIdAttribute(
attributeFactory.buildIdAttribute(
jpaEntityType,
(Property) component.getPropertyIterator().next()
)
);
}
}
}
}
private <X> void applyVersionAttribute(PersistentClass persistentClass, EntityTypeImpl<X> jpaEntityType) {
final Property declaredVersion = persistentClass.getDeclaredVersion();
if ( declaredVersion != null ) {
jpaEntityType.getBuilder().applyVersionAttribute(
attributeFactory.buildVersionAttribute( jpaEntityType, declaredVersion )
);
}
}
private <X> void applyVersionAttribute(MappedSuperclass mappingType, MappedSuperclassTypeImpl<X> jpaMappingType) {
final Property declaredVersion = mappingType.getDeclaredVersion();
if ( declaredVersion != null ) {
jpaMappingType.getBuilder().applyVersionAttribute(
attributeFactory.buildVersionAttribute( jpaMappingType, declaredVersion )
);
}
}
private <X> Set<SingularAttribute<? super X, ?>> buildIdClassAttributes(
AbstractIdentifiableType<X> ownerType,
Iterator<Property> propertyIterator) {
if ( LOG.isTraceEnabled() ) {
LOG.trace( "Building old-school composite identifier [" + ownerType.getJavaType().getName() + ']' );
}
Set<SingularAttribute<? super X, ?>> attributes = new HashSet<SingularAttribute<? super X, ?>>();
while ( propertyIterator.hasNext() ) {
attributes.add( attributeFactory.buildIdAttribute( ownerType, propertyIterator.next() ) );
}
return attributes;
}