6

Hi I have written code like this

@Id
@Column(nullable=false)
@GeneratedValue(strategy=GenerationType.AUTO)
public int getUserID() {
    return UserID; 
}

But I manually setting it from DAO like "e.setUserID(01);" to insert.Otherwise row not inserting Is there any process to get value to id and retrieve what value generated automatically. Im thinking i will get some help

Vidya
  • 145
  • 1
  • 1
  • 9

2 Answers2

5

Use the IDENTITY generation type instead of auto. Use a Long for id. I also recommend changing the name from UserID to userId. Do not forget the @Entity for the class name.

@Entity
public class MyClass{

private Long userId;

    @Id 
    @GeneratedValue(strategy=GenerationType.IDENTITY) 
    @Column
    public Long getUserID(){
        return userId;
    }

    //.. rest of class

}

Be very careful with the naming conventions and make sure your field names and types match the field names and types from the database.

Raul Rene
  • 10,014
  • 9
  • 53
  • 75
  • It will automatically create ID value when row created...or we should call setter In methods – Vidya Apr 12 '12 at 04:50
  • You should **never** set an id manually if in the database the id appears as an identity. First make sure that your database configuration is in such a way that it auto-increments the ids. Then map the id column as I suggested above. Again, be careful at naming conventions and types of the data. – Raul Rene Apr 12 '12 at 06:25
4

Use

@GenericGenerator(name="generator", strategy="increment")
@GeneratedValue(generator="generator")
Shehzad
  • 2,870
  • 17
  • 21
  • It worked ,but it is assigning to another column the generated value – Vidya Apr 12 '12 at 06:42
  • If anyone is down voting, there should be a reason which should be shared, Why down voted? – Shehzad Jul 24 '15 at 10:21
  • This is not a safe method since the generator selects the max id from the db and increments it. Though it is useful for testing purposes. The docs clearly warn `Do not use in a cluster!`. Check it out: https://docs.jboss.org/hibernate/orm/3.2/api/org/hibernate/id/IncrementGenerator.html https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/mapping.html#mapping-declaration-id – Bahattin Ungormus Aug 11 '15 at 07:35
  • @ Bahattin Ungormus did you really read the problem statement ? – Shehzad Aug 12 '15 at 10:25