use of org.apache.openejb.jee.jpa.GeneratedValue in project tomee by apache.
the class CmpJpaConversion method mapClass2x.
/**
* Generate the JPA mapping for a CMP 2.x bean. Since
* the field accessors are all defined as abstract methods
* and the fields will not be defined in the implementation
* class, we don't need to deal with mapped superclasses.
* All of the fields and concrete methods will be
* implemented by the generated subclass, so from
* a JPA standpoint, there are no mapped superclasses
* required.
*
* @param mapping The mapping information we're updating.
* @param bean The entity bean meta data
* @param classLoader The classloader for resolving class references and
* primary key classes.
*/
private Collection<MappedSuperclass> mapClass2x(final Mapping mapping, final EntityBean bean, final ClassLoader classLoader) {
final Set<String> allFields = new TreeSet<>();
// get an acculated set of the CMP fields.
for (final CmpField cmpField : bean.getCmpField()) {
allFields.add(cmpField.getFieldName());
}
Class<?> beanClass = null;
try {
beanClass = classLoader.loadClass(bean.getEjbClass());
} catch (final ClassNotFoundException e) {
// if it does fail, just return null from here
return null;
}
// build a map from the field name to the super class that contains that field.
// If this is a strictly CMP 2.x class, this is generally an empty map. However,
// we support some migration steps toward EJB3, so this can be defined completely
// or partially as a POJO with concrete fields and accessors. This allows us to
// locate and generate the mappings
final Map<String, MappedSuperclass> superclassByField = mapFields(beanClass, allFields);
for (final Method method : beanClass.getMethods()) {
if (!Modifier.isAbstract(method.getModifiers())) {
continue;
}
if (method.getParameterTypes().length != 0) {
continue;
}
if (method.getReturnType().equals(Void.TYPE)) {
continue;
}
// Skip relationships: anything of type EJBLocalObject or Collection
if (EJBLocalObject.class.isAssignableFrom(method.getReturnType())) {
continue;
}
if (Collection.class.isAssignableFrom(method.getReturnType())) {
continue;
}
if (Map.class.isAssignableFrom(method.getReturnType())) {
continue;
}
String name = method.getName();
if (name.startsWith("get")) {
name = name.substring("get".length(), name.length());
} else if (name.startsWith("is")) {
// boolean.
if (method.getReturnType() == Boolean.TYPE) {
name = name.substring("is".length(), name.length());
} else {
// not an acceptable "is" method.
continue;
}
} else {
continue;
}
// the property needs the first character lowercased. Generally,
// we'll have this field already in our list, but it might have been
// omitted from the meta data.
name = Strings.lcfirst(name);
if (!allFields.contains(name)) {
allFields.add(name);
bean.addCmpField(name);
}
}
//
// id: the primary key
//
final Set<String> primaryKeyFields = new HashSet<>();
if (bean.getPrimkeyField() != null) {
final String fieldName = bean.getPrimkeyField();
final MappedSuperclass superclass = superclassByField.get(fieldName);
// this need not be here...for CMP 2.x, these are generally autogenerated fields.
if (superclass != null) {
// ok, add this field to the superclass mapping
superclass.addField(new Id(fieldName));
// the direct mapping is an over ride
mapping.addField(new AttributeOverride(fieldName));
} else {
// this is a normal generated field, it will be in the main class mapping.
mapping.addField(new Id(fieldName));
}
primaryKeyFields.add(fieldName);
} else if ("java.lang.Object".equals(bean.getPrimKeyClass())) {
// the automatically generated keys use a special property name
// and will always be in the generated superclass.
final String fieldName = "OpenEJB_pk";
final Id field = new Id(fieldName);
field.setGeneratedValue(new GeneratedValue(GenerationType.AUTO));
mapping.addField(field);
primaryKeyFields.add(fieldName);
} else if (bean.getPrimKeyClass() != null) {
Class<?> pkClass = null;
try {
pkClass = classLoader.loadClass(bean.getPrimKeyClass());
MappedSuperclass idclass = null;
// to make sure everything maps correctly.
for (final Field pkField : pkClass.getFields()) {
final String pkFieldName = pkField.getName();
final int modifiers = pkField.getModifiers();
if (Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) && allFields.contains(pkFieldName)) {
// see if the bean field is concretely defined in one of the superclasses
final MappedSuperclass superclass = superclassByField.get(pkFieldName);
if (superclass != null) {
// ok, we have an override that needs to be specified at the main class level.
superclass.addField(new Id(pkFieldName));
mapping.addField(new AttributeOverride(pkFieldName));
idclass = resolveIdClass(idclass, superclass, beanClass);
} else {
// this field will be autogenerated
mapping.addField(new Id(pkFieldName));
}
primaryKeyFields.add(pkFieldName);
}
}
// if we've located an ID class, set it as such
if (idclass != null) {
idclass.setIdClass(new IdClass(bean.getPrimKeyClass()));
} else {
// do this for the toplevel mapping
mapping.setIdClass(new IdClass(bean.getPrimKeyClass()));
}
} catch (final ClassNotFoundException e) {
throw (IllegalStateException) new IllegalStateException("Could not find entity primary key class " + bean.getPrimKeyClass()).initCause(e);
}
}
//
for (final CmpField cmpField : bean.getCmpField()) {
// only add entries for cmp fields that are not part of the primary key
if (!primaryKeyFields.contains(cmpField.getFieldName())) {
final String fieldName = cmpField.getFieldName();
// this will be here if we've already processed this
final MappedSuperclass superclass = superclassByField.get(fieldName);
// we need to provide a mapping for this.
if (superclass != null) {
// we need to mark this as being in one of the superclasses
superclass.addField(new Basic(fieldName));
mapping.addField(new AttributeOverride(fieldName));
} else {
// directly generated.
mapping.addField(new Basic(fieldName));
}
}
}
// the field mappings
return new HashSet<>(superclassByField.values());
}
use of org.apache.openejb.jee.jpa.GeneratedValue in project tomee by apache.
the class SunCmpConversionTest method convert.
private EntityMappings convert(final String ejbJarFileName, final String sunEjbJarFileName, final String sunCmpMappingsFileName, final String expectedFileName) throws Exception {
InputStream in = getClass().getClassLoader().getResourceAsStream(ejbJarFileName);
final EjbJar ejbJar = (EjbJar) JaxbJavaee.unmarshalJavaee(EjbJar.class, new ByteArrayInputStream(readContent(in).getBytes()));
// create and configure the module
final EjbModule ejbModule = new EjbModule(getClass().getClassLoader(), "TestModule", null, ejbJar, new OpenejbJar());
final InitEjbDeployments initEjbDeployments = new InitEjbDeployments();
initEjbDeployments.deploy(ejbModule);
final AppModule appModule = new AppModule(getClass().getClassLoader(), "TestModule");
appModule.getEjbModules().add(ejbModule);
// add the altDD
ejbModule.getAltDDs().put("sun-cmp-mappings.xml", getClass().getClassLoader().getResource(sunCmpMappingsFileName));
ejbModule.getAltDDs().put("sun-ejb-jar.xml", getClass().getClassLoader().getResource(sunEjbJarFileName));
// convert the cmp declarations into jpa entity declarations
final CmpJpaConversion cmpJpaConversion = new CmpJpaConversion();
cmpJpaConversion.deploy(appModule);
// EntityMappings entityMappings = cmpJpaConversion.generateEntityMappings(ejbModule);
// // load the sun-cmp-mappings.xml file
// String sunCmpMappingsXml = readContent(getClass().getClassLoader().getResourceAsStream(sunCmpMappingsFileName));
// SunCmpMappings sunCmpMappings = (SunCmpMappings) JaxbSun.unmarshal(SunCmpMappings.class, new ByteArrayInputStream(sunCmpMappingsXml.getBytes()));
// fill in the jpa entity declarations with database mappings from the sun-cmp-mappings.xml file
final SunConversion sunConversion = new SunConversion();
// sunCmpConversion.mergeEntityMappings(ejbModule, entityMappings);
sunConversion.deploy(appModule);
// compare the results to the expected results
if (expectedFileName != null) {
in = getClass().getClassLoader().getResourceAsStream(expectedFileName);
final String expected = readContent(in);
// Sun doen't really support generated primary keys, so we need to add them by hand here
final Set<String> generatedPks = new HashSet<>(Arrays.asList("BasicCmp2", "AOBasicCmp2", "EncCmp2", "Cmp2RmiIiop"));
final EntityMappings cmpMappings = appModule.getCmpMappings();
for (final Entity entity : cmpMappings.getEntity()) {
if (generatedPks.contains(entity.getName())) {
entity.getAttributes().getId().get(0).setGeneratedValue(new GeneratedValue(GenerationType.IDENTITY));
}
}
final String actual = toString(cmpMappings);
XMLUnit.setIgnoreWhitespace(true);
try {
final Diff myDiff = new DetailedDiff(new Diff(expected, actual));
assertTrue("Files are not similar " + myDiff, myDiff.similar());
} catch (final AssertionFailedError e) {
assertEquals(expected, actual);
}
}
return appModule.getCmpMappings();
}
use of org.apache.openejb.jee.jpa.GeneratedValue in project tomee by apache.
the class CmpJpaConversion method mapClass1x.
/**
* Create the class mapping for a CMP 1.x entity bean.
* Since the fields for 1.x persistence are defined
* in the objects directly, we need to create superclass
* mappings for each of the defined fields to identify
* which classes implement each of the managed fields.
*
* @param ejbClassName The name of the class we're processing.
* @param mapping The mappings we're going to generate.
* @param bean The bean metadata for the ejb.
* @param classLoader The classloader used to load the bean class for
* inspection.
* @return The set of mapped superclasses used in this
* bean mapping.
*/
private Collection<MappedSuperclass> mapClass1x(final String ejbClassName, final Mapping mapping, final EntityBean bean, final ClassLoader classLoader) {
final Class ejbClass = loadClass(classLoader, ejbClassName);
// build a set of all field names
final Set<String> allFields = new TreeSet<>();
for (final CmpField cmpField : bean.getCmpField()) {
allFields.add(cmpField.getFieldName());
}
// build a map from the field name to the super class that contains that field
final Map<String, MappedSuperclass> superclassByField = mapFields(ejbClass, allFields);
//
// id: the primary key
//
final Set<String> primaryKeyFields = new HashSet<>();
if (bean.getPrimkeyField() != null) {
final String fieldName = bean.getPrimkeyField();
final MappedSuperclass superclass = superclassByField.get(fieldName);
if (superclass == null) {
throw new IllegalStateException("Primary key field " + fieldName + " is not defined in class " + ejbClassName + " or any super classes");
}
superclass.addField(new Id(fieldName));
mapping.addField(new AttributeOverride(fieldName));
primaryKeyFields.add(fieldName);
} else if ("java.lang.Object".equals(bean.getPrimKeyClass())) {
// a primary field type of Object is an automatically generated
// pk field. Mark it as such and add it to the mapping.
final String fieldName = "OpenEJB_pk";
final Id field = new Id(fieldName);
field.setGeneratedValue(new GeneratedValue(GenerationType.AUTO));
mapping.addField(field);
} else if (bean.getPrimKeyClass() != null) {
// we have a primary key class. We need to define the mappings between the key class fields
// and the bean's managed fields.
Class<?> pkClass = null;
try {
pkClass = classLoader.loadClass(bean.getPrimKeyClass());
MappedSuperclass superclass = null;
MappedSuperclass idclass = null;
for (final Field pkField : pkClass.getFields()) {
final String fieldName = pkField.getName();
final int modifiers = pkField.getModifiers();
// AND must also exist in the class hierarchy (not enforced by mapFields());
if (Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) && allFields.contains(fieldName)) {
superclass = superclassByField.get(fieldName);
if (superclass == null) {
throw new IllegalStateException("Primary key field " + fieldName + " is not defined in class " + ejbClassName + " or any super classes");
}
// these are defined ast ID fields because they are part of the primary key
superclass.addField(new Id(fieldName));
mapping.addField(new AttributeOverride(fieldName));
primaryKeyFields.add(fieldName);
idclass = resolveIdClass(idclass, superclass, ejbClass);
}
}
// if we've located an ID class, set it as such
if (idclass != null) {
idclass.setIdClass(new IdClass(bean.getPrimKeyClass()));
}
} catch (final ClassNotFoundException e) {
throw (IllegalStateException) new IllegalStateException("Could not find entity primary key class " + bean.getPrimKeyClass()).initCause(e);
}
}
//
for (final CmpField cmpField : bean.getCmpField()) {
final String fieldName = cmpField.getFieldName();
// all of the primary key fields have been processed, so only handle whatever is left over
if (!primaryKeyFields.contains(fieldName)) {
final MappedSuperclass superclass = superclassByField.get(fieldName);
if (superclass == null) {
throw new IllegalStateException("CMP field " + fieldName + " is not defined in class " + ejbClassName + " or any super classes");
}
superclass.addField(new Basic(fieldName));
mapping.addField(new AttributeOverride(fieldName));
}
}
// the field mappings
return new HashSet<>(superclassByField.values());
}
use of org.apache.openejb.jee.jpa.GeneratedValue in project tomee by apache.
the class OpenEjb2Conversion method mergeEntityMappings.
public final void mergeEntityMappings(final String moduleId, final EntityMappings entityMappings, final OpenejbJar openejbJar, final OpenejbJarType openejbJarType) {
final Map<String, EntityData> entities = new TreeMap<>();
if (entityMappings != null) {
for (final Entity entity : entityMappings.getEntity()) {
try {
entities.put(entity.getDescription(), new EntityData(entity));
} catch (final IllegalArgumentException e) {
LoggerFactory.getLogger(this.getClass()).error(e.getMessage(), e);
}
}
}
for (final org.apache.openejb.jee.oejb2.EnterpriseBean enterpriseBean : openejbJarType.getEnterpriseBeans()) {
if (!(enterpriseBean instanceof EntityBeanType)) {
continue;
}
final EntityBeanType bean = (EntityBeanType) enterpriseBean;
final EntityData entityData = entities.get(moduleId + "#" + bean.getEjbName());
if (entityData == null) {
// todo warn no such ejb in the ejb-jar.xml
continue;
}
final Table table = new Table();
table.setName(bean.getTableName());
entityData.entity.setTable(table);
for (final EntityBeanType.CmpFieldMapping cmpFieldMapping : bean.getCmpFieldMapping()) {
final String cmpFieldName = cmpFieldMapping.getCmpFieldName();
final Field field = entityData.fields.get(cmpFieldName);
if (field == null) {
// todo warn no such cmp-field in the ejb-jar.xml
continue;
}
final Column column = new Column();
column.setName(cmpFieldMapping.getTableColumn());
field.setColumn(column);
}
if (bean.getKeyGenerator() != null) {
// todo support complex primary keys
final Attributes attributes = entityData.entity.getAttributes();
if (attributes != null && attributes.getId().size() == 1) {
final Id id = attributes.getId().get(0);
// todo detect specific generation strategy
id.setGeneratedValue(new GeneratedValue(GenerationType.IDENTITY));
}
}
for (final QueryType query : bean.getQuery()) {
final NamedQuery namedQuery = new NamedQuery();
final QueryType.QueryMethod queryMethod = query.getQueryMethod();
// todo deployment id could change in one of the later conversions... use entity name instead, but we need to save it off
final StringBuilder name = new StringBuilder();
name.append(entityData.entity.getName()).append(".").append(queryMethod.getMethodName());
if (queryMethod.getMethodParams() != null && !queryMethod.getMethodParams().getMethodParam().isEmpty()) {
name.append('(');
boolean first = true;
for (final String methodParam : queryMethod.getMethodParams().getMethodParam()) {
if (!first) {
name.append(",");
}
name.append(methodParam);
first = false;
}
name.append(')');
}
namedQuery.setName(name.toString());
namedQuery.setQuery(query.getEjbQl());
entityData.entity.getNamedQuery().add(namedQuery);
}
}
for (final EjbRelationType relation : openejbJarType.getEjbRelation()) {
final List<EjbRelationshipRoleType> roles = relation.getEjbRelationshipRole();
if (roles.isEmpty()) {
continue;
}
if (relation.getManyToManyTableName() == null) {
final EjbRelationshipRoleType leftRole = roles.get(0);
final EjbRelationshipRoleType.RelationshipRoleSource leftRoleSource = leftRole.getRelationshipRoleSource();
final String leftEjbName = leftRoleSource == null ? null : leftRoleSource.getEjbName();
final EntityData leftEntityData = entities.get(moduleId + "#" + leftEjbName);
final EjbRelationshipRoleType.CmrField cmrField = leftRole.getCmrField();
final String leftFieldName = null != cmrField ? cmrField.getCmrFieldName() : null;
RelationField field;
if (leftRole.isForeignKeyColumnOnSource()) {
field = null != leftFieldName && null != leftEntityData ? leftEntityData.relations.get(leftFieldName) : null;
// todo warn field not found
if (field == null) {
continue;
}
} else {
final RelationField other = null != leftFieldName && null != leftEntityData ? leftEntityData.relations.get(leftFieldName) : null;
// todo warn field not found
if (other == null) {
continue;
}
field = other.getRelatedField();
// todo warn field not found
if (field == null) {
if (other instanceof OneToMany) {
// for a unidirectional oneToMany, the join column declaration
// is placed on the oneToMany element instead of manyToOne
field = other;
} else {
continue;
}
}
}
// is marked as the owning field
if (field instanceof OneToOne) {
final OneToOne left = (OneToOne) field;
final OneToOne right = (OneToOne) left.getRelatedField();
if (right != null) {
left.setMappedBy(null);
right.setMappedBy(left.getName());
}
}
final EjbRelationshipRoleType.RoleMapping roleMapping = leftRole.getRoleMapping();
for (final EjbRelationshipRoleType.RoleMapping.CmrFieldMapping cmrFieldMapping : roleMapping.getCmrFieldMapping()) {
final JoinColumn joinColumn = new JoinColumn();
joinColumn.setName(cmrFieldMapping.getForeignKeyColumn());
joinColumn.setReferencedColumnName(cmrFieldMapping.getKeyColumn());
field.getJoinColumn().add(joinColumn);
}
} else {
final JoinTable joinTable = new JoinTable();
joinTable.setName(relation.getManyToManyTableName());
//
// left
final EjbRelationshipRoleType leftRole = roles.get(0);
RelationField left = null;
if (leftRole.getRelationshipRoleSource() != null) {
final String leftEjbName = leftRole.getRelationshipRoleSource().getEjbName();
final EntityData leftEntityData = entities.get(moduleId + "#" + leftEjbName);
if (leftEntityData == null) {
// todo warn no such entity in ejb-jar.xml
continue;
}
final EjbRelationshipRoleType.CmrField lcf = leftRole.getCmrField();
left = (null != lcf ? leftEntityData.relations.get(lcf.getCmrFieldName()) : null);
}
if (left != null) {
left.setJoinTable(joinTable);
final EjbRelationshipRoleType.RoleMapping roleMapping = leftRole.getRoleMapping();
for (final EjbRelationshipRoleType.RoleMapping.CmrFieldMapping cmrFieldMapping : roleMapping.getCmrFieldMapping()) {
final JoinColumn joinColumn = new JoinColumn();
joinColumn.setName(cmrFieldMapping.getForeignKeyColumn());
joinColumn.setReferencedColumnName(cmrFieldMapping.getKeyColumn());
joinTable.getJoinColumn().add(joinColumn);
}
}
// right
if (roles.size() > 1) {
final EjbRelationshipRoleType rightRole = roles.get(1);
// if there wasn't a left cmr field, find the field for the right, so we can add the join table to it
if (left == null) {
final EjbRelationshipRoleType.CmrField rcf = rightRole.getCmrField();
if (rcf == null) {
// todo warn no cmr field declared for either role
continue;
} else if (rightRole.getRelationshipRoleSource() != null) {
final String rightEjbName = rightRole.getRelationshipRoleSource().getEjbName();
final EntityData rightEntityData = entities.get(moduleId + "#" + rightEjbName);
if (rightEntityData == null) {
// todo warn no such entity in ejb-jar.xml
continue;
}
final RelationField right = rightEntityData.relations.get(rcf.getCmrFieldName());
right.setJoinTable(joinTable);
}
}
final EjbRelationshipRoleType.RoleMapping roleMapping = rightRole.getRoleMapping();
for (final EjbRelationshipRoleType.RoleMapping.CmrFieldMapping cmrFieldMapping : roleMapping.getCmrFieldMapping()) {
final JoinColumn joinColumn = new JoinColumn();
joinColumn.setName(cmrFieldMapping.getForeignKeyColumn());
joinColumn.setReferencedColumnName(cmrFieldMapping.getKeyColumn());
joinTable.getInverseJoinColumn().add(joinColumn);
}
}
}
}
}
Aggregations