{
JavaSourceFacet java = project.getFacet(JavaSourceFacet.class);
try
{
JavaClass one = getJavaClass();
JavaClass many;
// Field type may end with .java
if (areTypesSame(fieldType, one.getCanonicalName()))
{
many = one;
}
else
{
many = findEntity(fieldType);
one.addImport(many.getQualifiedName());
}
if (one.hasField(fieldName))
{
throw new IllegalStateException("Entity [" + one.getCanonicalName() + "] already has a field named ["
+ fieldName + "]");
}
if (!Strings.isNullOrEmpty(inverseFieldName) && many.hasField(inverseFieldName))
{
throw new IllegalStateException("Entity [" + many.getCanonicalName() + "] already has a field named ["
+ inverseFieldName + "]");
}
one.addImport(Set.class);
one.addImport(HashSet.class);
Field<JavaClass> oneField = one.addField("private Set<" + many.getName() + "> " + fieldName + "= new HashSet<"
+ many.getName() + ">();");
Annotation<JavaClass> annotation = oneField.addAnnotation(OneToMany.class);
Refactory.createGetterAndSetter(one, oneField);
if (!Strings.isNullOrEmpty(inverseFieldName))
{
annotation.setStringValue("mappedBy", inverseFieldName);
annotation.setLiteralValue("cascade", "CascadeType.ALL");
annotation.getOrigin().addImport(CascadeType.class);
annotation.setLiteralValue("orphanRemoval", "true");
if (!many.getCanonicalName().equals(one.getCanonicalName()))
{
many.addImport(one);
}
Field<JavaClass> manyField = many.addField("private " + one.getName() + " " + inverseFieldName + ";");
manyField.addAnnotation(ManyToOne.class);
Refactory.createGetterAndSetter(many, manyField);
java.saveJavaSource(many);
}