kuros / random-jpa

Create random test data for JPA/Hibernate entities.
GNU General Public License v3.0
26 stars 4 forks source link

No way to resolve "Cyclic dependency found for class"? #43

Closed Ansonator closed 3 years ago

Ansonator commented 3 years ago

One of my @Entity classes has a reference to itself. It would prefer this to be set to null or a fixed value when generating that entity. I don't really want to edit the entity class itself.

But, I don't see a way to do this. The error comes as soon as I call JpaContextFactory#generate. I tried assigning a custom attribute and class generator for this class, but it still gives me the error.

I also tried ignoreLink. See the following example. With this, it fails at the call to jpaContextFactory.generate() because the link's from and to fields are null. I'm not seeing anything in the code which would look for the @StaticMetamodel annotation and initialize those?

        final com.github.kuros.random.jpa.JPAContextFactory jpaContextFactory =
            com.github.kuros.random.jpa.JPAContextFactory.newInstance(Database.ORACLE, entityManager);
        final Generator generator = Generator.newInstance();
        Link link = Link.newLink(JobTask_.parent, JobTask_.id);
        jpaContextFactory.with(Dependencies.newInstance()
            .ignoreLink(link));
        JPAContext jpaContext = jpaContextFactory.generate();
        jpaContext.remove(JobTask.class);
@StaticMetamodel(JobTask.class) 
class JobTask_ {
    public static volatile SingularAttribute<JobTask, Long> id;
    public static volatile SingularAttribute<JobTask, Job> job;
    public static volatile SingularAttribute<JobTask, Environment> environment;
    public static volatile SingularAttribute<JobTask, JobTask> parent;
}

Here's the relevant part of my @Entity.

@Entity
@Table(name = "JOB_TASKS")
public class JobTask {
    @Id
    @GeneratedValue(generator = "triggerAssigned")
    @Column(name = "JOB_TASK_ID")
    protected Long id;

    @ManyToOne
    @JoinColumn(name = "job_id", updatable = false, nullable = false)
    @NonNull
    private Job job;

    @Column(name = "ENVIRONMENT_ID")
    @Convert(converter = EnvironmentConverter.class)
    @NonNull
    private Environment environment;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_job_task_id")
    private JobTask parent;
}
kuros commented 3 years ago

I will provide mechanism to ignore cyclic dependency cases manually.

kuros commented 3 years ago

I have fixed the issue, added a method to ignore fields. The feature is available in version 1.0.4

Now you can ignore attributes in Dependencies while building JPAContextFactory

 jpaContextFactory.with(Dependencies.newInstance()
            .ignoreAttribute(JobTask_.parent));