Spring-boot: TestEntityManager persist issue

Created on 3 Aug 2016  路  1Comment  路  Source: spring-projects/spring-boot

Hi all,

I'm using the TestEntityManager in my unit tests but noticed something strange.
I have an entity with a field name annotated with @Id.

@Entity(name = "section")
public class SectionEntity {

    @Id
    private String name;

    private String title;

    private String directory;

    @ManyToOne
    @JoinColumn(name = "parent_name")
    private SectionEntity parent;

    public SectionEntity() {
        //default
    }

    public SectionEntity(String name) {
        this.name = name;
    };
//getters and setters

In my test I want to insert a section by doing this:

testEntityManager.persist(new SectionEntity(section));

this results in

Entity SectionEntity already has an ID")

The field name is a String and needs to be set before it can be inserted.
So why is this done in the code:

public <E> E persist(E entity) {
        Assert.state(getId(entity) == null,
                "Entity " + entity.getClass().getName() + " already has an ID");
        getEntityManager().persist(entity);
        return entity;
    }

As a workaround I do this:

testEntityManager.getEntityManager().persist(new SectionEntity(section));

But shouldn't it be possible to do this without calling the getEntityManager() ?

Regards,

Derk

Most helpful comment

I think the assumption was that @Id fields would always be marked with @GeneratedValue. In hindsight that restriction looks a bit too much.

>All comments

I think the assumption was that @Id fields would always be marked with @GeneratedValue. In hindsight that restriction looks a bit too much.

Was this page helpful?
0 / 5 - 0 ratings