Let the code stand up .. This is a Java project ..
The first is the hibernate core configuration file hibernate. cfg. xml under SRC.
<? XML version = '1. 0' encoding = 'utf-8'?> <Br/> <! Doctype hibernate-configuration Public <br/> "-// hibernate/hibernate configuration DTD 3.0/EN" <br/> "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <br/> <pibernate-configuration> <br/> <session-factory> <br/> <property name = "dialect"> Org. hibernate. dialect. mysqldialect </property> <br/> <property name = "connection. URL "> JDBC: mysql: // localhost: 3306/jadyer? Characterencoding = UTF-8 </property> <br/> <property name = "connection. username "> root </property> <br/> <property name =" connection. password "> jadyer </property> <br/> <property name =" connection. driver_class "> COM. mySQL. JDBC. driver </property> </P> <p> <property name = "hibernate. show_ SQL "> true </property> <br/> <property name =" hibernate. format_ SQL "> true </property> </P> <p> <! -- Read data in batches. Recommended Value: 50. Support for JDBC and underlying databases --> <br/> <property name = "hibernate. JDBC. fetch_size"> 50 </property> <br/> <! -- Update Data in batches. Recommended Value: 30 --> <br/> <property name = "hibernate. JDBC. batch_size"> 30 </property> <br/> <! -- After these two attributes are configured, when we submit SQL statements to the database, all data will not be read into the memory at one time --> <br/> <! -- Read the corresponding data in batches according to a certain amount, but whether the data will take effect depends on the support of the underlying database. --> <br/> <! -- Some databases do not support these parameters. Both Oracle and sqlserver are supported, while MySQL does not seem to support --> </P> <p> <! -- You can also write the ing file in the following ways --> <br/> <Mapping Resource = "com/jadyer/hibernate/all. HBM. xml"/> <br/> <! -- <Br/> <Mapping Resource = "com/jadyer/hibernate/user11.hbm. XML "/> <br/> <Mapping Resource =" com/jadyer/hibernate/user22.hbm. XML "/> <br/> <Mapping Resource =" com/jadyer/hibernate/user33.hbm. XML "/> <br/> --> <br/> </session-factory> <br/> </pibernate-configuration>
Next we will use three entity classes.
Package COM. jadyer. hibernate; <br/> Import Java. util. date; <br/> public class user11 {<br/> private string ID; <br/> private string name; <br/> private string password; <br/> private date createtime; <br/>/* -- setter and getter corresponding to the three attributes -- */<br/>}</P> <p> package COM. jadyer. hibernate; <br/> Import Java. util. date; <br/> public class user22 {<br/> private int ID; <br/> private string name; <br/> private string password; <br/> private date createtime; <br/>/* -- setter and getter corresponding to the three attributes -- */<br/>}</P> <p> package COM. jadyer. hibernate; <br/> Import Java. util. date; <br/> public class user33 {<br/> private string ID; <br/> private string name; <br/> private string password; <br/> private date createtime; <br/>/* -- the setter and getter corresponding to the three attributes are omitted -- */<br/>}
The Hibernate ing file all. HBM. xml corresponding to these three object classes is as follows:
<? XML version = "1.0"?> <Br/> <! Doctype hibernate-mapping Public <br/> "-// hibernate/hibernate DTD ing DTD 3.0/EN" <br/> "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <br/> <pibernate-mapping package = "com. jadyer. hibernate "> <br/> <class name =" user11 "table =" t_user11 "> <br/> <ID name =" ID "column =" user_id "length =" 32 "> <br/> <generator class =" UUID "/> <br/> </ID> <br/> <property name =" name "unique =" true "not -null = "true" length = "20"/> <br/> <property name = "password" not-null = "true" length = "10"/> <br /> <property name = "createtime" column = "create_time"/> <br/> </class> </P> <p> <class name = "user22" table = "t_user22"> <br/> <ID name = "ID" column = "user_id"> <br/> <generator class = "native"/> <br/> </ id> <br/> <property name = "name" unique = "true" not-null = "true" length = "20"/> <br/> <property name = "password"/> <br/> <property name = "createtime" column = "createtime"/> <br/> </class> </P> <p> <class name = "user33" table = "t_user33"> <br/> <ID name = "ID" column = "user_id" length = "32"> <br/> <generator class = "assigned"/> <br/> </ID> <br/> <property name = "name"/> <br/> <property name = "password"/> <br/> <property name = "createtime" column = "create_time"/> <br/> </class> <br/> </pibernate-mapping>
Then, use the hibernate ing file to generate the exportdb. Java of the database table.
Package COM. jadyer. hibernate; </P> <p> Import Org. hibernate. cfg. configuration; <br/> Import Org. hibernate. tool. hbm2ddl. schemaexport; </P> <p>/** <br/> * use the hibernate ing file to generate a database table <br/> */<br/> public class exportdb {<br/> public static void main (string [] ARGs) {</P> <p> // read hibernate. cfg. XML file <br/> Configuration CFG = new configuration (). configure (); </P> <p> // create a schemaexport object <br/> schemaexport export = new schemaexport (CFG ); </P> <p> // create a database table <br/> export. create (True, true); <br/>}< br/>}
The following is the custom tool class hibernatesessionutils. java used to generate a session.
Package COM. jadyer. hibernate; </P> <p> Import Org. hibernate. session; <br/> Import Org. hibernate. sessionfactory; <br/> Import Org. hibernate. cfg. configuration; </P> <p> public class hibernatesessionutils {<br/> Private Static sessionfactory factory; </P> <p> static {<br/> try {<br/> Configuration CFG = new configuration (). configure (); <br/> factory = cfg. buildsessionfactory (); <br/>}catch (exception e) {<br/> E. P Rintstacktrace (); <br/>}</P> <p> Public static session getsession () {<br/> return factory. opensession (); <br/>}</P> <p> Public static void closesession (session) {<br/> If (null! = Session & session. isopen () {<br/> session. Close (); <br/>}< br/>}
Finally, sessionflushtest. Java is the unit test class implemented by junit3.8.
Package COM. jadyer. hibernate; </P> <p> Import Java. util. date; </P> <p> Import Org. hibernate. session; <br/> Import Org. hibernate. transaction; </P> <p> Import COM. jadyer. hibernate. hibernatesessionutils; <br/> Import COM. jadyer. hibernate. user11; <br/> Import COM. jadyer. hibernate. user22; <br/> Import COM. jadyer. hibernate. user33; </P> <p> Import JUnit. framework. testcase; </P> <p> public class sessionflushtest extends Test Case {<br/>/** <br/> * batch input 1000 data records into the database <br/> * @ see when the SAVE () method is executed, it also stores data in the first-level cache <br/> * @ see. Therefore, you must consider memory overflow caused by a large amount of physical data stored in the database at one time. <br/> * @ see, you can use the session. flush () () and clear () method <br/> */<br/> Public void testcachea () {<br/> session = NULL; <br/> try {<br/> session = hibernatesessionutils. getsession (); <br/> session. begintransaction (); // start the transaction <br/> for (INT I = 0; I <1000; I ++) {<br/> user22 user = new user22 (); <Br/> User. setname ("U _" + I); <br/> session. save (User); <br/> If (0 = I % 20) {<br/> session. flush (); // every 20 pieces of data forces session persistence data <br/> session. clear (); // clear the cache at the same time to avoid memory overflow caused by a large amount of data <br/>}< br/> // if the data volume is too large, we recommend that you do not use hibernate to input data any more. You can use JDBC to implement it. <br/> // If JDBC cannot meet the requirements, you can also consider using a specific database import tool <br/> // For example, compared with Oracle, you can use its specific tool [SQL * loader] <br/> session. gettransaction (). commit (); // submit the transaction <br/>} catch (exception e) {<br/> E. printstacktrace (); <br/> session. gettransaction (). rollback (); // if an exception occurs, the transaction is rolled back <br/>} finally {<br/> hibernatesessionutils. closesession (session); // do not forget to close Org. hibernate. session <br/>}</P> <p>/** <br/> * when the primary key generation policy is UUID <br/> * Monitoring: SQL statement sending status after saving () and explicit execution of flush () <br/> * Result: After saving () is called, The insert statement is not immediately issued. After calling flush, <br/> * @ see [description of the existsindatebase attribute in the session] <br/> * @ see focuses on the variables in the upper right corner of the debug perspective. changes in data in the view <br/> * @ see first executes the unit test method in the debug as --- JUnit test mode, then, after saving () is executed, it is not executed to flush () <br/> * @ see open to session --- actionqueue --- insertions --- elementdata --- [0] In the variables view. <br/> * @ see we can set data is interpreted as a set of insert objects, this set will be traversed later to generate the insert statement <br/> * @ see the actionqueue under the session in the variables view is Temporary set, used to form insert or other statements <br/> * @ see in the variables view, persistencecontext under the session can be understood as its cache <br/> * @ see expands to persistencecontext --- entityentries --- map --- entries --- table --- [0] --- value <br/> * @ See note: in the expanded table, it may not always be [0] each time. In this case, we should expand the hashmap $ entry <K, v> the value [I] is correct. <br/> * @ see is followed by a copy of data under the second-level value. We can roughly understand it as the data in its cache <br/> * @ see then we will find the existsindatebase attribute, which is used to determine whether the current data exists in the database, the value is false or true <br/> * @ see. Before the execution of SAVE () is complete, the value of the existsindatebase attribute is false. <br/> * @ see: the value of the existsindatebase attribute is true after flush () is executed but not before commit () is executed, the SQL statement <br/> * @ see will be issued immediately. When the value of existsindatebase changes to true, it indicates that the data already exists in the database <br/> * @ see. Then, return to elementdata --- [0] To find the temporary set, it is found that the data in the temporary set is no longer available <br/> * @ see because it needs to traverse the temporary set, and then take out the data in the temporary set to form the inse RT statement. After an insert statement is executed, the temporary set is cleared. <br/> * @ see. Therefore, this temporary set is used for temporary exchange. After the temporary set is cleared, the status of existsindatebase in the cache will be updated to true <br/> * @ see. After the flush () command is executed, the Commit () command is not executed, at this time, the transaction has not been committed, but the SQL statement <br/> * @ see has been executed. If you execute the SELECT query in the MySQL command line client, the data cannot be viewed, this involves the isolation level of the database <br/> * @ see we can use select @ tx_isolation; command to view the default isolation level of MySQL, the result is REPEATABLE-READ: you can read it again <br/> * @ see. If we execute the SET transaction isolation level read uncommitted; command, the isolation level is uncommitted <br/> */<br/> Public void testsave11 () {<br/> Session session = NULL; <br/> transaction Tx = NULL; <br/> try {<br/> session = hibernatesessionutils. getsession (); <br/> Tx = session. begintransaction (); <br/> user11 user = new user11 (); <br/> User. setname ("Zhang San"); <br/> User. setpassword ("123"); <br/> User. setcreatetime (new date (); <br/> // Since user11 adopts the uuid primary key generation policy <br/> // after saving () is called, the insert statement is not issued, but the user is included in the session management <br/> // but the ID is generated. In addition, the existsindatebase status in the session is false <br/> session. save (User); <br/> // After flush () is called, Hibernate clears the cache and runs the SQL statement, the user object will be saved to the database <br/> // if the database isolation level is set to read-uncommitted, that is, the read is not committed, then we can see flush () <br/> // clears the user object in the insertions temporary set in the session. In this case, the existsindatebase in the session is also set to true <br/> // session. flush (); <br/> // by default, the Commit () operation will first execute flush () to clear the cache, so you do not need to explicitly call flush () method <br/> Tx. commit (); <br/>}catch (exception e) {<br/> E. Printstacktrace (); <br/> Tx. rollback (); <br/>}finally {<br/> hibernatesessionutils. closesession (session ); <br/>}</P> <p>/** <br/> * when the primary key generation policy is native <br/> * @ see Monitoring: SQL statement sending status after saving () is executed <br/> * @ see Result: After saving () is called, The insert statement is sent immediately and executed. Because you need to return the id value generated by the database <br/> */<br/> Public void testsave22 () {<br/> session = NULL; <br/> try {<br/> session = hibernatesessionutils. getsession (); <br/> session. begintransaction (); <br/> user22 user = new user22 (); <br/> User. setname ("Li Si"); <br/> User. setpassword ("123"); <br/> User. setcreatetime (new date (); <br/> // Since user22 adopts the native primary key generation policy <br/> // after calling the SAVE () method, the insert statement is sent and executed, and the id value generated by the database is returned <br/> // The session management function also modifies the existsindatebase status in the session to true <br/> // if the database isolation level is set to uncommitted read, then we can see the saved () Data <br/> session. save (User); <br/> session. gettransaction (). commit (); <br/>}catch (exception e) {<br/> E. printstacktrace (); <br/> session. gettransaction (). rollback (); <br/>}finally {<br/> hibernatesessionutils. closesession (session ); <br/>}</P> <p>/** <br/> * when the primary key generation policy is UUID <br/> * @ see Monitoring: run save () and evict (), Data changes in the cache <br/> * @ see result: the request cannot be submitted successfully after the Commit () command is executed, report possible nonthreadsafe access to session <br/> */<br/> Public void testsave33 () {<br/> session = NULL; <br/> try {<br/> session = hibernatesessionutils. getsession (); <br/> session. begintransaction (); <br/> user11 user = new user11 (); <br/> User. setname ("Wang Wu"); <br/> User. setpassword ("123"); <br/> User. setcreatetime (new date (); <br/> session. save (u Ser); <br/> // After evict () is executed, the user object is evicted from the session. That is, the user object is evicted from the entityentries attribute of the session <br/> session. evict (User); <br/> // After the Commit () command is executed, it cannot be submitted successfully. <br/> // when hibernate clears the cache, the user object will be taken out of the temporary set insertions of the session for the insert operation <br/> // The value of the existsindatabase attribute in entityentries in persistencecontext will be updated to true <br/>/ /We have used evict () the user object is evicted from the entityentries of the session. Therefore, related data cannot be found and cannot be updated. <br/> // an exception is thrown: Org. hibernate. assertionfailure: Possible nonthreadsafe access to session <br/> // The thread does not Security. That is to say, when the user object is cleared and the data is updated, it is considered that other threads have deleted the data. <br/> // In fact, it is understood that this problem will not occur. Some people on the Internet say this may be a bug of hibernate, but it is not actually <br/> // you can see through these: hibernate has made some effort in caching <br/> session. gettransaction (). commit (); <br/>}catch (exception e) {<br/> E. printstacktrace (); <br/> session. gettransaction (). rollback (); <br/>}finally {<br/> hibernatesessionutils. closesession (session ); <br/>}</P> <p>/** <br/> * when the primary key generation policy is UUID <br/> * @ see Monitoring: run the flush () method before evict () to solve the problem that data cannot be submitted after evict () is called. <br/> * @ see result: Execution Successfully submitted after the row commit () <br/> */<br/> Public void testsave44 () {<br/> session = NULL; <br/> try {<br/> session = hibernatesessionutils. getsession (); <br/> session. begintransaction (); <br/> user11 user = new user11 (); <br/> User. setname ("Zhao six"); <br/> User. setpassword ("123"); <br/> User. setcreatetime (new date (); <br/> session. save (User); <br/> session. flush (); // an insert statement is issued <br/> session. evict (User); <br/>/ /After executing commit (), you can successfully submit the job. <br/> // because hibernate clears the cache, the user object cannot be found in the insertions temporary set of the session <br/> // so the insert statement is not issued, and the status of the existsindatabase attribute in the session is not updated <br/> session. gettransaction (). commit (); <br/>}catch (exception e) {<br/> E. printstacktrace (); <br/> session. gettransaction (). rollback (); <br/>}finally {<br/> hibernatesessionutils. closesession (session ); <br/>}</P> <p>/** <br/> * when the primary key generation policy is native <br/> * @ se S monitoring: Changes in data in the cache after saving () and evict () are executed <br/> * @ ses result: Execute commit () after successful submission <br/> */<br/> Public void testsave55 () {<br/> session = NULL; <br/> try {<br/> session = hibernatesessionutils. getsession (); <br/> session. begintransaction (); <br/> user22 user = new user22 (); <br/> User. setname ("Ma Qi"); <br/> User. setpassword ("123"); <br/> User. setcreatetime (new date (); <br/> session. save (User); // an insert statement is sent. <br/> Session. evict (User); <br/> // after you execute commit (), you can successfully submit the file. <br/> // when hibernate clears the cache, the user object cannot be found in the insertions temporary set of the session <br/> // so the insert statement is not issued, and the status of the existsindatabase attribute in the session is not updated <br/> session. gettransaction (). commit (); <br/>}catch (exception e) {<br/> E. printstacktrace (); <br/> session. gettransaction (). rollback (); <br/>}finally {<br/> hibernatesessionutils. closesession (session); <br/>}</P> <p>/** <br/> * When the primary key generation policy is assigned, <br/> * @ see Monitoring: sequence of batch save, update, and delete operations <br/> * @ see result: hibernate submits related operations in the order of SAVE, update, and delete <br/> */<br/> Public void testsave66 () {<br/> session = NULL; <br/> try {<br/> session = hibernatesessionutils. getsession (); <br/> session. begintransaction (); <br/> user33 user = new user33 (); <br/> User. setid ("001"); <br/> User. setname (""); <br/> session. save (User); <br/> User. Setname (" Yao"); <br/> // session. Update (User); // you can also call Update () without explicit calling (). At this time, the user is in the persistent state, and it will automatically update <br/> user33 user3 = new user33 (); <br/> user3.setid ("002 "); <br/> user3.setname (""); <br/> session. save (user3); <br/> // hibernate: insert into t_user33 (name, password, create_time, user_id) values (?, ?, ?, ?) <Br/> // hibernate: insert into t_user33 (name, password, create_time, user_id) values (?, ?, ?, ?) <Br/> // hibernate: Update t_user33 set name = ?, Password = ?, Create_time =? Where user_id =? <Br/> // hibernate submits related operations in the order of SAVE, update, and delete <br/> session. gettransaction (). commit (); <br/>}catch (exception e) {<br/> E. printstacktrace (); <br/> session. gettransaction (). rollback (); <br/>}finally {<br/> hibernatesessionutils. closesession (session ); <br/>}</P> <p>/** <br/> * when the primary key generation policy is assigned <br/> * @ see Monitoring: use flush () to implement the execution sequence of custom save, update, and delete operations <br/> * @ see result: SQL will be executed as per our wishes <br/> */<br/> Publ IC void testsave77 () {<br/> session = NULL; <br/> try {<br/> session = hibernatesessionutils. getsession (); <br/> session. begintransaction (); <br/> user33 user = new user33 (); <br/> User. setid ("003"); <br/> User. setname ("Cai Yilin"); <br/> session. save (User); <br/> User. setname ("dish 10"); <br/> // session. update (User); // you can call Update () without explicit calling (). At this time, the user is in the persistent State and will automatically update the <br/> session. flush (); // use flush () to implement the execution sequence of custom save, update, and delete operations. <br/> user33 user33 = new user33 (); <br/> user33.setid ("004"); <br/> user33.setname ("Zheng yijian"); <br/> session. save (user33); <br/> // hibernate: insert into t_user33 (name, password, create_time, user_id) values (?, ?, ?, ?) <Br/> // hibernate: Update t_user33 set name = ?, Password = ?, Create_time =? Where user_id =? <Br/> // hibernate: insert into t_user33 (name, password, create_time, user_id) values (?, ?, ?, ?) <Br/> // because the flush () method is executed after udpate (), only sessions are generated when commit () clears the cache. save (user33) SQL statement <br/> session. gettransaction (). commit (); <br/>}catch (exception e) {<br/> E. printstacktrace (); <br/> session. gettransaction (). rollback (); <br/>}finally {<br/> hibernatesessionutils. closesession (session); <br/>}< br/>}