So, I want to customize the ID for a "FriendID" with IdentifierGenerator, and I want to make it as simple as possible first just to make sure it works. Been watching tutorials and looked at code examples, but I can't get it to work even though it seems really simple... Might it be something else I'm missing out?
It doesn't seem to reach the GenFriendID-class in the strategy-parameter, because the generator class name is grey and says "Class 'GenFriendID' is never used". The path should be right, and been trying moving them to same package and so on.
Also been trying to drop the DB and rerun the creation of the DB based on the changes (It was GenerationType.AUTO before)
Entity class,
package com.WineOutBE.entity;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "FriendID")
public class FriendID implements Serializable {
@Id
@GenericGenerator(name = "friend_id", strategy = "com.WineOutBE.generator.GenFriendID")
@GeneratedValue(generator = "friend_id")
@Column(name = "FriendID", unique = true, length = 6)
private Long friendid;
public Long getId() {
return friendid;
}
public void setId(Long FID) {
this.friendid = FID;
}
}
Generator class that implements IdentifierGenerator,
package com.WineOutBE.generator;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import java.io.Serializable;
public class GenFriendID implements IdentifierGenerator {
@Override
public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
return 1234L;
}
}
Testing method which returns NULL and not 1234,
package com.WineOutBE;
import com.WineOutBE.entity.FriendID;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class Testing {
FriendID friendID;
@Test
void checkCorrectIdValue(){
friendID = new FriendID();
assertEquals(1234L, friendID.getId());
}
}
Let me know if there's any other code you need to see and I'll update the post! Thank you in advance!
CodePudding user response:
Id generation will work if you write entity to db
if you execute simple
friendID = new FriendID();
it wont work
save friendID
to database using for example EntityManager.merge
od spring and than saved object should have id generated