'Java SpringBootTest EntityNotFoundException on setup method

There is a class for test to save some constraints, there is method setup with @Before annotation, where test data is saved in database:

.. And when running the test in this method, there is an EntityNotFoundException error when saving Entity to the repository:

    
    . . .

    @Autowired
    EntityFeatureConfigRepository entityFeatureConfigRepository;

    @Autowired
    FeatureRepository featureRepository;

    @Autowired
    EntityRepository entityRepository;

    @Before
    public void setup() {
        entityRepository.deleteAll();
        featureRepository.deleteAll();
        entityFeatureConfigRepository.deleteAll();
        
        featureRepository.save(new Feature(1);                    <==== 1L - id 
        entityRepository.save(new Entity(1));
        entityFeatureConfigRepository.save(new EntityFeatureConfig( <=EXCEPTION
                new Feature(1),          
                new Entity(1),
                true));
    }
    . . .

Unable to find Entity with id 1; nested exception is javax.persistence.EntityNotFoundException: Unable to find Entity with id 1

The error is that Entity does not exist, although it is saved in the setup method

If there are such fields in the class EntityFeatureConfig, maybe the problem is in them.

    @Id
    @ManyToOne
    @ToString.Exclude
    @JsonIgnore
    @JoinColumn(name = "feature_id", referencedColumnName = "id")
    private Feature feature;

    @Id
    @ManyToOne
    @ToString.Exclude
    @JoinColumn(name = "entity_id", referencedColumnName = "id")
    private Entity entity;

And Entity

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "entity")
    @EqualsAndHashCode.Exclude
    @JsonIgnore
    private Set<UserManagingEntity> user;

What can this error be related to, that the data is not in the repository?



Solution 1:[1]

Try to use returned objects from save method instead of create new ones

Feature f = featureRepository.save(new Feature(1);                 
Entity e = entityRepository.save(new Entity(1));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris