下面列出了javax.validation.constraints.Digits#org.hibernate.mapping.Column 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Generates the statements needed to create a table.
*/
public List<String> createTable(Table table, Metadata metadata) {
if (spannerDatabaseInfo.getAllTables().contains(table.getName())) {
return Collections.EMPTY_LIST;
}
Iterable<Column> keyColumns;
if (table.hasPrimaryKey()) {
// a typical table that corresponds to an entity type
keyColumns = getSortedPkColumns(table, metadata);
} else if (isElementCollection(table, metadata)) {
// a table that is actually an element collection property
keyColumns = table::getColumnIterator;
} else {
// the case corresponding to a sequence-table that will only have 1 row.
keyColumns = Collections.emptyList();
}
return getCreateTableStrings(table, metadata, keyColumns);
}
private static List<Column> getSortedPkColumns(Table table, Metadata metadata) {
Interleaved interleaved = SchemaUtils.getInterleaveAnnotation(table, metadata);
if (interleaved == null) {
return table.getPrimaryKey().getColumns();
}
Table parentTable = SchemaUtils.getTable(interleaved.parentEntity(), metadata);
List<Column> sortedParentPkColumns = getSortedPkColumns(parentTable, metadata);
List<Column> sortedCurrentPkColumns = table.getPrimaryKey().getColumns().stream()
.filter(column -> !sortedParentPkColumns.contains(column))
.collect(Collectors.toList());
ArrayList<Column> currentPkColumns = new ArrayList<>();
currentPkColumns.addAll(sortedParentPkColumns);
currentPkColumns.addAll(sortedCurrentPkColumns);
return currentPkColumns;
}
private void addConstraintToColumn(final String columnName ) {
Column column = table.getColumn(
new Column(
buildingContext.getMetadataCollector().getPhysicalColumnName( table, columnName )
)
);
if ( column == null ) {
throw new AnnotationException(
"@Index references a unknown column: " + columnName
);
}
if ( unique ) {
table.getOrCreateUniqueKey( indexName ).addColumn( column );
}
else {
table.getOrCreateIndex( indexName ).addColumn( column );
}
}
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 static void applyDigits(Property property, ConstraintDescriptor<?> descriptor) {
if ( Digits.class.equals( descriptor.getAnnotation().annotationType() ) ) {
@SuppressWarnings("unchecked")
ConstraintDescriptor<Digits> digitsConstraint = (ConstraintDescriptor<Digits>) descriptor;
int integerDigits = digitsConstraint.getAnnotation().integer();
int fractionalDigits = digitsConstraint.getAnnotation().fraction();
@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;
col.setPrecision( integerDigits + fractionalDigits );
col.setScale( fractionalDigits );
}
}
}
}
private static void applySize(Property property, ConstraintDescriptor<?> descriptor, PropertyDescriptor propertyDescriptor) {
if ( Size.class.equals( descriptor.getAnnotation().annotationType() )
&& String.class.equals( propertyDescriptor.getElementClass() ) ) {
@SuppressWarnings("unchecked")
ConstraintDescriptor<Size> sizeConstraint = (ConstraintDescriptor<Size>) descriptor;
int max = sizeConstraint.getAnnotation().max();
@SuppressWarnings("unchecked")
final Iterator<Selectable> itor = property.getColumnIterator();
if ( itor.hasNext() ) {
final Selectable selectable = itor.next();
Column col = (Column) selectable;
if ( max < Integer.MAX_VALUE ) {
col.setLength( max );
}
}
}
}
private static void applyLength(Property property, ConstraintDescriptor<?> descriptor, PropertyDescriptor propertyDescriptor) {
if ( "org.hibernate.validator.constraints.Length".equals(
descriptor.getAnnotation().annotationType().getName()
)
&& String.class.equals( propertyDescriptor.getElementClass() ) ) {
@SuppressWarnings("unchecked")
int max = (Integer) descriptor.getAttributes().get( "max" );
@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;
if ( max < Integer.MAX_VALUE ) {
col.setLength( max );
}
}
}
}
}
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 );
}
/**
* Called to apply column definitions from the referenced FK column to this column.
*
* @param column the referenced column.
*/
public void overrideFromReferencedColumnIfNecessary(org.hibernate.mapping.Column column) {
if (getMappingColumn() != null) {
// columnDefinition can also be specified using @JoinColumn, hence we have to check
// whether it is set or not
if ( StringHelper.isEmpty( sqlType ) ) {
sqlType = column.getSqlType();
getMappingColumn().setSqlType( sqlType );
}
// these properties can only be applied on the referenced column - we can just take them over
getMappingColumn().setLength(column.getLength());
getMappingColumn().setPrecision(column.getPrecision());
getMappingColumn().setScale(column.getScale());
}
}
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 String getFromAndWhereFormula(
String tableName,
Iterator<Selectable> collectionTableColumns,
Iterator<Selectable> referencedEntityColumns) {
String alias = "$alias$";
StringBuilder fromAndWhereSb = new StringBuilder( " from " )
.append( tableName )
//.append(" as ") //Oracle doesn't support it in subqueries
.append( " " )
.append( alias ).append( " where " );
while ( collectionTableColumns.hasNext() ) {
Column colColumn = (Column) collectionTableColumns.next();
Column refColumn = (Column) referencedEntityColumns.next();
fromAndWhereSb.append( alias )
.append( '.' )
.append( refColumn.getQuotedName() )
.append( '=' )
.append( colColumn.getQuotedName() )
.append( " and " );
}
return fromAndWhereSb.substring( 0, fromAndWhereSb.length() - 5 );
}
public static Ejb3Column[] buildColumnFromAnnotation(
javax.persistence.Column[] anns,
org.hibernate.annotations.Formula formulaAnn,
Nullability nullability,
PropertyHolder propertyHolder,
PropertyData inferredData,
Map<String, Join> secondaryTables,
MetadataBuildingContext context) {
return buildColumnFromAnnotation(
anns,
formulaAnn,
nullability,
propertyHolder,
inferredData,
null,
secondaryTables,
context
);
}
public boolean matches(ForeignKey fk) {
if ( refTable.equalsIgnoreCase( fk.getReferencedTable().getName() ) ) {
if ( fk.getColumnSpan() == references.size() ) {
List fkRefs;
if ( fk.isReferenceToPrimaryKey() ) {
fkRefs = fk.getReferencedTable().getPrimaryKey().getColumns();
}
else {
fkRefs = fk.getReferencedColumns();
}
for ( int i = 0; i < fk.getColumnSpan(); i++ ) {
Column column = fk.getColumn( i );
Column ref = ( Column ) fkRefs.get( i );
if ( !hasReference( column, ref ) ) {
return false;
}
}
return true;
}
}
return false;
}
@Override
public void addColumnNameBinding(Table table, Identifier logicalName, Column column) throws DuplicateMappingException {
TableColumnNameBinding binding = null;
if ( columnNameBindingByTableMap == null ) {
columnNameBindingByTableMap = new HashMap<>();
}
else {
binding = columnNameBindingByTableMap.get( table );
}
if ( binding == null ) {
binding = new TableColumnNameBinding( table.getName() );
columnNameBindingByTableMap.put( table, binding );
}
binding.addBinding( logicalName, column );
}
public static void bindColumn(Element node, Column column, boolean isNullable) {
Attribute lengthNode = node.attribute( "length" );
if ( lengthNode != null ) column.setLength( Integer.parseInt( lengthNode.getValue() ) );
Attribute scalNode = node.attribute( "scale" );
if ( scalNode != null ) column.setScale( Integer.parseInt( scalNode.getValue() ) );
Attribute precNode = node.attribute( "precision" );
if ( precNode != null ) column.setPrecision( Integer.parseInt( precNode.getValue() ) );
Attribute nullNode = node.attribute( "not-null" );
column.setNullable( nullNode == null ? isNullable : nullNode.getValue().equals( "false" ) );
Attribute unqNode = node.attribute( "unique" );
if ( unqNode != null ) column.setUnique( unqNode.getValue().equals( "true" ) );
column.setCheckConstraint( node.attributeValue( "check" ) );
column.setDefaultValue( node.attributeValue( "default" ) );
Attribute typeNode = node.attribute( "sql-type" );
if ( typeNode != null ) column.setSqlType( typeNode.getValue() );
Element comment = node.element("comment");
if (comment!=null) column.setComment( comment.getTextTrim() );
}
public void testForeignKeyCreation() {
PersistentClass classMapping = getCfg().getClassMapping("org.hibernate.test.propertyref.basic.Account");
Iterator foreignKeyIterator = classMapping.getTable().getForeignKeyIterator();
boolean found = false;
while ( foreignKeyIterator.hasNext() ) {
ForeignKey element = (ForeignKey) foreignKeyIterator.next();
if(element.getReferencedEntityName().equals(Person.class.getName() ) ) {
if(!element.isReferenceToPrimaryKey() ) {
List referencedColumns = element.getReferencedColumns();
Column column = (Column) referencedColumns.get(0);
if(column.getName().equals("person_userid") ) {
found = true; // extend test to include the columns
}
}
}
}
assertTrue("Property ref foreign key not found",found);
}
@Test
public void testEntityToDatabaseBindingMetadata() {
Metadata metadata = MetadataExtractorIntegrator.INSTANCE.getMetadata();
for ( PersistentClass persistentClass : metadata.getEntityBindings()) {
Table table = persistentClass.getTable();
LOGGER.info( "Entity: {} is mapped to table: {}",
persistentClass.getClassName(),
table.getName()
);
for(Iterator propertyIterator =
persistentClass.getPropertyIterator(); propertyIterator.hasNext(); ) {
Property property = (Property) propertyIterator.next();
for(Iterator columnIterator =
property.getColumnIterator(); columnIterator.hasNext(); ) {
Column column = (Column) columnIterator.next();
LOGGER.info( "Property: {} is mapped on table column: {} of type: {}",
property.getName(),
column.getName(),
column.getSqlType()
);
}
}
}
}
/**
* 构造列
*/
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);
}
}
}
}
/**
* Processes the columns of the table and creates Unique Constraints for columns
* annotated with @Column(unique = true).
*/
private static void initializeUniqueConstraints(Table table) {
Iterator<Column> colIterator = table.getColumnIterator();
while (colIterator.hasNext()) {
Column col = colIterator.next();
if (col.isUnique()) {
String name = Constraint.generateName("UK_", table, col);
UniqueKey uk = table.getOrCreateUniqueKey(name);
uk.addColumn(col);
}
}
}
private List<String> getCreateTableStrings(
Table table, Metadata metadata, Iterable<Column> keyColumns) {
// Get the comma separated string of the primary keys of the table.
String primaryKeyColNames = StreamSupport.stream(keyColumns.spliterator(), false)
.map(Column::getQuotedName)
.collect(Collectors.joining(","));
// Get the comma separated string of all columns of the table.
Iterable<Column> columnIterable = () -> (Iterator<Column>) table.getColumnIterator();
String allColumnNames = StreamSupport.stream(columnIterable.spliterator(), false)
.map(column -> buildColumnTypeString(column, metadata))
.collect(Collectors.joining(","));
ArrayList<String> statements = new ArrayList<>();
// Build the Create Table string.
String createTableString = MessageFormat.format(
CREATE_TABLE_TEMPLATE,
table.getQuotedName(),
allColumnNames,
primaryKeyColNames,
getInterleavedClause(table, metadata));
statements.add(createTableString);
if (table.getName().equals(SequenceStyleGenerator.DEF_SEQUENCE_NAME)) {
// Caches the INSERT statement since DML statements must be run after a DDL batch.
addStatementAfterDdlBatch(
metadata,
"INSERT INTO " + SequenceStyleGenerator.DEF_SEQUENCE_NAME + " ("
+ SequenceStyleGenerator.DEF_VALUE_COLUMN + ") VALUES(1)");
}
return statements;
}
private static void applySQLCheck(Column col, String checkConstraint) {
String existingCheck = col.getCheckConstraint();
// need to check whether the new check is already part of the existing check, because applyDDL can be called
// multiple times
if ( StringHelper.isNotEmpty( existingCheck ) && !existingCheck.contains( checkConstraint ) ) {
checkConstraint = col.getCheckConstraint() + " AND " + checkConstraint;
}
col.setCheckConstraint( checkConstraint );
}
@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;
}
/**
* 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 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 );
}
}
}
}
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 );
}
private void makeOneToManyMapKeyColumnNullableIfNotInProperty(
final XProperty property) {
final org.hibernate.mapping.Map map = (org.hibernate.mapping.Map) this.collection;
if ( map.isOneToMany() &&
property.isAnnotationPresent( MapKeyColumn.class ) ) {
final Value indexValue = map.getIndex();
if ( indexValue.getColumnSpan() != 1 ) {
throw new AssertionFailure( "Map key mapped by @MapKeyColumn does not have 1 column" );
}
final Selectable selectable = indexValue.getColumnIterator().next();
if ( selectable.isFormula() ) {
throw new AssertionFailure( "Map key mapped by @MapKeyColumn is a Formula" );
}
Column column = (Column) map.getIndex().getColumnIterator().next();
if ( !column.isNullable() ) {
final PersistentClass persistentClass = ( ( OneToMany ) map.getElement() ).getAssociatedClass();
// check if the index column has been mapped by the associated entity to a property;
// @MapKeyColumn only maps a column to the primary table for the one-to-many, so we only
// need to check "un-joined" properties.
if ( !propertyIteratorContainsColumn( persistentClass.getUnjoinedPropertyIterator(), column ) ) {
// The index column is not mapped to an associated entity property so we can
// safely make the index column nullable.
column.setNullable( true );
}
}
}
}
private boolean propertyIteratorContainsColumn(Iterator propertyIterator, Column column) {
for ( Iterator it = propertyIterator; it.hasNext(); ) {
final Property property = (Property) it.next();
for ( Iterator<Selectable> selectableIterator = property.getColumnIterator(); selectableIterator.hasNext(); ) {
final Selectable selectable = selectableIterator.next();
if ( column.equals( selectable ) ) {
final Column iteratedColumn = (Column) selectable;
if ( column.getValue().getTable().equals( iteratedColumn.getValue().getTable() ) ) {
return true;
}
}
}
}
return false;
}