JavaSourceFacet java = project.getFacet(JavaSourceFacet.class);
try
{
JavaClass entity = getJavaClass();
JavaClass otherEntity;
if (areTypesSame(fieldType, entity.getCanonicalName()))
{
otherEntity = entity;
}
else
{
otherEntity = findEntity(fieldType);
entity.addImport(otherEntity.getQualifiedName());
}
if (entity.hasField(fieldName))
{
throw new IllegalStateException("Entity [" + entity.getCanonicalName() + "] already has a field named ["
+ fieldName + "]");
}
if (!Strings.isNullOrEmpty(inverseFieldName) && otherEntity.hasField(inverseFieldName))
{
throw new IllegalStateException("Entity [" + otherEntity.getCanonicalName()
+ "] already has a field named ["
+ inverseFieldName + "]");
}
entity.addImport(Set.class);
entity.addImport(HashSet.class);
Field<JavaClass> field = entity.addField("private Set<" + otherEntity.getName() + "> " + fieldName
+ "= new HashSet<"
+ otherEntity.getName() + ">();");
Annotation<JavaClass> annotation = field.addAnnotation(ManyToMany.class);
Refactory.createGetterAndSetter(entity, field);
if (!Strings.isNullOrEmpty(inverseFieldName))
{
annotation.setStringValue("mappedBy", inverseFieldName);
otherEntity.addImport(Set.class);
otherEntity.addImport(HashSet.class);
if (!otherEntity.getCanonicalName().equals(entity.getCanonicalName()))
{
otherEntity.addImport(entity.getQualifiedName());
}
Field<JavaClass> otherField = otherEntity.addField("private Set<" + entity.getName() + "> "
+ inverseFieldName
+ "= new HashSet<" + entity.getName() + ">();");
otherField.addAnnotation(ManyToMany.class);
Refactory.createGetterAndSetter(otherEntity, otherField);