I am trying to save data in table using hibernate. My entity looks like
@Entity
public class Nemocnica implements java.io.Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
//@Column(name="N_ID")
private BigDecimal NId;
private String adresa;
private Set sanitkas = new HashSet(0);
public Nemocnica() {
}
public Nemocnica( String adresa) {
this.NId = NId;
}
public Nemocnica(BigDecimal NId, String adresa) {
this.NId = NId;
this.adresa = adresa;
}
public Nemocnica(BigDecimal NId, String adresa, Set sanitkas) {
this.NId = NId;
this.adresa = adresa;
this.sanitkas = sanitkas;
}
public BigDecimal getNId() {
return this.NId;
}
public void setNId(BigDecimal NId) {
this.NId = NId;
}
public String getAdresa() {
return this.adresa;
}
public void setAdresa(String adresa) {
this.adresa = adresa;
}
public Set getSanitkas() {
return this.sanitkas;
}
public void setSanitkas(Set sanitkas) {
this.sanitkas = sanitkas;
}
}
And the way i want to insert data into it
public static Integer addNemocnica( String adresa ){
Integer ID = null;
try{
Nemocnica n = new Nemocnica( adresa);
ID = (Integer) session.save(n);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}
return ID;
}
Yet it still throws error
ids for this class must be manually assigned before calling save()
I tried everything i found including
@GeneratedValue(strategy=GenerationType.IDENTITY)
I am using oracle database and the table i am trying to insert data into has set autoincrement to true. How can fix this?
Thanks for help
Best Answer
Edit 4:
It's not clear how is your tables setup in DB. I am assuming tables are setup like this:
)
If that's how your table is created, then
should work. Try matching the names of the columns in the table to the fields in the Java class. If not, then show us your sql table how it was created. If you don't know how to get the table creation schema, you will need to look it up online for your specific Database. You may also want to lookup how to get the sequence schema out of the Database (if schema exists, you will find it).
End of Edit 4.
If you are using a sequence in Oracle database, then
GenerationType.IDENTITY
is not correct. you need to provide GenerationType.SEQUENCE in strategy attribute. Code would will look like this:But the above code will create a new sequence. If you already have a sequence ready and setup in Oracle DB then you would need to provide:
If you go this route, you have to specify the
allocationSize
which needs to be the same value that the DB sequence uses as its "auto increment".Try this:
sequenceName
attribute is the name of the sequence in DB. So you will put that name in that attribute.The last resort is to manually retrieve the value of the sequence from DB. Then set it yourself. Retrieving part would look like this
But for this to work you would have to modify your code, which I suggest you don't.