下面列出了怎么用org.hibernate.mapping.SimpleValue的API类实例代码及写法,或者点击链接到github查看源代码。
private static void bindDiscriminatorColumnToRootPersistentClass(
RootClass rootClass,
Ejb3DiscriminatorColumn discriminatorColumn,
Map<String, Join> secondaryTables,
PropertyHolder propertyHolder,
MetadataBuildingContext context) {
if ( rootClass.getDiscriminator() == null ) {
if ( discriminatorColumn == null ) {
throw new AssertionFailure( "discriminator column should have been built" );
}
discriminatorColumn.setJoins( secondaryTables );
discriminatorColumn.setPropertyHolder( propertyHolder );
SimpleValue discriminatorColumnBinding = new SimpleValue( context, rootClass.getTable() );
rootClass.setDiscriminator( discriminatorColumnBinding );
discriminatorColumn.linkWithValue( discriminatorColumnBinding );
discriminatorColumnBinding.setTypeName( discriminatorColumn.getDiscriminatorTypeName() );
rootClass.setPolymorphic( true );
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Setting discriminator for entity {0}", rootClass.getEntityName() );
}
}
}
public void linkValueUsingDefaultColumnNaming(
Column referencedColumn,
PersistentClass referencedEntity,
SimpleValue value) {
String logicalReferencedColumn = getBuildingContext().getMetadataCollector().getLogicalColumnName(
referencedEntity.getTable(),
referencedColumn.getQuotedName()
);
String columnName = buildDefaultColumnName( referencedEntity, logicalReferencedColumn );
//yuk side effect on an implicit column
setLogicalColumnName( columnName );
setReferencedColumn( logicalReferencedColumn );
initMappingColumn(
columnName,
null, referencedColumn.getLength(),
referencedColumn.getPrecision(),
referencedColumn.getScale(),
getMappingColumn() != null ? getMappingColumn().isNullable() : false,
referencedColumn.getSqlType(),
getMappingColumn() != null ? getMappingColumn().isUnique() : false,
false
);
linkWithValue( value );
}
private Property makePropertyAndValue() {
validateBind();
LOG.debugf( "MetadataSourceProcessor property %s with lazy=%s", name, lazy );
final String containerClassName = holder.getClassName();
holder.startingProperty( property );
simpleValueBinder = new SimpleValueBinder();
simpleValueBinder.setBuildingContext( buildingContext );
simpleValueBinder.setPropertyName( name );
simpleValueBinder.setReturnedClassName( returnedClassName );
simpleValueBinder.setColumns( columns );
simpleValueBinder.setPersistentClassName( containerClassName );
simpleValueBinder.setType(
property,
returnedClass,
containerClassName,
holder.resolveAttributeConverterDescriptor( property )
);
simpleValueBinder.setReferencedEntityName( referencedEntityName );
simpleValueBinder.setAccessType( accessType );
SimpleValue propertyValue = simpleValueBinder.make();
setValue( propertyValue );
return makeProperty();
}
public static void linkJoinColumnWithValueOverridingNameIfImplicit(
PersistentClass referencedEntity,
Iterator columnIterator,
Ejb3JoinColumn[] columns,
SimpleValue value) {
for (Ejb3JoinColumn joinCol : columns) {
Column synthCol = (Column) columnIterator.next();
if ( joinCol.isNameDeferred() ) {
//this has to be the default value
joinCol.linkValueUsingDefaultColumnNaming( synthCol, referencedEntity, value );
}
else {
joinCol.linkWithValue( value );
joinCol.overrideFromReferencedColumnIfNecessary( synthCol );
}
}
}
private void setFKNameIfDefined(Join join) {
// just awful..
org.hibernate.annotations.Table matchingTable = findMatchingComplimentTableAnnotation( join );
if ( matchingTable != null && !BinderHelper.isEmptyAnnotationValue( matchingTable.foreignKey().name() ) ) {
( (SimpleValue) join.getKey() ).setForeignKeyName( matchingTable.foreignKey().name() );
}
else {
javax.persistence.SecondaryTable jpaSecondaryTable = findMatchingSecondaryTable( join );
if ( jpaSecondaryTable != null ) {
if ( jpaSecondaryTable.foreignKey().value() == ConstraintMode.NO_CONSTRAINT ) {
( (SimpleValue) join.getKey() ).setForeignKeyName( "none" );
}
else {
( (SimpleValue) join.getKey() ).setForeignKeyName( StringHelper.nullIfEmpty( jpaSecondaryTable.foreignKey().name() ) );
( (SimpleValue) join.getKey() ).setForeignKeyDefinition( StringHelper.nullIfEmpty( jpaSecondaryTable.foreignKey().foreignKeyDefinition() ) );
}
}
}
}
private void resolveLob(final SingularAttributeSourceBasic attributeSource, SimpleValue value) {
// Resolves whether the property is LOB based on the type attribute on the attribute property source.
// Essentially this expects the type to map to a CLOB/NCLOB/BLOB sql type internally and compares.
if ( !value.isLob() && value.getTypeName() != null ) {
final TypeResolver typeResolver = attributeSource.getBuildingContext().getMetadataCollector().getTypeResolver();
final BasicType basicType = typeResolver.basic( value.getTypeName() );
if ( basicType instanceof AbstractSingleColumnStandardBasicType ) {
if ( isLob( ( (AbstractSingleColumnStandardBasicType) basicType ).getSqlTypeDescriptor().getSqlType(), null ) ) {
value.makeLob();
}
}
}
// If the prior check didn't set the lob flag, this will inspect the column sql-type attribute value and
// if this maps to CLOB/NCLOB/BLOB then the value will be marked as lob.
if ( !value.isLob() ) {
for ( RelationalValueSource relationalValueSource : attributeSource.getRelationalValueSources() ) {
if ( ColumnSource.class.isInstance( relationalValueSource ) ) {
if ( isLob( null, ( (ColumnSource) relationalValueSource ).getSqlType() ) ) {
value.makeLob();
}
}
}
}
}
private static void bindSimpleValueType(
MappingDocument mappingDocument,
HibernateTypeSource typeSource,
SimpleValue simpleValue) {
if ( mappingDocument.getBuildingOptions().useNationalizedCharacterData() ) {
simpleValue.makeNationalized();
}
final TypeResolution typeResolution = resolveType( mappingDocument, typeSource );
if ( typeResolution == null ) {
// no explicit type info was found
return;
}
if ( CollectionHelper.isNotEmpty( typeResolution.parameters ) ) {
simpleValue.setTypeParameters( typeResolution.parameters );
}
if ( typeResolution.typeName != null ) {
simpleValue.setTypeName( typeResolution.typeName );
}
}
public void bindColumns(
MappingDocument sourceDocument,
List<ColumnSource> columnSources,
SimpleValue simpleValue,
boolean areColumnsNullableByDefault,
ColumnNamingDelegate columnNamingDelegate) {
for ( ColumnSource columnSource : columnSources ) {
bindColumn(
sourceDocument,
columnSource,
simpleValue,
areColumnsNullableByDefault,
columnNamingDelegate
);
}
}
public void bindColumnsAndFormulas(
MappingDocument sourceDocument,
List<RelationalValueSource> relationalValueSources,
SimpleValue simpleValue,
boolean areColumnsNullableByDefault,
ColumnNamingDelegate columnNamingDelegate) {
for ( RelationalValueSource relationalValueSource : relationalValueSources ) {
if ( ColumnSource.class.isInstance( relationalValueSource ) ) {
final ColumnSource columnSource = (ColumnSource) relationalValueSource;
bindColumn(
sourceDocument,
columnSource,
simpleValue,
areColumnsNullableByDefault,
columnNamingDelegate
);
}
else {
final DerivedValueSource formulaSource = (DerivedValueSource) relationalValueSource;
simpleValue.addFormula( new Formula( formulaSource.getExpression() ) );
}
}
}
private static void bindDiscriminatorProperty(Table table, RootClass entity, Element subnode,
Mappings mappings) {
SimpleValue discrim = new SimpleValue( table );
entity.setDiscriminator( discrim );
bindSimpleValue(
subnode,
discrim,
false,
RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME,
mappings
);
if ( !discrim.isTypeSpecified() ) {
discrim.setTypeName( "string" );
// ( (Column) discrim.getColumnIterator().next() ).setType(type);
}
entity.setPolymorphic( true );
if ( "true".equals( subnode.attributeValue( "force" ) ) )
entity.setForceDiscriminator( true );
if ( "false".equals( subnode.attributeValue( "insert" ) ) )
entity.setDiscriminatorInsertable( false );
}
public static void bindIdentifierCollectionSecondPass(Element node,
IdentifierCollection collection, java.util.Map persistentClasses, Mappings mappings,
java.util.Map inheritedMetas) throws MappingException {
bindCollectionSecondPass( node, collection, persistentClasses, mappings, inheritedMetas );
Element subnode = node.element( "collection-id" );
SimpleValue id = new SimpleValue( collection.getCollectionTable() );
bindSimpleValue(
subnode,
id,
false,
IdentifierCollection.DEFAULT_IDENTIFIER_COLUMN_NAME,
mappings
);
collection.setIdentifier( id );
makeIdentifier( subnode, id, mappings );
}
public void testProperCallbacks() {
ValueVisitor vv = new ValueVisitorValidator();
new Any(new Table()).accept(vv);
new Array(new RootClass()).accept(vv);
new Bag(new RootClass()).accept(vv);
new Component(new RootClass()).accept(vv);
new DependantValue(null,null).accept(vv);
new IdentifierBag(null).accept(vv);
new List(null).accept(vv);
new ManyToOne(null).accept(vv);
new Map(null).accept(vv);
new OneToMany(null).accept(vv);
new OneToOne(null, new RootClass() ).accept(vv);
new PrimitiveArray(null).accept(vv);
new Set(null).accept(vv);
new SimpleValue().accept(vv);
}
/**
* 构造SimpleValue
*/
private SimpleValue buildSimpleValue(Table table, PersistentClass pclazz,
MetaProperty property, String columnName) {
// 是否枚举是枚举类型
if (MetaConstant.isEnum(property)) {
Class<?>[] inners = ReflectUtil
.classForName(property.getEnumClass()).getClasses();
if (inners != null) {
for (Class<?> inner : inners) {
if (!AttributeConverter.class.isAssignableFrom(inner)) {
continue;
}
SimpleValue value = new SimpleValue(metadataCollector,
table);
value.setTypeName(StringHelper.join(
AttributeConverterTypeAdapter.NAME_PREFIX,
inner.getName()));
value.setTypeUsingReflection(pclazz.getClassName(),
property.getName());
buildColumn(columnName, property.getLength(), value, table);
return value;
}
}
}
return buildSimpleValue(table, property.getType(), columnName,
property.getLength());
}
/**
* 构造SimpleValue
*/
private SimpleValue buildSimpleValue(Table table, String type,
String columnName, int len) {
SimpleValue value = new SimpleValue(metadataCollector, table);
String typeName = null;
for (Entry<String, String> entry : HBMTYPES.entrySet()) {
if (entry.getValue().equals(type)) {
typeName = entry.getKey();
break;
}
}
value.setTypeName(typeName == null ? type.toLowerCase() : typeName);
buildColumn(columnName, len, value, table);
return value;
}
/**
* 构造列
*/
private Column buildColumn(String name, int len, SimpleValue value,
Table table) {
Column column = new Column();
column.setName(name);
column.setLength(len);
table.addColumn(column);
value.addColumn(column);
return column;
}
private void multilingualProcess(PersistentClass pclazz, MetaEntityImpl entity, String name) {
Class<?> clazz = ReflectUtil.classForName(pclazz.getClassName());
PropertyDescriptor[] descs = BeanUtils.getPropertyDescriptors(clazz);
for (java.beans.PropertyDescriptor desc : descs) {
// 判断是否要做多语言
if (name.equals(desc.getName())) {
for (String lang : LangUtil.getSupportCountries()) {
String propertyName = name + lang;
MetaPropertyImpl langProp = new MetaPropertyImpl();
langProp.setShowType(ShowType.ALWAYS);
langProp.setDynamic(true);
langProp.setName(propertyName);
SimpleValue simpleValue = (SimpleValue) pclazz.getProperty(name).getValue();
if (simpleValue.isLob()) {
langProp.setType(MetaConstant.TYPE_RTF);
} else {
langProp.setType(MetaConstant.TYPE_STRING);
}
Column column = (Column) ((SimpleValue) pclazz.getProperty(name).getValue()).getConstraintColumns().get(0);
if (StringUtils.isNotEmpty(column.getSqlType())) {
HibernatePropertyFeature feature = new HibernatePropertyFeature();
feature.setColumnDefinition(column.getSqlType());
Map<String, Object> features = new HashMap<>(1);
features.put(HibernatePropertyFeature.class.getName(), feature);
langProp.setFeatures(features);
}
langProp.setLength(column.getLength());
parser.parse(langProp, pclazz);
// 增加的字段标记为临时属性,不需要生成数据字典
entity.addTempProperty(propertyName);
}
}
}
}
/**
* 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;
}
/**
* apply an id generator to a SimpleValue
*/
public static void makeIdGenerator(
SimpleValue id,
XProperty idXProperty,
String generatorType,
String generatorName,
MetadataBuildingContext buildingContext,
IdentifierGeneratorDefinition foreignKGeneratorDefinition) {
Map<String, IdentifierGeneratorDefinition> localIdentifiers = null;
if ( foreignKGeneratorDefinition != null ) {
localIdentifiers = new HashMap<>();
localIdentifiers.put( foreignKGeneratorDefinition.getName(), foreignKGeneratorDefinition );
}
makeIdGenerator( id, idXProperty, generatorType, generatorName, buildingContext, localIdentifiers );
}
public JoinedSubclassFkSecondPass(
JoinedSubclass entity,
Ejb3JoinColumn[] inheritanceJoinedColumns,
SimpleValue key,
MetadataBuildingContext buildingContext) {
super( key, inheritanceJoinedColumns );
this.entity = entity;
this.buildingContext = buildingContext;
}
public IdGeneratorResolverSecondPass(
SimpleValue id,
XProperty idXProperty,
String generatorType,
String generatorName,
MetadataBuildingContext buildingContext) {
this.id = id;
this.idXProperty = idXProperty;
this.generatorType = generatorType;
this.generatorName = generatorName;
this.buildingContext = buildingContext;
}
public IdGeneratorResolverSecondPass(
SimpleValue id,
XProperty idXProperty,
String generatorType,
String generatorName,
MetadataBuildingContext buildingContext,
IdentifierGeneratorDefinition localIdentifierGeneratorDefinition) {
this(id,idXProperty,generatorType,generatorName,buildingContext);
this.localIdentifierGeneratorDefinition = localIdentifierGeneratorDefinition;
}
public void copyReferencedStructureAndCreateDefaultJoinColumns(
PersistentClass referencedEntity,
Iterator columnIterator,
SimpleValue value) {
if ( !isNameDeferred() ) {
throw new AssertionFailure( "Building implicit column but the column is not implicit" );
}
while ( columnIterator.hasNext() ) {
Column synthCol = (Column) columnIterator.next();
this.linkValueUsingDefaultColumnNaming( synthCol, referencedEntity, value );
}
//reset for the future
setMappingColumn( null );
}
/**
* used for mappedBy cases
*/
public void linkValueUsingAColumnCopy(Column column, SimpleValue value) {
initMappingColumn(
//column.getName(),
column.getQuotedName(),
null, column.getLength(),
column.getPrecision(),
column.getScale(),
getMappingColumn().isNullable(),
column.getSqlType(),
getMappingColumn().isUnique(),
false //We do copy no strategy here
);
linkWithValue( value );
}
@Override
protected void addColumnBinding(SimpleValue value) {
if ( StringHelper.isEmpty( mappedBy ) ) {
// was the column explicitly quoted in the mapping/annotation
// TODO: in metamodel, we need to better split global quoting and explicit quoting w/ respect to logical names
boolean isLogicalColumnQuoted = StringHelper.isQuoted( getLogicalColumnName() );
final ObjectNameNormalizer nameNormalizer = getBuildingContext().getObjectNameNormalizer();
final String logicalColumnName = nameNormalizer.normalizeIdentifierQuotingAsString( getLogicalColumnName() );
final String referencedColumn = nameNormalizer.normalizeIdentifierQuotingAsString( getReferencedColumn() );
final String unquotedLogColName = StringHelper.unquote( logicalColumnName );
final String unquotedRefColumn = StringHelper.unquote( referencedColumn );
String logicalCollectionColumnName = StringHelper.isNotEmpty( unquotedLogColName )
? unquotedLogColName
: getPropertyName() + '_' + unquotedRefColumn;
logicalCollectionColumnName = getBuildingContext().getMetadataCollector()
.getDatabase()
.getJdbcEnvironment()
.getIdentifierHelper()
.toIdentifier( logicalCollectionColumnName, isLogicalColumnQuoted )
.render();
getBuildingContext().getMetadataCollector().addColumnNameBinding(
value.getTable(),
logicalCollectionColumnName,
getMappingColumn()
);
}
}
private static void checkFilterConditions(Collection collValue) {
//for now it can't happen, but sometime soon...
if ( ( collValue.getFilters().size() != 0 || StringHelper.isNotEmpty( collValue.getWhere() ) ) &&
collValue.getFetchMode() == FetchMode.JOIN &&
!( collValue.getElement() instanceof SimpleValue ) && //SimpleValue (CollectionOfElements) are always SELECT but it does not matter
collValue.getElement().getFetchMode() != FetchMode.JOIN ) {
throw new MappingException(
"@ManyToMany or @CollectionOfElements defining filter or where without join fetching "
+ "not valid within collection using join fetching[" + collValue.getRole() + "]"
);
}
}
private static void bindCollectionSecondPass(
Collection collValue,
PersistentClass collectionEntity,
Ejb3JoinColumn[] joinColumns,
boolean cascadeDeleteEnabled,
XProperty property,
PropertyHolder propertyHolder,
MetadataBuildingContext buildingContext) {
try {
BinderHelper.createSyntheticPropertyReference(
joinColumns,
collValue.getOwner(),
collectionEntity,
collValue,
false,
buildingContext
);
}
catch (AnnotationException ex) {
throw new AnnotationException( "Unable to map collection " + collValue.getOwner().getClassName() + "." + property.getName(), ex );
}
SimpleValue key = buildCollectionKey( collValue, joinColumns, cascadeDeleteEnabled, property, propertyHolder, buildingContext );
if ( property.isAnnotationPresent( ElementCollection.class ) && joinColumns.length > 0 ) {
joinColumns[0].setJPA2ElementCollection( true );
}
TableBinder.bindFk( collValue.getOwner(), collectionEntity, joinColumns, key, false, buildingContext );
}
public SimpleValue make() {
validate();
LOG.debugf( "building SimpleValue for %s", propertyName );
if ( table == null ) {
table = columns[0].getTable();
}
simpleValue = new SimpleValue( buildingContext, table );
if ( isVersion ) {
simpleValue.makeVersion();
}
if ( isNationalized ) {
simpleValue.makeNationalized();
}
if ( isLob ) {
simpleValue.makeLob();
}
linkWithValue();
boolean isInSecondPass = buildingContext.getMetadataCollector().isInSecondPass();
if ( !isInSecondPass ) {
//Defer this to the second pass
buildingContext.getMetadataCollector().addSecondPass( new SetSimpleValueTypeSecondPass( this ) );
}
else {
//We are already in second pass
fillSimpleValue();
}
return simpleValue;
}
private void bindJoinToPersistentClass(Join join, Ejb3JoinColumn[] ejb3JoinColumns, MetadataBuildingContext buildingContext) {
SimpleValue key = new DependantValue( buildingContext, join.getTable(), persistentClass.getIdentifier() );
join.setKey( key );
setFKNameIfDefined( join );
key.setCascadeDeleteEnabled( false );
TableBinder.bindFk( persistentClass, null, ejb3JoinColumns, key, false, buildingContext );
join.createPrimaryKey();
join.createForeignKey();
persistentClass.addJoin( join );
}
public void linkWithValue(SimpleValue value) {
if ( formula != null ) {
value.addFormula( formula );
}
else {
getMappingColumn().setValue( value );
value.addColumn( getMappingColumn(), insertable, updatable );
value.getTable().addColumn( getMappingColumn() );
addColumnBinding( value );
table = value.getTable();
}
}
protected void addColumnBinding(SimpleValue value) {
final String logicalColumnName;
if ( StringHelper.isNotEmpty( this.logicalColumnName ) ) {
logicalColumnName = this.logicalColumnName;
}
else {
final ObjectNameNormalizer normalizer = context.getObjectNameNormalizer();
final Database database = context.getMetadataCollector().getDatabase();
final ImplicitNamingStrategy implicitNamingStrategy = context.getBuildingOptions()
.getImplicitNamingStrategy();
final Identifier implicitName = normalizer.normalizeIdentifierQuoting(
implicitNamingStrategy.determineBasicColumnName(
new ImplicitBasicColumnNameSource() {
@Override
public AttributePath getAttributePath() {
return AttributePath.parse( propertyName );
}
@Override
public boolean isCollectionElement() {
return false;
}
@Override
public MetadataBuildingContext getBuildingContext() {
return context;
}
}
)
);
logicalColumnName = implicitName.render( database.getDialect() );
}
context.getMetadataCollector().addColumnNameBinding( value.getTable(), logicalColumnName, getMappingColumn() );
}