Home > Software engineering >  Insert null in @JoinColumn field
Insert null in @JoinColumn field

Time:11-23

I have a tables

CREATE TABLE IF NOT EXISTS users
(
    id                      BIGSERIAL PRIMARY KEY
);

CREATE TABLE IF NOT EXISTS positions
(
    id                   BIGSERIAL PRIMARY KEY,
    parent_user_id       BIGINT,  -- can be null its cause without REFERENCES users (id)
    user_id              BIGINT REFERENCES users (id)
);

And entity class

@Table(name = "users")
@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ToString.Exclude
    @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
    private Set<Position> positions;
}

@Table(name = "positions")
@Entity
public class Position {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ToString.Exclude
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private User user;

    @ToString.Exclude
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_user_id", columnDefinition = "BIGINT")
    private User parentUser;
}

Accordingly, business logic parentUser can be null but when I try to insert a new position get the error:

2022-11-21 18:24:21:934 ERROR i.n.c.impl.ErrorListenerLoggerImpl - exceptionOccurred, Connection: 207475, Exception: org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : ltd.package.model.Position.parentUser -> ltd.package.model.User; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : ltd.package.model.Position.parentUser -> ltd.package.model.User

Is it possible to insert a new Position with null as parentUser?

CodePudding user response:

Yes. The problem is not the fact that the relationship is null. The problem is that parentUser is set to an unmanaged object.

You need to show how you are creating the object position, but I bet somewhere, you are initializing parentUser and that's what's causing the exception.

You can quickly check by setting parentUser to null before saving the position:

...
position.setParentUser(null);
positionRepository.save(position);

Make sure that when you create a new Position object, you are also not initializing the parentUser.

  • Related