Home > Net >  Update nested OneToMany hibernate entity
Update nested OneToMany hibernate entity

Time:04-19

I implemented two entites. A RuleEntity and a RestCallEntity like the following:

RuleEntity

    @Entity(name = "RuleEntity")
    @Table(name = "Rule")
    public class RuleEntity {
    
        @Id
        @Column(name = ID_COLUMN_NAME, nullable = false)
        @GeneratedValue(strategy = AUTO)
        private Long id;

        @Column(name = "name", nullable = false)
        public String name = "";
    
        @OneToMany(targetEntity = RestCallEntity.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
        public final Set<RestCallEntity> restCalls = new HashSet<>();
    }

RestCallEntity

@Entity(name = "RestCallEntity")
@Table(name = "RestCall")
public class RestCallEntity

    @Id
    @Column(name = ID_COLUMN_NAME, nullable = false)
    @GeneratedValue(strategy = AUTO)
    private Long id;

    @Column(name = "name", nullable = false)
    public String name = "";
}

I receive a rule in a json endpoint. Than i convert the received json rule to a RuleEntity and call

getEntityManager().merge(ruleEntity);

The update works fine when i just change the name of the rule. But when i change the name of the it looks like hibernate tries to create a new restcall, even though it already has an ID. I get the following exception.

Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint ?rule_restcall_pkey? Detail: key ?(ruleentity_id, restcalls_id)=(45, 49)? already exists. at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2675) at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2365) at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:355) at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:490) at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:408) at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:166) at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:134) at io.agroal.pool.wrapper.PreparedStatementWrapper.executeUpdate(PreparedStatementWrapper.java:88) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197) ... 99 more

CodePudding user response:

So I finally figured out that it was probably caused by the implementation of the equals/hashcode methods. I changed the equals method to only check the id and the hashcode method to only return the hashcode of the id. Now the update works fine.

  • Related