eu estou fazendo uma biblioteca que popula um model qualquer com valores aleatorios, para ser usado em testes, mas acontece que quando eu tenho uma relação como abaixo, eu recebo um StackOverflowException
Author
@Entity
public class Author implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Long id;
private String name;
@OneToMany
private List<Book> books = new ArrayList<Book>();
e Book
@Entity
public class Book implements Serializable {
@ManyToOne
private Author author;
o codigo que faz a leitura dos campos é assim
public <T> T fakeIt(Class<T> clazz) throws FakerException {
if(clazz.getAnnotation(Entity.class) == null){
throw new FakerException("The class "+ clazz.getName()+ "is not an entity");
}
try {
T faked = clazz.newInstance();
for(Field f : clazz.getDeclaredFields()){
if(f.getName().equals("serialVersionUID"))
continue;
System.out.println("Genearting value for "+f.getName() + " on " + f.getDeclaringClass());
f.setAccessible(true);
f.set(faked, getValueForField(f));
}
return faked;
} catch(Exception e){
throw new FakerException(e);
}
}
private Object getValueForField(Field f) throws Exception {
if(f.isAnnotationPresent(UseGenerator.class)){
Generator<?> gen = (Generator<?>) f.getAnnotation(UseGenerator.class).generator().newInstance();
return gen.genearte();
} else if(f.isAnnotationPresent(ManyToOne.class)){
return fakeIt(f.getType());
} else if(f.isAnnotationPresent(OneToMany.class)){
Class<?> toFake = extractTypeFromList(f);
List<Object> fakedObjects = new ArrayList<Object>();
for(int i = 0; i < 6; i++){
fakedObjects.add(fakeIt(toFake));
}
return fakedObjects;
}
// Other types
String clazzType = f.getType().getSimpleName();
Generator<?> generator = defaultGenerators.get(clazzType.toLowerCase());
if(generator != null)
return generator.genearte();
return null;
}
private Class<?> extractTypeFromList(Field f) {
ParameterizedType parameterizedType = (ParameterizedType) f.getGenericType();
Class<?> type = (Class<?>) parameterizedType.getActualTypeArguments()[0];
return type;
}
no caso, fakeIt
é a função que gera os valores aleatorios. nesse caso, ele cai no campo books
e quando chama novamente o fakeIt
, vai tentar criar um novo Author
que vai cair no campo books
e assim por diante.
qual a melhor forma de evitar isso?
StackOverflow
. EssefakeIt
acaba por chamar esse mesmo método?fakeIt
chama o metodogetValueForField(Field F)
que chama novamente ofakeIt
em caso de relacionamento. posso postar o codigo todo se ajudarStackOverflow
é por causa da relação bidirecional: quando vai criar umauthor
ele cria uma lista debook
e esses também tentarão criar umauthor
, a partir dai segue em loop. Você terá que procurar tratar as relações bidirecionais.