Search code examples
javahibernatecriteriahibernate-criteria

How to use Id autoinkriment at Hibernate?


Probably a silly question but I don't get it. So I've got a class like:

@Entity
@Table(name="colour"
    ,catalog="car_store"
)
public class Colour  implements java.io.Serializable {


     private Byte id;
     private String name;
     private Set<Car> cars = new HashSet<Car>(0);

    public Colour() {
    }


    public Colour(String name) {
        this.name = name;
    }
    public Colour(String name, Set<Car> cars) {
       this.name = name;
       this.cars = cars;
    }

     @Id @GeneratedValue(strategy=IDENTITY)


    @Column(name="id", unique=true, nullable=false)
    public Byte getId() {
        return this.id;
    }

    public void setId(Byte id) {
        this.id = id;
    }


    @Column(name="name", nullable=false)
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

@OneToMany(fetch=FetchType.LAZY, mappedBy="colour")
    public Set<Car> getCars() {
        return this.cars;
    }

    public void setCars(Set<Car> cars) {
        this.cars = cars;
    }
}

So if I'm trying to insert like:

Session session = HibernateUtil.getSessionFactory().openSession();
Colour newColour = new Colour();

newColour.setName("Deep Sea Blue");
session.save(newColour);

session.getTransaction().commit();

it should not automaticly generate new id value during this? Because it doesn't.

What am I doing wrong?

Thanks.


Solution

  • In the documentation provided type of the property is Long. In the example provided by you Byte is used. I assume there can be problems with this. Try to change it to Long.