简体   繁体   中英

Bypass GeneratedValue

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;
    }
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM