public void testForeignKeyColumnBinding() { GroovyClassLoader cl = new GroovyClassLoader(); GrailsDomainClass oneClass = new DefaultGrailsDomainClass( cl.parseClass( "class TestOneSide {\n" + " Long id \n" + " Long version \n" + " String name \n" + " String description \n" + "}")); GrailsDomainClass domainClass = new DefaultGrailsDomainClass( cl.parseClass( "class TestManySide {\n" + " Long id \n" + " Long version \n" + " String name \n" + " TestOneSide testOneSide \n" + "\n" + " static mapping = {\n" + " columns {\n" + " testOneSide column:'EXPECTED_COLUMN_NAME'" + " }\n" + " }\n" + "}")); DefaultGrailsDomainConfiguration config = getDomainConfig(cl, new Class[] {oneClass.getClazz(), domainClass.getClazz()}); PersistentClass persistentClass = config.getClassMapping("TestManySide"); Column column = (Column) persistentClass.getProperty("testOneSide").getColumnIterator().next(); assertEquals("EXPECTED_COLUMN_NAME", column.getName()); }
public String sqlTemporaryTableCreateString(Dialect dialect, Mapping mapping) throws HibernateException { StringBuffer buffer = new StringBuffer(dialect.getCreateTemporaryTableString()) .append(' ') .append(name) .append(" ("); Iterator itr = getColumnIterator(); while (itr.hasNext()) { final Column column = (Column) itr.next(); buffer.append(column.getQuotedName(dialect)).append(' '); buffer.append(column.getSqlType(dialect, mapping)); if (column.isNullable()) { buffer.append(dialect.getNullColumnString()); } else { buffer.append(" not null"); } if (itr.hasNext()) { buffer.append(", "); } } buffer.append(") "); buffer.append(dialect.getCreateTemporaryTablePostfix()); return buffer.toString(); }
public Iterator sqlCommentStrings(Dialect dialect, String defaultCatalog, String defaultSchema) { List comments = new ArrayList(); if (dialect.supportsCommentOn()) { String tableName = getQualifiedName(dialect, defaultCatalog, defaultSchema); if (comment != null) { comments.add("comment on table " + tableName + " is '" + comment + "'"); } Iterator iter = getColumnIterator(); while (iter.hasNext()) { Column column = (Column) iter.next(); String columnComment = column.getComment(); if (columnComment != null) { comments.add( "comment on column " + tableName + '.' + column.getQuotedName(dialect) + " is '" + columnComment + "'"); } } } return comments.iterator(); }
public Iterator sqlCommentStrings(Dialect dialect, String defaultCatalog, String defaultSchema) { List comments = new ArrayList(); if (dialect.supportsCommentOn()) { String tableName = getQualifiedName(dialect, defaultCatalog, defaultSchema); if (comment != null) { StringBuffer buf = new StringBuffer() .append("comment on table ") .append(tableName) .append(" is '") .append(comment) .append("'"); comments.add(buf.toString()); } Iterator iter = getColumnIterator(); while (iter.hasNext()) { Column column = (Column) iter.next(); String columnComment = column.getComment(); if (columnComment != null) { StringBuffer buf = new StringBuffer() .append("comment on column ") .append(tableName) .append('.') .append(column.getQuotedName(dialect)) .append(" is '") .append(columnComment) .append("'"); comments.add(buf.toString()); } } } return comments.iterator(); }
public void addColumn(Column column) { if (!columns.contains(column)) { columns.add(column); } column.setValue(this); column.setTypeIndex(columns.size() - 1); }
private void bindColumnsToVersioning(Table table, RootClass rc, Set processed, Mapping mapping) { TableIdentifier identifier = TableIdentifier.create(table); String optimisticLockColumnName = revengStrategy.getOptimisticLockColumnName(identifier); if (optimisticLockColumnName != null) { Column column = table.getColumn(new Column(optimisticLockColumnName)); if (column == null) { log.warn( "Column " + column + " wanted for <version>/<timestamp> not found in " + identifier); } else { bindVersionProperty(table, identifier, column, rc, processed, mapping); } } else { log.debug("Scanning " + identifier + " for <version>/<timestamp> columns."); Iterator columnIterator = table.getColumnIterator(); while (columnIterator.hasNext()) { Column column = (Column) columnIterator.next(); boolean useIt = revengStrategy.useColumnForOptimisticLock(identifier, column.getName()); if (useIt && !processed.contains(column)) { bindVersionProperty(table, identifier, column, rc, processed, mapping); return; } } log.debug( "No columns reported while scanning for <version>/<timestamp> columns in " + identifier); } }
private void assertColumnPrecisionAndScale( ConstrainedProperty constrainedProperty, int expectedPrecision, int expectedScale) { Column column = new Column(); GrailsDomainBinder.bindNumericColumnConstraints(column, constrainedProperty); assertEquals(expectedPrecision, column.getPrecision()); assertEquals(expectedScale, column.getScale()); }
/** * Return the column which is identified by column provided as argument. * * @param column column with atleast a name. * @return the underlying column or null if not inside this table. Note: the instance *can* be * different than the input parameter, but the name will be the same. */ public Column getColumn(Column column) { if (column == null) return null; Column myColumn = (Column) columns.get(column.getCanonicalName()); return column.equals(myColumn) ? myColumn : null; }
public void addColumn(Column column) { Column old = (Column) getColumn(column); if (old == null) { columns.put(column.getCanonicalName(), column); column.uniqueInteger = columns.size(); } else { column.uniqueInteger = old.uniqueInteger; } }
@SuppressWarnings("unchecked") public List<T> findByText2(String searchText, String sortColumn, boolean ascending) { List<Column> cols = HibernateUtil.getColumns(persistentClass.getName(), excludeDefault); String query = "select * from " + schemaName + "." + tableName + " where "; Iterator<Column> it = cols.iterator(); while (it.hasNext()) { Column col = it.next(); String colName = col.getName(); String propName = HibernateUtil.convertToHibernatePropertyName(colName); String type = HibernateUtil.getPropertyType(persistentClass, propName); String condition = null; if (type != null) { if (type.equals("integer") || type.equals("smallint")) { try { Integer.valueOf(searchText); condition = colName + "=" + searchText; } catch (NumberFormatException ex) { } } else if (type.equals("timestamp")) { try { Integer.valueOf(searchText); condition = "( YEAR(" + colName + ") = " + searchText + " OR " + " MONTH(" + colName + ") = " + searchText + " OR " + " DAY(" + colName + ") = " + searchText + ")"; } catch (NumberFormatException ex) { } } else if (type.equals("string") || type.equals("timestamp") || type.equals("date")) condition = colName + " ilike '%" + searchText + "%'"; if (condition != null) if (query.trim().endsWith("where")) query = query + condition; else query = query + " OR " + condition; } System.out.println("\n TYPE ZA KOLONU: " + colName + " JE: " + type + "\n"); } if (sortColumn != null && !sortColumn.equals("")) { if (ascending) query = query + " order by " + sortColumn + " asc"; else query = query + " order by " + sortColumn + " desc"; } System.out.println("\n\n\n FINAL QUERY = " + query + " \n\n\n"); return getSession().createSQLQuery(query).list(); }
private Property bindMeta(Property property, TableIdentifier identifier) { Iterator columnIterator = property.getValue().getColumnIterator(); while (columnIterator.hasNext()) { Column col = (Column) columnIterator.next(); Map map = revengStrategy.columnToMetaAttributes(identifier, col.getName()); if (map != null) { // TODO: merge from each column ? property.setMetaAttributes(map); } } return property; }
@SuppressWarnings("unchecked") public List<T> findByText(String searchText, String sortProp, boolean ascending) { List<Column> cols = HibernateUtil.getColumns(persistentClass.getName(), excludeDefault); Iterator<Column> it = cols.iterator(); Criteria crit = getSession().createCriteria(persistentClass); Disjunction disjunction = Restrictions.disjunction(); while (it.hasNext()) { Column col = it.next(); String colName = col.getName(); String propName = HibernateUtil.convertToHibernatePropertyName(colName); String type = HibernateUtil.getPropertyType(persistentClass, propName); if (type != null) { if (type.equals("integer") || type.equals("smallint")) { try { Integer.valueOf(searchText); Criterion criterium = Restrictions.eq(propName, Integer.valueOf(searchText)); disjunction.add(criterium); } catch (NumberFormatException ex) { } } else if (type.equals("string")) { Criterion criterium = Restrictions.ilike(propName, searchText, MatchMode.ANYWHERE); disjunction.add(criterium); } /*else if(type.equals("timestamp")){ Disjunction dis = Restrictions.disjunction(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); try { dis.add(Restrictions.eq(propName, format.parse(searchText))); } catch (ParseException e) { } try{ Integer.valueOf(searchText); dis.add(Restrictions.sqlRestriction( "YEAR(DATE("+colName+"))="+searchText+ " OR " + "MONTH(DATE("+colName+"))="+searchText+ " OR " + "DAY(DATE("+colName+"))="+searchText)); } catch(NumberFormatException ex) { } disjunction.add(dis); }*/ } } crit.add(disjunction); if (sortProp != null && !sortProp.equals("")) { if (ascending) crit.addOrder(Order.asc(sortProp)); else crit.addOrder(Order.desc(sortProp)); } return crit.list(); }
private void buildColumnAnnotation( Selectable selectable, StringBuffer annotations, boolean insertable, boolean updatable) { if (selectable.isFormula()) { annotations .append("@") .append(importType("org.hibernate.annotations.Formula")) .append("(value=\"") .append(selectable.getText()) .append("\")"); } else { Column column = (Column) selectable; annotations .append("@" + importType("javax.persistence.Column") + "(name=\"") .append(column.getName()) .append("\""); appendCommonColumnInfo(annotations, column, insertable, updatable); if (column.getPrecision() != Column.DEFAULT_PRECISION) { // the default is actually 0 in spec annotations.append(", precision=").append(column.getPrecision()); } if (column.getScale() != Column.DEFAULT_SCALE) { // default is actually 0 in spec annotations.append(", scale=").append(column.getScale()); } else if (column.getLength() != 255) { annotations.append(", length=").append(column.getLength()); } // TODO support secondary table annotations.append(")"); } }
/** * 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()); } }
/** 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); }
public static boolean isColumnPresent(String tableName, String columnName, Configuration cfg) { final Iterator<Table> tables = (Iterator<Table>) cfg.getTableMappings(); while (tables.hasNext()) { Table table = tables.next(); if (tableName.equals(table.getName())) { Iterator<Column> columns = (Iterator<Column>) table.getColumnIterator(); while (columns.hasNext()) { Column column = columns.next(); if (columnName.equals(column.getName())) { return true; } } } } return false; }
public void testDefaultNamingStrategy() { GroovyClassLoader cl = new GroovyClassLoader(); GrailsDomainClass oneClass = new DefaultGrailsDomainClass( cl.parseClass( "class TestOneSide {\n" + " Long id \n" + " Long version \n" + " String fooName \n" + " String barDescriPtion \n" + "}")); GrailsDomainClass domainClass = new DefaultGrailsDomainClass( cl.parseClass( "class TestManySide {\n" + " Long id \n" + " Long version \n" + " TestOneSide testOneSide \n" + "\n" + " static mapping = {\n" + " columns {\n" + " testOneSide column:'EXPECTED_COLUMN_NAME'" + " }\n" + " }\n" + "}")); DefaultGrailsDomainConfiguration config = getDomainConfig(cl, new Class[] {oneClass.getClazz(), domainClass.getClazz()}); PersistentClass persistentClass = config.getClassMapping("TestOneSide"); assertEquals("test_one_side", persistentClass.getTable().getName()); Column column = (Column) persistentClass.getProperty("id").getColumnIterator().next(); assertEquals("id", column.getName()); column = (Column) persistentClass.getProperty("version").getColumnIterator().next(); assertEquals("version", column.getName()); column = (Column) persistentClass.getProperty("fooName").getColumnIterator().next(); assertEquals("foo_name", column.getName()); column = (Column) persistentClass.getProperty("barDescriPtion").getColumnIterator().next(); assertEquals("bar_descri_ption", column.getName()); persistentClass = config.getClassMapping("TestManySide"); assertEquals("test_many_side", persistentClass.getTable().getName()); column = (Column) persistentClass.getProperty("id").getColumnIterator().next(); assertEquals("id", column.getName()); column = (Column) persistentClass.getProperty("version").getColumnIterator().next(); assertEquals("version", column.getName()); column = (Column) persistentClass.getProperty("testOneSide").getColumnIterator().next(); assertEquals("EXPECTED_COLUMN_NAME", column.getName()); }
private List columnMatches(Column[] myPkColumns, int offset, ForeignKey key) { if (key.getColumnSpan() > (myPkColumns.length - offset)) { return null; // not enough columns in the key } List columns = new ArrayList(); for (int j = 0; j < key.getColumnSpan(); j++) { Column column = myPkColumns[j + offset]; if (!column.equals(key.getColumn(j))) { return null; } else { columns.add(column); } } return columns.isEmpty() ? null : columns; }
public void validateColumns(Dialect dialect, Mapping mapping, TableMetadata tableInfo) { Iterator iter = getColumnIterator(); while (iter.hasNext()) { Column col = (Column) iter.next(); ColumnMetadata columnInfo = tableInfo.getColumnMetadata(col.getName()); if (columnInfo == null) { throw new HibernateException( "Missing column: " + col.getName() + " in " + Table.qualify( tableInfo.getCatalog(), tableInfo.getSchema(), tableInfo.getName())); } else { final boolean typesMatch = col.getSqlType(dialect, mapping) .toLowerCase(Locale.ROOT) .startsWith(columnInfo.getTypeName().toLowerCase(Locale.ROOT)) || columnInfo.getTypeCode() == col.getSqlTypeCode(mapping); if (!typesMatch) { throw new HibernateException( "Wrong column type in " + Table.qualify( tableInfo.getCatalog(), tableInfo.getSchema(), tableInfo.getName()) + " for column " + col.getName() + ". Found: " + columnInfo.getTypeName().toLowerCase(Locale.ROOT) + ", expected: " + col.getSqlType(dialect, mapping)); } } } }
public void testScaleProperty() { DefaultGrailsDomainConfiguration config = getDomainConfig( "class Widget {\n" + " Long id \n" + " Long version \n" + " Float width \n" + " Float height \n" + " static mapping = {\n" + " width scale: 7\n" + " }\n" + "}"); Table tableMapping = getTableMapping("widget", config); Column heightColumn = tableMapping.getColumn(new Column("height")); Column widthColumn = tableMapping.getColumn(new Column("width")); assertEquals(7, widthColumn.getScale()); assertEquals(Column.DEFAULT_SCALE, heightColumn.getScale()); }
public void testPrecisionProperty() { DefaultGrailsDomainConfiguration config = getDomainConfig( "class Widget {\n" + " Long id \n" + " Long version \n" + " Float width \n" + " Float height \n" + " static mapping = {\n" + " width precision: 3\n" + " }\n" + "}"); Table tableMapping = getTableMapping("widget", config); Column heightColumn = tableMapping.getColumn(new Column("height")); Column widthColumn = tableMapping.getColumn(new Column("width")); assertEquals(3, widthColumn.getPrecision()); assertEquals(Column.DEFAULT_PRECISION, heightColumn.getPrecision()); }
public void testUniqueProperty() { DefaultGrailsDomainConfiguration config = getDomainConfig( "class Widget {\n" + " Long id \n" + " Long version \n" + " String name \n" + " String description \n" + " static mapping = {\n" + " name unique: true\n" + " }\n" + "}"); Table tableMapping = getTableMapping("widget", config); Column nameColumn = tableMapping.getColumn(new Column("name")); Column descriptionColumn = tableMapping.getColumn(new Column("description")); assertEquals(true, nameColumn.isUnique()); assertEquals(false, descriptionColumn.isUnique()); }
public void testLengthProperty() { DefaultGrailsDomainConfiguration config = getDomainConfig( "class Widget {\n" + " Long id \n" + " Long version \n" + " String name \n" + " String description \n" + " static mapping = {\n" + " name column: 's_name', sqlType: 'text', length: 42\n" + " description column: 's_description', sqlType: 'text'\n" + " }\n" + "}"); Table tableMapping = getTableMapping("widget", config); Column nameColumn = tableMapping.getColumn(new Column("s_name")); Column descriptionColumn = tableMapping.getColumn(new Column("s_description")); assertEquals(42, nameColumn.getLength()); assertEquals(Column.DEFAULT_LENGTH, descriptionColumn.getLength()); }
/** * @param table * @param rc * @param primaryKey */ private void bindColumnsToProperties( Table table, RootClass rc, Set processedColumns, Mapping mapping) { for (Iterator iterator = table.getColumnIterator(); iterator.hasNext(); ) { Column column = (Column) iterator.next(); if (!processedColumns.contains(column)) { checkColumn(column); String propertyName = revengStrategy.columnToPropertyName(TableIdentifier.create(table), column.getName()); Property property = bindBasicProperty( makeUnique(rc, propertyName), table, column, processedColumns, mapping); rc.addProperty(property); } } }
/** Test for GRAILS-4200 */ public void testEmbeddedComponentMapping() { DefaultGrailsDomainConfiguration config = getDomainConfig( "class Widget {\n" + " Long id \n" + " Long version \n" + " EmbeddedWidget ew \n" + " static embedded = ['ew']\n" + "}\n" + " class EmbeddedWidget {\n" + " String ew\n" + " static mapping = {\n" + " ew column: 'widget_name'\n" + " }\n" + " }"); Table tableMapping = getTableMapping("widget", config); Column embeddedComponentMappedColumn = tableMapping.getColumn(new Column("widget_name")); assertNotNull(embeddedComponentMappedColumn); assertEquals("widget_name", embeddedComponentMappedColumn.getName()); }
private void bindVersionProperty( Table table, TableIdentifier identifier, Column column, RootClass rc, Set processed, Mapping mapping) { processed.add(column); String propertyName = revengStrategy.columnToPropertyName(identifier, column.getName()); Property property = bindBasicProperty(makeUnique(rc, propertyName), table, column, processed, mapping); rc.addProperty(property); rc.setVersion(property); rc.setOptimisticLockMode(Versioning.OPTIMISTIC_LOCK_VERSION); log.debug( "Column " + column.getName() + " will be used for <version>/<timestamp> columns in " + identifier); }
@SuppressWarnings({"unchecked"}) @Test public void testJoinColumnName() { Iterator<Column> columns = getCfg().getClassMapping(MIDDLE_VERSIONS_ENTITY_NAME).getTable().getColumnIterator(); boolean id1Found = false; boolean id2Found = false; while (columns.hasNext()) { Column column = columns.next(); if ("ID_1".equals(column.getName())) { id1Found = true; } if ("ID_2".equals(column.getName())) { id2Found = true; } } assert id1Found && id2Found; }
protected void appendCommonColumnInfo( StringBuffer annotations, Column column, boolean insertable, boolean updatable) { if (column.isUnique()) { annotations.append(", unique=").append(column.isUnique()); } if (!column.isNullable()) { annotations.append(", nullable=").append(column.isNullable()); } if (!insertable) { annotations.append(", insertable=").append(insertable); } if (!updatable) { annotations.append(", updatable=").append(updatable); } String sqlType = column.getSqlType(); if (StringHelper.isNotEmpty(sqlType)) { annotations.append(", columnDefinition=\"").append(sqlType).append("\""); } }
public void /*test*/ AddNewProperty() { System.out.println("******************* testAddNewProperty ********************"); PersistentClass userMapping = HibernateUtil.getClassMapping(User.class); Column column = new Column(); column.setName("MOTTO"); column.setNullable(false); column.setUnique(true); column.setSqlType("VARCHAR"); userMapping.getTable().addColumn(column); SimpleValue value = new SimpleValue(); value.setTable(userMapping.getTable()); value.addColumn(column); value.setTypeName("string"); Property prop = new Property(); prop.setValue(value); prop.setName("motto"); prop.setPropertyAccessorName("field"); prop.setNodeName(prop.getName()); userMapping.addProperty(prop); HibernateUtil.rebuildSessionFactory(); ClassMetadata metadata = HibernateUtil.getClassMetadata(User.class); String[] propNames = metadata.getPropertyNames(); boolean mottoFound = false; for (int i = 0; i < propNames.length; i++) { String propName = propNames[i]; if (propName.equalsIgnoreCase("motto")) { mottoFound = true; break; } } assertTrue(mottoFound); }
/** * calculated the max length of an attribute of type String * * @param c Cluster that holds the attribute * @param attributeName name of the attribute * @return max allowed length of the attribute */ public int getLenthOfStringAttribute(ICluster c, String attributeName) { Assert.notNull(c, "c may not be null"); Assert.notNull(attributeName, "attributeName may not be null"); PersistentClass pc = cfg.getClassMapping(c.getDaoClass().getName()); if (pc == null) throw new ConfigurationException( "Persistent Dao Class from Cluster " + c.getClass().getName() + " is not Hibernate configured"); Property p = pc.getProperty(attributeName); if (p == null) throw new ConfigurationException( "Property " + attributeName + " in cluster " + c.getClass().getName() + " not found"); Iterator<Column> i = (Iterator<Column>) p.getValue().getColumnIterator(); Column column = i.next(); return column.getLength(); }