@Option(name = "required", required = false, flagOnly = true, description = "Whether the association is required. Sets the optional attribute to false.") final boolean required,
@Option(name = "cascade",
required = false,
description = "Define the set of operations that are cascaded to the target.") final CascadeType[] cascadeTypes)
{
JavaSourceFacet java = project.getFacet(JavaSourceFacet.class);
try
{
JavaClass many = getJavaClass();
JavaClass one;
if (areTypesSame(fieldType, many.getCanonicalName()))
{
one = many;
}
else
{
one = findEntity(fieldType);
many.addImport(one);
}
if (many.hasField(fieldName))
{
throw new IllegalStateException("Entity [" + many.getCanonicalName() + "] already has a field named ["
+ fieldName + "]");
}
if (!Strings.isNullOrEmpty(inverseFieldName) && one.hasField(inverseFieldName))
{
throw new IllegalStateException("Entity [" + one.getCanonicalName() + "] already has a field named ["
+ inverseFieldName + "]");
}
Field<JavaClass> manyField = many.addField("private " + one.getName() + " " + fieldName + ";");
Annotation<JavaClass> manyAnnotation = manyField.addAnnotation(ManyToOne.class);
Refactory.createGetterAndSetter(many, manyField);
if (!Strings.isNullOrEmpty(inverseFieldName))
{
one.addImport(Set.class);
one.addImport(HashSet.class);
if (!one.getCanonicalName().equals(many.getCanonicalName()))
{
one.addImport(many.getQualifiedName());
}
Field<JavaClass> oneField = one.addField("private Set<" + many.getName() + "> " + inverseFieldName
+ "= new HashSet<"
+ many.getName() + ">();");
Annotation<JavaClass> oneAnnotation = oneField.addAnnotation(OneToMany.class).setStringValue("mappedBy",
fieldName);
oneAnnotation.setLiteralValue("cascade", "CascadeType.ALL");
oneAnnotation.getOrigin().addImport(CascadeType.class);
Refactory.createGetterAndSetter(one, oneField);
java.saveJavaSource(one);
}
if(fetchType != null)
{
manyAnnotation.setEnumValue("fetch", fetchType);
}
if (required)
{
// Set the optional attribute of @OneToOne/@ManyToOne only when false, since the default value is true
manyAnnotation.setLiteralValue("optional", "false");
}
if(cascadeTypes !=null && cascadeTypes.length > 0)
{
manyAnnotation.setEnumArrayValue("cascade", cascadeTypes);
}
java.saveJavaSource(many);
}
catch (FileNotFoundException e)
{
shell.println("Could not locate the @Entity requested. No update was made.");
}