Skip to main content
summaryrefslogtreecommitdiffstats
blob: 3bd647425178b8d6df4c9b7f669cda743161e023 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
/**
 * <copyright>
 *
 * Copyright (c) 2005, 2006, 2007 Springsite BV (The Netherlands) and others
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Martin Taal
 *   Davide Marchignoli
 * </copyright>
 *
 * $Id: AbstractMapper.java,v 1.10 2007/02/05 15:35:35 mtaal Exp $
 */

package org.eclipse.emf.teneo.hibernate.mapper;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.teneo.annotations.pamodel.PAnnotatedEAttribute;
import org.eclipse.emf.teneo.annotations.pamodel.PAnnotatedEReference;
import org.eclipse.emf.teneo.annotations.pannotation.Column;
import org.eclipse.emf.teneo.annotations.pannotation.PannotationFactory;
import org.eclipse.emf.teneo.ecore.EClassNameStrategy;
import org.eclipse.emf.teneo.hibernate.hbannotation.Cache;
import org.eclipse.emf.teneo.hibernate.hbannotation.Parameter;
import org.eclipse.emf.teneo.hibernate.hbmodel.HbAnnotatedEAttribute;
import org.eclipse.emf.teneo.hibernate.hbmodel.HbAnnotatedEDataType;
import org.eclipse.emf.teneo.simpledom.Element;
import org.eclipse.emf.teneo.util.EcoreDataTypes;

/**
 * Base class for all mapping classes. Provides access to the hbmcontext.
 * 
 * @author <a href="mailto:marchign at elver.org">Davide Marchignoli</a>
 * @author <a href="mailto:mtaal at elver.org">Martin Taal</a>
 */
abstract class AbstractMapper {

	/** logs it all */
	// private static final Log log = LogFactory.getLog(AbstractMapper.class);
	/** return the opposite of an association */
	protected PAnnotatedEReference getOtherSide(PAnnotatedEReference paReference) {
		// TODO assuming that mappedBy coincide with opposite, check in validation
		if (paReference.getAnnotatedEReference().getEOpposite() == null) {
			return null;
		}
		return paReference.getPaModel().getPAnnotated(paReference.getAnnotatedEReference().getEOpposite());
	}

	/** The mapping context of this mapping action */
	protected final MappingContext hbmContext;

	/** Constructor */
	public AbstractMapper(final MappingContext hbmContext) {
		this.hbmContext = hbmContext;
	}

	/**
	 * @return The mapping context used by this mapper
	 */
	protected MappingContext getHbmContext() {
		return hbmContext;
	}

	/** Handles the type or typedef annotations */
	protected void setType(PAnnotatedEAttribute paAttribute, Element propElement) {

		// handle the type annotation
		final HbAnnotatedEAttribute hea = (HbAnnotatedEAttribute) paAttribute;
		final EDataType ed = (EDataType) hea.getAnnotatedEAttribute().getEType();
		final HbAnnotatedEDataType hed = (HbAnnotatedEDataType) hea.getPaModel().getPAnnotated(ed);

		final String name;
		final List params;
		if (hea.getHbType() != null) {
			name = hea.getHbType().getType();
			params = hea.getHbType().getParameters();
		} else if (hed != null && hed.getHbTypeDef() != null) {
			name = hed.getHbTypeDef().getName();
			params = null;
		} else {
			name = null;
			params = null;
		}
		if (name != null) {
			if (params == null || params.isEmpty()) {
				// simple
				propElement.addAttribute("type", name);
			} else {
				final Element typeElement = propElement.addElement("type").addAttribute("name", name);
				for (Iterator it = params.iterator(); it.hasNext();) {
					final Parameter param = (Parameter) it.next();
					typeElement.addElement("param").addAttribute("name", param.getName()).addText(param.getValue());
				}
			}
		} else {
			final String hType = hbType(paAttribute);
			if (hType != null) {
				propElement.addAttribute("type", hType);
			} else {
				final Element typeElement = propElement.addElement("type").addAttribute("name",
						hbmContext.getDefaultUserType());
				typeElement.addElement("param").addAttribute("name", HbMapperConstants.EDATATYPE_PARAM).addText(
						paAttribute.getAnnotatedEAttribute().getEAttributeType().getName());
				typeElement.addElement("param").addAttribute("name", HbMapperConstants.EPACKAGE_PARAM).addText(
						paAttribute.getAnnotatedEAttribute().getEType().getEPackage().getNsURI());
			}
		}
	}

	/**
	 * @return Returns the hibernate name for the given Ecore data type.
	 * @throws MappingException
	 *             if no corresponding hb type is defined.
	 */
	private String hbType(PAnnotatedEAttribute paAttribute) {
		final EAttribute eAttribute = paAttribute.getAnnotatedEAttribute();
		final HbAnnotatedEDataType hed = (HbAnnotatedEDataType) paAttribute.getPaModel().getPAnnotated(
				eAttribute.getEAttributeType());
		final EDataType eDataType = paAttribute.getAnnotatedEAttribute().getEAttributeType();
		if (hed != null && hed.getHbTypeDef() != null) {
			return hed.getHbTypeDef().getName();
		} else if (paAttribute.getLob() != null) {
			if (EcoreDataTypes.isByteArray(eDataType)) {
				return "binary";
			} else if (EcoreDataTypes.INSTANCE.isEString(eDataType)) {
				return "text";
			} else {
				throw new MappingException("Lob annotations can only be used with Strings or byte arrays. "
						+ "Attribute is of type: " + eDataType);
			}
		} else if (EcoreDataTypes.INSTANCE.isEWrapper(eDataType) || EcoreDataTypes.INSTANCE.isEPrimitive(eDataType)) {
			return eDataType.getInstanceClassName();
		} else if (EcoreDataTypes.INSTANCE.isEString(eDataType)) {
			return eDataType.getInstanceClassName();
		} else if (EcoreDataTypes.INSTANCE.isEDate(eDataType)) {
			return "java.util.Date";
		} else if (eDataType.getInstanceClass() != null && eDataType.getInstanceClass() == Object.class) {
			// null forces caller to use usertype
			return null; // "org.eclipse.emf.teneo.hibernate.mapping.DefaultToStringUserType";
		} else if (eDataType.getInstanceClass() != null) {
			return eDataType.getInstanceClassName();
		} else {
			// all edatatypes are translatable to a string, done by caller
			return null; // "org.eclipse.emf.teneo.hibernate.mapping.DefaultToStringUserType";
		}
	}

	/**
	 * Returns the (possibly overridden) JoinColumns annotations for the given reference or an empty list if no
	 * JoinColumns were defined.
	 */
	protected List getJoinColumns(PAnnotatedEReference paReference) {
		List joinColumns = getHbmContext().getOverride(paReference);
		if (joinColumns == null) {
			return paReference.getJoinColumns();
		}
		return joinColumns;
	}

	/** Adds a cache element */
	protected void addCacheElement(Element parent, Cache cache) {
		// translate to hibernate specific notation
		final String usage = cache.getUsage().getName().toLowerCase().replaceAll("_", "-");

		// note a trick because the name of the
		Element cacheElement = parent.addElement("cache").addAttribute("usage", usage);
		if (cache.getRegion() != null) {
			cacheElement.addAttribute("region", cache.getRegion());
		}
		if (cache.getInclude() != null) {
			cacheElement.addAttribute("include", cache.getInclude());
		}
		parent.remove(cacheElement);
		parent.add(0, cacheElement);
	}

	/** Same as above only handles multiple columns */
	protected void addColumns(Element propertyElement, String defaultName, List columns, boolean isNullable,
			boolean setColumnAttributesInProperty) {
		// if no columns set then use some default
		if (columns.isEmpty()) {
			final String name;
			if (getHbmContext().getEmbeddingFeature() != null) { // embedded
				// TODO: check illegal, embedded component can not really have an id
				final PAnnotatedEReference pae = getHbmContext().getEmbeddingFeature();
				name = getHbmContext().trunc(pae.getAnnotatedEReference().getName() + "_" + defaultName);
			} else {
				name = getHbmContext().trunc(defaultName);
			}
			final Column col = PannotationFactory.eINSTANCE.createColumn();
			col.setName(hbmContext.trunc(name));
			col.setNullable(isNullable);
			columns.add(col);
		}
		for (Iterator it = columns.iterator(); it.hasNext();) {
			final Column column = (Column) it.next();
			addColumn(propertyElement, defaultName, column, isNullable, setColumnAttributesInProperty);
		}
	}

	/** Adds anytype columns */
	protected List getAnyTypeColumns(String featureName, boolean isNullable) {
		final ArrayList result = new ArrayList();
		final Column typeColumn = PannotationFactory.eINSTANCE.createColumn();
		typeColumn.setName(hbmContext.trunc(featureName + "_type"));
		typeColumn.setNullable(isNullable);
		result.add(typeColumn);
		final Column idColumn = PannotationFactory.eINSTANCE.createColumn();
		idColumn.setName(hbmContext.trunc(featureName + "_id"));
		idColumn.setNullable(isNullable);
		result.add(idColumn);
		return result;
	}

	/**
	 * Returns the (possibly overridden) columns annotation for the given attribute.
	 */
	protected List getColumns(PAnnotatedEAttribute paAttribute) {
		final Column defaultColumn = paAttribute.getColumn();
		final Column oc = getHbmContext().getOverride(paAttribute);

		if (oc != null) {
			final ArrayList result = new ArrayList();
			result.add(oc);
			return result;
		}
		// try multiple columns
		final HbAnnotatedEAttribute hae = (HbAnnotatedEAttribute) paAttribute;
		if (hae.getHbColumns().size() > 0) {
			return hae.getHbColumns();
		}
		final ArrayList result = new ArrayList();
		if (defaultColumn != null) {
			result.add(defaultColumn);
		}
		return result;
	}

	/** Sets property attributes on the basis of the column */
	private void addColumn(Element propertyElement, String defaultName, Column column, boolean isNullable,
			boolean setColumnAttributesInProperty) {
		if (column != null) {
			if (setColumnAttributesInProperty) {
				// this is not the nicest place to do this
				if (propertyElement.getName().compareTo("property") == 0
						|| propertyElement.getName().compareTo("many-to-one") == 0) {
					propertyElement.addAttribute("insert", column.isInsertable() ? "true" : "false");
					propertyElement.addAttribute("update", column.isUpdatable() ? "true" : "false");
				}
				// MT: I think that the column nullability should not be used for setting not-null
				// on the property, this is already specified by the optional attribute on the
				// basic annotation. Maybe a check can be used instead to detect inconsistenties
				// in the column attributes and the basic ann.
				// Note that the ejb3 spec says that optional should be disregarded for primitive types which I
				// do not understand.
				// I disabled it for now to ignore for the test cases.
				// MT05032006: After some more thought the column nullability can be used in case of
				// single table inheritance mapping
				propertyElement.addAttribute("not-null", isNullable || column.isNullable() ? "false" : "true");
				propertyElement.addAttribute("unique", column.isUnique() ? "true" : "false");
			}
			addColumnElement(propertyElement, defaultName, column, isNullable);
		}
	}

	/**
	 * Add a columnelement to the property, takes into account length, precision etc. forceNullable is set when the
	 * feature belongs to a featuremap
	 */
	private void addColumnElement(Element propertyElement, String defaultName, Column column, boolean forceNullable) {
		if (column != null) {
			Element columnElement = propertyElement.addElement("column").addAttribute("not-null",
					column.isNullable() || forceNullable ? "false" : "true").addAttribute("unique",
					column.isUnique() ? "true" : "false");
			final String name;
			if (column.getName() != null) {
				name = column.getName();
			} else {
				name = defaultName;
			}
			columnElement.addAttribute("name", getHbmContext().trunc(name));
			if (column.isSetLength())
				columnElement.addAttribute("length", Integer.toString(column.getLength()));
			if (column.isSetPrecision())
				columnElement.addAttribute("precision", Integer.toString(column.getPrecision()));
			if (column.isSetScale())
				columnElement.addAttribute("scale", Integer.toString(column.getScale()));
			if (column.getColumnDefinition() != null) {
				columnElement.addAttribute("sql-type", column.getColumnDefinition());
			}
			final String uc = getHbmContext().getUniqueConstraintKey(name);
			if (uc != null) {
				columnElement.addAttribute("unique-key", uc);
			}
		}
	}

	/** Returns true if the target is the general EObject type */
	protected boolean isEObject(String typeName) {
		if (typeName == null) {
			return false;
		}
		return typeName.compareTo(EClassNameStrategy.EOBJECT_ECLASS_URI) == 0;
	}
}

Back to the top