0

I'm trying to create a costume IdentityGenerator. If the id is null generate else give the value. I found this : Bypass GeneratedValue in Hibernate (merge data not in db?)

but I keep getting java.sql.SQLException: Field 'id' doesn't have a default value.

my entity:

@Entity
public class TestEntity extends AbstractEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "IdOrGenerated")
    @GenericGenerator(name = "IdOrGenerated", strategy = "com.xxx.service.UseIdOrGenerate")
    protected Long id;

    @Column(length = 64)
    private String name;


    public TestEntity(String name) {

    super();
    this.name = name;
    }


    public TestEntity(Long id, String name) {

    super();
    this.id = id;
    this.name = name;
    }


    public TestEntity() {

    super();
    }
}

my custom generator:

public class UseIdOrGenerate extends IdentityGenerator {

    @Override
    public Serializable generate(SessionImplementor session, Object object) throws HibernateException {

    Serializable id = session.getEntityPersister(null, object).getClassMetadata().getIdentifier(object, session);

    id = id != null ? id : super.generate(session, object);
    return id;
    }
}
Community
  • 1
  • 1
lior
  • 1,127
  • 3
  • 24
  • 43
  • for anyone looking for answer, you can refer to this http://stackoverflow.com/questions/804514/hibernate-field-id-doesnt-have-a-default-value – Joshua H Apr 19 '17 at 16:57

1 Answers1

0

returning an unassigned variable/field causes errors. The field id needs to be assigned a default value, which doesn't matter what it is as long as it has one.

protected Long id = new Long(0);