ConnectLast timeTo continue, IDs in tmp_emp are generated based on the sequence sq_tmp_emp. You need to set in tmpemp. HBM. xml:
<ID name = "ID" type = "long">
<Column name = "ID" not-null = "true" SQL-type = "Number" unique = "true"/>
<Generator class = "sequence">
<Param name = "sequence"> sq_tmp_emp </param>
</Generator>
</ID>
In this way, Hibernate will automatically retrieve nextval from sq_tmp_emp to fill in the ID field.
ExampleCode:
Create a tool class first
Package app; import Org. hibernate. session; import Org. hibernate. sessionfactory; import Org. hibernate. transaction; import Org. hibernate. cfg. configuration; public class hibernateutils {private hibernateutils () {} static sessionfactory;/** get hibernate session */public static session getsession () {If (sessionfactory = NULL) {sessionfactory = new configuration (). configure (). buildsessionfactory ();} return sessionfactory. opensession ();}/** insert record */public static Boolean addobject (Object OBJ) {session Ss = NULL; transaction Ts = NULL; boolean result = false; try {Ss = getsession (); TS = ss. begintransaction (); SS. save (OBJ); Ts. commit (); Result = true;} finally {ss. close () ;}return result ;}}
Add record class
Package app; import Org. hibernate. session; import Org. hibernate. sessionfactory; import Org. hibernate. cfg. configuration; import domain. tmpemp; import Java. math. bigdecimal; import Java. util. calendar; import Java. util. date; import Java. util. list; public class Hello {/*** @ Param ARGs */public static void main (string [] ARGs) {tmpemp EMP = new tmpemp (); EMP. setname ("Zhang Sanfeng"); EMP. setsalary (New bigdecimal (1000); EMP. s Etsex ('M'); EMP. setbirthday (new date (1985-1900,12-); // No. 1985-12-1 Boolean B = hibernateutils. addobject (EMP); If (B) {system. out. println ("successfully inserted, the ID of the new record is:" + EMP. GETID ();} else {system. out. println ("insertion failed! ");}}}
Running result:
Hibernate: Select igsa. sq_tmp_emp.nextval from dual
Hibernate: insert into igsa. tmp_emp (name, birthday, sex, salary, ID) values (?, ?, ?, ?, ?)
Inserted successfully. The ID of the new record is 210.