PageRenderTime 36ms CodeModel.GetById 13ms app.highlight 20ms RepoModel.GetById 0ms app.codeStats 0ms

/jboss-as-7.1.1.Final/cmp/src/main/java/org/jboss/as/cmp/jdbc/metadata/JDBCRelationshipRoleMetaData.java

#
Java | 431 lines | 240 code | 66 blank | 125 comment | 47 complexity | 3953e3778d208b8833d47b0c962fbe2d MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0
  1/*
  2 * JBoss, Home of Professional Open Source.
  3 * Copyright 2008, Red Hat Middleware LLC, and individual contributors
  4 * as indicated by the @author tags. See the copyright.txt file in the
  5 * distribution for a full listing of individual contributors.
  6 *
  7 * This is free software; you can redistribute it and/or modify it
  8 * under the terms of the GNU Lesser General Public License as
  9 * published by the Free Software Foundation; either version 2.1 of
 10 * the License, or (at your option) any later version.
 11 *
 12 * This software is distributed in the hope that it will be useful,
 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 15 * Lesser General Public License for more details.
 16 *
 17 * You should have received a copy of the GNU Lesser General Public
 18 * License along with this software; if not, write to the Free
 19 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 20 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 21 */
 22package org.jboss.as.cmp.jdbc.metadata;
 23
 24import java.util.ArrayList;
 25import java.util.Collection;
 26import java.util.Collections;
 27import java.util.HashMap;
 28import java.util.List;
 29import java.util.Map;
 30import org.jboss.as.cmp.CmpMessages;
 31import static org.jboss.as.cmp.CmpMessages.MESSAGES;
 32import org.jboss.as.cmp.jdbc.metadata.parser.ParsedCmpField;
 33import org.jboss.as.cmp.jdbc.metadata.parser.ParsedRelationshipRole;
 34import org.jboss.metadata.ejb.spec.RelationRoleMetaData;
 35
 36/**
 37 * Immutable class which represents one ejb-relationship-role element found in
 38 * the ejb-jar.xml file's ejb-relation elements.
 39 *
 40 * @author <a href="mailto:dain@daingroup.com">Dain Sundstrom</a>
 41 * @author <a href="mailto:alex@jboss.org">Alexey Loubyansky</a>
 42 * @version $Revision: 81030 $
 43 */
 44public final class JDBCRelationshipRoleMetaData {
 45    /**
 46     * Relation to which this role belongs.
 47     */
 48    private final JDBCRelationMetaData relationMetaData;
 49
 50    /**
 51     * Role name
 52     */
 53    private final String relationshipRoleName;
 54
 55    /**
 56     * Should this role have a foreign key constraint?
 57     */
 58    private final boolean foreignKeyConstraint;
 59
 60    /**
 61     * Should the cascade-delete be batched.
 62     */
 63    private final boolean batchCascadeDelete;
 64
 65    private boolean genIndex;
 66
 67    /**
 68     * Type of the cmr field (i.e., collection or set)
 69     */
 70    private JDBCReadAheadMetaData readAhead;
 71
 72    /**
 73     * Is the multiplicity one? If not, multiplicity is many.
 74     */
 75    private final boolean multiplicityOne;
 76
 77    /**
 78     * Should this entity be deleted when related entity is deleted.
 79     */
 80    private final boolean cascadeDelete;
 81
 82    /**
 83     * The entity that has this role.
 84     */
 85    private final JDBCEntityMetaData entity;
 86
 87    /**
 88     * Name of the entity's cmr field for this role.
 89     */
 90    private final String cmrFieldName;
 91
 92    /**
 93     * true if this side is navigable
 94     */
 95    private final boolean navigable;
 96
 97    /**
 98     * Type of the cmr field (i.e., collection or set)
 99     */
100    private final String cmrFieldType;
101
102    /**
103     * The other role in this relationship.
104     */
105    private JDBCRelationshipRoleMetaData relatedRole;
106
107    /**
108     * The key fields used by this role by field name.
109     */
110    private Map<String, JDBCCMPFieldMetaData> keyFields = new HashMap<String, JDBCCMPFieldMetaData>();
111
112    public JDBCRelationshipRoleMetaData(final JDBCRelationMetaData relationMetaData, final JDBCApplicationMetaData application, final RelationRoleMetaData role) {
113        this.relationMetaData = relationMetaData;
114
115        relationshipRoleName = role.getEjbRelationshipRoleName();
116        multiplicityOne = role.isMultiplicityOne();
117        cascadeDelete = role.isCascadedDelete();
118        batchCascadeDelete = false;
119        foreignKeyConstraint = false;
120        readAhead = null;
121
122        String fieldName = role.getCmrField() != null ? role.getCmrField().getCmrFieldName() : null;
123        if (fieldName == null) {
124            cmrFieldName = generateNonNavigableCMRName(role);
125            navigable = false;
126        } else {
127            cmrFieldName = fieldName;
128            navigable = true;
129        }
130        cmrFieldType = role.getCmrField() != null ? role.getCmrField().getCmrFieldType() : null;
131        // get the entity for this role
132        entity = application.getBeanByEjbName(role.getRoleSource().getEjbName());
133        if (entity == null) {
134            throw MESSAGES.entityNotFoundForRelation(role.getRoleSource().getEjbName(), role.getRelation().getEjbRelationName());
135        }
136    }
137
138    public JDBCRelationshipRoleMetaData(JDBCRelationMetaData relationMetaData, JDBCApplicationMetaData application, JDBCRelationshipRoleMetaData defaultValues) {
139        this.relationMetaData = relationMetaData;
140        this.entity = application.getBeanByEjbName(defaultValues.getEntity().getName());
141
142        relationshipRoleName = defaultValues.getRelationshipRoleName();
143        multiplicityOne = defaultValues.isMultiplicityOne();
144        cascadeDelete = defaultValues.isCascadeDelete();
145
146        cmrFieldName = defaultValues.getCMRFieldName();
147        navigable = defaultValues.isNavigable();
148        cmrFieldType = defaultValues.getCMRFieldType();
149
150        foreignKeyConstraint = defaultValues.hasForeignKeyConstraint();
151        readAhead = entity.getReadAhead();
152
153        batchCascadeDelete = defaultValues.isBatchCascadeDelete();
154        if (batchCascadeDelete) {
155            if (!cascadeDelete)
156                throw MESSAGES.cascadeDeleteInJbossXmlButNoEjbJar(relationMetaData.getRelationName(), relationshipRoleName);
157
158            if (relationMetaData.isTableMappingStyle()) {
159                throw MESSAGES.batchCascadeDeleteOnlyForFkMapping(relationMetaData.getRelationName());
160            }
161        }
162    }
163
164    public JDBCRelationshipRoleMetaData(JDBCRelationMetaData relationMetaData, JDBCApplicationMetaData application, ParsedRelationshipRole parsedRelationshipRole, JDBCRelationshipRoleMetaData defaultValues) {
165        this.relationMetaData = relationMetaData;
166        this.entity = application.getBeanByEjbName(defaultValues.getEntity().getName());
167
168        relationshipRoleName = defaultValues.getRelationshipRoleName();
169        multiplicityOne = defaultValues.isMultiplicityOne();
170        cascadeDelete = defaultValues.isCascadeDelete();
171
172        cmrFieldName = defaultValues.getCMRFieldName();
173        navigable = defaultValues.isNavigable();
174        cmrFieldType = defaultValues.getCMRFieldType();
175
176        // foreign key constraint?  If not provided, keep default.
177        if (parsedRelationshipRole.getForeignKeyConstraint() != null) {
178            foreignKeyConstraint = parsedRelationshipRole.getForeignKeyConstraint();
179        } else {
180            foreignKeyConstraint = defaultValues.hasForeignKeyConstraint();
181        }
182
183        // read-ahead
184        if (parsedRelationshipRole.getReadAhead() != null) {
185            readAhead = new JDBCReadAheadMetaData(parsedRelationshipRole.getReadAhead(), entity.getReadAhead());
186        } else {
187            readAhead = entity.getReadAhead();
188        }
189        batchCascadeDelete = parsedRelationshipRole.getBatchCascadeDelete() != null && parsedRelationshipRole.getBatchCascadeDelete();
190        if (batchCascadeDelete) {
191            if (!cascadeDelete)
192                throw CmpMessages.MESSAGES.invalidCascadeDeleteForRelation(relationMetaData.getRelationName(), relationshipRoleName);
193
194            if (relationMetaData.isTableMappingStyle()) {
195                throw MESSAGES.batchCascadeDeleteOnlyForFkMapping(relationMetaData.getRelationName());
196            }
197        }
198    }
199
200    public void init(final JDBCRelationshipRoleMetaData relatedRole) {
201        this.relatedRole = relatedRole;
202        keyFields.putAll(loadKeyFields());
203    }
204
205    public void init(final JDBCRelationshipRoleMetaData relatedRole, final ParsedRelationshipRole parsedRole) {
206        this.relatedRole = relatedRole;
207        keyFields.putAll(loadKeyFields(parsedRole));
208    }
209
210
211    /**
212     * Gets the relation to which this role belongs.
213     */
214    public JDBCRelationMetaData getRelationMetaData() {
215        return relationMetaData;
216    }
217
218    /**
219     * Gets the name of this role.
220     */
221    public String getRelationshipRoleName() {
222        return relationshipRoleName;
223    }
224
225    /**
226     * Should this role use a foreign key constraint.
227     *
228     * @return true if the store manager will execute an ALTER TABLE ADD
229     *         CONSTRAINT statement to add a foreign key constraint.
230     */
231    public boolean hasForeignKeyConstraint() {
232        return foreignKeyConstraint;
233    }
234
235    public boolean isBatchCascadeDelete() {
236        return batchCascadeDelete;
237    }
238
239    /**
240     * Gets the read ahead meta data
241     */
242    public JDBCReadAheadMetaData getReadAhead() {
243        return readAhead;
244    }
245
246    public JDBCEntityMetaData getEntity() {
247        return entity;
248    }
249
250    /**
251     * Gets the key fields of this role.
252     *
253     * @return an unmodifiable collection of JDBCCMPFieldMetaData objects
254     */
255    public Collection<JDBCCMPFieldMetaData> getKeyFields() {
256        return Collections.unmodifiableCollection(keyFields.values());
257    }
258
259    public boolean isIndexed() {
260        return genIndex;
261    }
262
263    private static String generateNonNavigableCMRName(final RelationRoleMetaData role) {
264        RelationRoleMetaData relatedRole = role.getRelatedRole();
265        return relatedRole.getRoleSource().getEjbName() + "_" + relatedRole.getCmrField().getCmrFieldName();
266    }
267
268    /**
269     * Checks if the multiplicity is one.
270     */
271    public boolean isMultiplicityOne() {
272        return multiplicityOne;
273    }
274
275    /**
276     * Checks if the multiplicity is many.
277     */
278    public boolean isMultiplicityMany() {
279        return !multiplicityOne;
280    }
281
282    /**
283     * Should this entity be deleted when related entity is deleted.
284     */
285    public boolean isCascadeDelete() {
286        return cascadeDelete;
287    }
288
289    /**
290     * Gets the name of the entity's cmr field for this role.
291     */
292    public String getCMRFieldName() {
293        return cmrFieldName;
294    }
295
296    public boolean isNavigable() {
297        return navigable;
298    }
299
300    /**
301     * Gets the type of the cmr field (i.e., collection or set)
302     */
303    public String getCMRFieldType() {
304        return cmrFieldType;
305    }
306
307    /**
308     * Gets the related role's jdbc meta data.
309     */
310    public JDBCRelationshipRoleMetaData getRelatedRole() {
311        return relationMetaData.getOtherRelationshipRole(this);
312    }
313
314    /**
315     * Loads the key fields for this role based on the primary keys of the
316     * this entity.
317     */
318    private Map<String, JDBCCMPFieldMetaData> loadKeyFields() {
319        // with foreign key mapping, foreign key fields are no added if
320        // - it is the many side of one-to-many relationship
321        // - it is the one side of one-to-one relationship and related side is not navigable
322        if (relationMetaData.isForeignKeyMappingStyle()) {
323            if (isMultiplicityMany())
324                return Collections.emptyMap();
325            else if (getRelatedRole().isMultiplicityOne() && !getRelatedRole().isNavigable())
326                return Collections.emptyMap();
327        }
328
329        // get all of the pk fields
330        List<JDBCCMPFieldMetaData> pkFields = new ArrayList<JDBCCMPFieldMetaData>();
331        for (JDBCCMPFieldMetaData cmpField : entity.getCMPFields()) {
332            if (cmpField.isPrimaryKeyMember()) {
333                pkFields.add(cmpField);
334            }
335        }
336
337        // generate a new key field for each pk field
338        Map<String, JDBCCMPFieldMetaData> fields = new HashMap<String, JDBCCMPFieldMetaData>(pkFields.size());
339        for (JDBCCMPFieldMetaData cmpField : pkFields) {
340            String columnName;
341            if (relationMetaData.isTableMappingStyle()) {
342                if (entity.equals(relatedRole.getEntity()))
343                    columnName = getCMRFieldName();
344                else
345                    columnName = entity.getName();
346            } else {
347                columnName = relatedRole.getCMRFieldName();
348            }
349
350            if (pkFields.size() > 1) {
351                columnName += "_" + cmpField.getFieldName();
352            }
353
354            genIndex = (genIndex) || cmpField.isIndexed();
355
356            cmpField = new JDBCCMPFieldMetaData(
357                    entity,
358                    cmpField,
359                    columnName,
360                    false,
361                    relationMetaData.isTableMappingStyle(),
362                    relationMetaData.isReadOnly(),
363                    relationMetaData.getReadTimeOut(),
364                    relationMetaData.isTableMappingStyle());
365            fields.put(cmpField.getFieldName(), cmpField);
366        }
367        return Collections.unmodifiableMap(fields);
368    }
369
370    private Map<String, JDBCCMPFieldMetaData> loadKeyFields(final ParsedRelationshipRole parsedRole) {
371
372        // no field overrides, we're done
373        final List<ParsedCmpField> keyFields = parsedRole.getKeyFields();
374        if (keyFields == null) {
375            return loadKeyFields();
376        }
377
378        if(keyFields.isEmpty()) {
379            return Collections.EMPTY_MAP;
380        }
381
382        if (relationMetaData.isForeignKeyMappingStyle() && isMultiplicityMany()) {
383            throw CmpMessages.MESSAGES.relationshipRoleCanNotHaveKeyFields(relationshipRoleName);
384        }
385
386        // load the default field values
387        Map<String, JDBCCMPFieldMetaData> defaultFields = getPrimaryKeyFields();
388
389        // load overrides
390        Map<String, JDBCCMPFieldMetaData> fields = new HashMap<String, JDBCCMPFieldMetaData>(defaultFields.size());
391        for (ParsedCmpField keyField : keyFields) {
392            String fieldName = keyField.getFieldName();
393
394            JDBCCMPFieldMetaData cmpField = defaultFields.remove(fieldName);
395            if (cmpField == null) {
396                throw MESSAGES.cmpFieldNotFoundForRole(relationshipRoleName, entity.getName(), fieldName);
397            }
398            genIndex = keyField.getGenIndex() != null && keyField.getGenIndex();
399
400
401            cmpField = new JDBCCMPFieldMetaData(
402                    entity,
403                    keyField,
404                    cmpField,
405                    false,
406                    relationMetaData.isTableMappingStyle(),
407                    relationMetaData.isReadOnly(),
408                    relationMetaData.getReadTimeOut(),
409                    relationMetaData.isTableMappingStyle());
410            fields.put(cmpField.getFieldName(), cmpField);
411        }
412
413        // all fields must be overridden
414        if (!defaultFields.isEmpty()) {
415            throw MESSAGES.mappingsNotProvidedForAllFieldsForRole(defaultFields.keySet(), relationshipRoleName);
416        }
417        return Collections.unmodifiableMap(fields);
418    }
419
420    /**
421     * Returns the primary key fields of the entity mapped by field name.
422     */
423    private Map<String, JDBCCMPFieldMetaData> getPrimaryKeyFields() {
424        Map<String, JDBCCMPFieldMetaData> pkFields = new HashMap<String, JDBCCMPFieldMetaData>();
425        for (JDBCCMPFieldMetaData cmpField : entity.getCMPFields()) {
426            if (cmpField.isPrimaryKeyMember())
427                pkFields.put(cmpField.getFieldName(), cmpField);
428        }
429        return pkFields;
430    }
431}