Hibernate Unit Test Framework

Source: Internet
Author: User

Hibernate is very uncertain when writing database configuration files and must be tested to ensure the correctness of the database structure. So you can apply junit for testing.

Using JUnit is very simple, and eclipse just needs to create a new junit test case for the right-click Project (fill in the class name and package name). Then write the corresponding code in the corresponding location to run the test.

A common hibernate testing framework is given below:

Package Com.atguigu.hibernate.entities;import Java.io.fileinputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.sql.blob;import Java.sql.connection;import Java.sql.sqlexception;import Java.util.date;import Org.hibernate.hibernate;import Org.hibernate.session;import org.hibernate.SessionFactory; Import Org.hibernate.transaction;import Org.hibernate.cfg.configuration;import Org.hibernate.jdbc.work;import Org.hibernate.service.serviceregistry;import Org.hibernate.service.serviceregistrybuilder;import Org.junit.After ; Import Org.junit.before;import Org.junit.test;public class Hibernatetest {private Sessionfactory sessionfactory; Private Session session;private Transaction Transaction; @Beforepublic void init () {Configuration configuration = new Configuration (). Configure ();                            Serviceregistry serviceregistry = new Serviceregistrybuilder (). Applysettings (Configuration.getproperties ()) . Buildserviceregistry (); sessionfactory = Configuration.buildsessionFactory (serviceregistry); session = Sessionfactory.opensession (); transaction = Session.begintransaction ();} @Afterpublic void Destroy () {transaction.commit (); Session.close (); Sessionfactory.close ();} @Testpublic void Testcomponent () {Worker worker = new Worker (); Pay pay = new pay ();p Ay.setmonthlypay;p Ay.setyearpay (80000); Pay.setvocationwithpay (5); Worker.setname ("ABCD"); Worker.setpay (pay); Session.save (worker); @Testpublic void Testblob () throws Exception{//news news = new News ()//news.setauthor ("CC");//news.setcontent (" CONTENT ");//news.setdate (new Date ());//news.setdesc (" DESC ");//news.settitle (" CC ");////inputstream stream = new FileInputStream ("hydrangeas.jpg");//blob image = Hibernate.getlobcreator (session)//. Createblob (Stream, Strea M.available ());//news.setimage (image);////session.save (news); News news = (news) Session.get (News.class, 1); Blob image = News.getimage (); InputStream in = Image.getbinarystream (); System.out.println (In.available ()); } @Testpublic void TestproperTyupdate () {News news = (news) Session.get (News.class, 1); News.settitle ("AAAA"); System.out.println (News.getdesc ()); System.out.println (News.getdate (). GetClass ()); } @Testpublic void Testidgenerator () throws Interruptedexception{news news = new News ("AA", "AA", New Java.sql.Date (New Dat E (). GetTime ()); Session.save (news); Thread.Sleep (5000); } @Testpublic void Testdynamicupdate () {News News = (news) Session.get (News.class, 1); News.setauthor ("Aabcd");} @Testpublic void Testdowork () {session.dowork (new work () {@Overridepublic void execute (Connection Connection) throws SQLException {System.out.println (connection);//Call stored procedure.}}); /** * Evict: Removes the specified persisted object from the session cache */@Testpublic void testevict () {News news1 = (news) Session.get (News.class, 1); News news2 = (news) Session.get (News.class, 2); News1.settitle ("AA"); News2.settitle ("BB"); Session.evict (NEWS1); }/** * Delete: Performs the delete operation. As long as the OID is corresponding to a record in the datasheet, the delete operation is prepared * If the OID does not have a corresponding record in the data table, an exception is thrown * * can be set by setting Hibernate profile Hibernate.use_identifier_rollbACK is true, * causes the OID to be set to NULL after the object is deleted */@Testpublic void Testdelete () {//news news = new News ();//news.setid (11); News news = (news) Session.get (News.class, 163840); Session.delete (news); SYSTEM.OUT.PRINTLN (news);} /** * Note: * 1. If the OID is not NULL, there are no records in the datasheet that correspond to it.  Throws an exception. * 2. Understand: The OID value equals the ID of the Unsaved-value property value of the object, also considered to be a free object */@Testpublic void Testsaveorupdate () {News news = new News ("FFF", "FFF" , new Date ()); News.setid (one); Session.saveorupdate (news); }/** * UPDATE: * 1. If you update a persisted object, you do not need to display the call to the Update method. Because the flush method of the session is executed first when the commit () method of the Transaction * is called. * 2. Updating a free object requires an explicit call to the session's Update method. You can turn a free object * into a persistent object * * Note: * 1.  The UPDATE statement is sent regardless of the consistent record of the free object and the data table to be updated. * How can you let the Updat method not blindly start the UPDATE statement? The class node of the. hbm.xml file is set to * select-before-update=true (default = False).  However, you typically do not need to set this property. * * 2. If there is no corresponding record in the datasheet, but the Update method is also called, an exception is thrown * * 3. When the update () method associates a free object, an exception is thrown if a persisted object of the same OID already exists in the cache of the Session. Because in the Session cache * cannot have two OID objects of the same! * */@Testpublic void TestupdatE () {News News = (news) Session.get (News.class, 1); Transaction.commit (); Session.close ();//news.setid (+); session = Sessionfactory.opensession (); transaction = Session.begintransaction ();//news.setauthor ("SUN"); News news2 = (news) Session.get (News.class, 1); Session.update (news); /** * Get VS Load: * * 1.  Executes the Get method: The object is loaded immediately.  * The Load method is executed, and if the object is not applied, the query operation is not performed immediately, and a proxy object is returned * Get is immediately retrieved and load is a deferred retrieval. * * 2. The Load method may throw an Lazyinitializationexception exception: Session * 3 has been closed before initialization of the proxy object is required.   If there is no corresponding record in the data table, the Session is not closed. * Get returns NULL * load if no properties of the object are used, no problem;   Throws an exception if initialization is required. */@Testpublic void TestLoad () {News news = (news) session.load (News.class, 10); System.out.println (News.getclass (). GetName ()); Session.close ();//system.out.println (news); } @Testpublic void Testget () {News News = (news) Session.get (News.class, 1);//session.close (); SYSTEM.OUT.PRINTLN (news); }/** * PERSIST (): The difference between the insert operation * and Save () is also performed: * Before calling the Persist method, if the object already has an ID, the insert is not executed and an exception is thrown */@Testpublic void Testpersist () {News news = new News (); News.settitle ("ee"); News.setauthor ("ee"); News.setdate (new Date ()); News.setid (200); Session.persist (news); }/** * 1. Save () method * 1). Causes a temporary object to become a persisted object * 2). Assigns an ID to an object. * 3). An INSERT statement is sent when the flush cache. * 4). The ID before the Save method is invalid * 5). The ID of the persisted object cannot be modified! */@Testpublic void Testsave () {News news = new News (); News.settitle ("CC"); News.setauthor ("CC"); News.setdate (new Date () ); News.setid (100); SYSTEM.OUT.PRINTLN (news); Session.save (news); SYSTEM.OUT.PRINTLN (news);//news.setid (101); }/** * Clear (): Clean cache */@Testpublic void Testclear () {News news1 = (news) Session.get (News.class, 1); Session.clear (); News news2 = (news) Session.get (News.class, 1);} /** * Refresh (): The SELECT statement is forced to be sent so that the state of the object in the Session cache is consistent with the corresponding record in the data table! */@Testpublic void Testrefresh () {News news = (news) Session.get (News.class, 1); SYSTEM.OUT.PRINTLN (news); Session.refresh (news); SYSTEM.OUT.PRINTLN (news); }/** * Flush: Keeps the records in the data table consistent with the state of the objects in the Session cache. In order to remain consistent, the corresponding SQL statement may be sent. * 1. In Transaction's Commit () Method: First call the session's Flush method, then commit the transaction * 2.  The flush () method may send an SQL statement, but the transaction will not be committed. * 3. Note: the flush () operation is also possible before a transaction is committed or explicitly called by the Session.flush () method. * 1). To perform a HQL or QBC query, the flush () operation is performed first to get the most recent record of the data table * 2).  If the ID of the record is generated using the self-increment method of the underlying database, the INSERT statement is sent immediately when the Save () method is called. * Because after the Save method, the ID of the object must be guaranteed to exist! */@Testpublic void TestSessionFlush2 () {News news = new News ("Java", "SUN", New Date ()); Session.save (news); @Testpublic void Testsessionflush () {News News = (news) Session.get (News.class, 1); News.setauthor ("Oracle");// Session.flush ();//system.out.println ("flush"); News news2 = (news) Session.createcriteria (news.class). Uniqueresult (); System.out.println (NEWS2);} @Testpublic void Testsessioncache () {News News = (news) Session.get (News.class, 1); SYSTEM.OUT.PRINTLN (news); News news2 = (news) Session.get (News.class, 1); System.out.println (NEWS2);}}

Package Com.atguigu.hibernate.entities.n21;import Java.io.fileinputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.sql.blob;import Java.sql.connection;import Java.sql.sqlexception;import Java.util.date;import Org.hibernate.hibernate;import Org.hibernate.lazyinitializationexception;import Org.hibernate.session;import Org.hibernate.sessionfactory;import Org.hibernate.transaction;import Org.hibernate.cfg.configuration;import Org.hibernate.jdbc.work;import Org.hibernate.service.ServiceRegistry; Import Org.hibernate.service.serviceregistrybuilder;import Org.junit.after;import Org.junit.before;import Org.junit.test;public class Hibernatetest {private sessionfactory sessionfactory;private Session session;private Transaction Transaction; @Beforepublic void init () {Configuration configuration = new Configuration (). Configure ();                            Serviceregistry serviceregistry = new Serviceregistrybuilder (). Applysettings (Configuration.getproperties ()) . buildservicerEgistry (); sessionfactory = Configuration.buildsessionfactory (serviceregistry); session = Sessionfactory.opensession (); transaction = Session.begintransaction ();} @Afterpublic void Destroy () {transaction.commit (); Session.close (); Sessionfactory.close ();} @Testpublic void Testdelete () {//In the case that there is no cascading relationship, and the object at this end of 1 has an object of n being referenced, you cannot directly delete the object at the end of the 1 customer customer = (customer) session. Get (Customer.class, 1); Session.delete (Customer); } @Testpublic void Testupdate () {Order order = (order) Session.get (Order.class, 1); Order.getcustomer (). Setcustomername ( "AAA");} @Testpublic void Testmany2oneget () {//1. If you query an object at one end of the multiple, by default, only the object at the end of the query is queried. Without querying the object at the end of the associated//1! Order order = (order) Session.get (Order.class, 1); System.out.println (Order.getordername ()); System.out.println (Order.getcustomer (). GetClass (). GetName ()); Session.close ();//2. The corresponding SQL statement is sent when the associated object needs to be used. Customer customer = Order.getcustomer (); System.out.println (Customer.getcustomername ()); 3. When querying the Customer object, the one end of the 1 is navigated to by one side,//If the session is closed at this time, by default//will be sentRaw lazyinitializationexception Abnormal//4. When you get the Order object, by default, its associated Customer object is a proxy object!} @Testpublic void Testmany2onesave () {Customer customer = new Customer (); Customer.setcustomername ("BB"); Order order1 = New Order (); Order1.setordername ("ORDER-3"); Order Order2 = New Order (); Order2.setordername ("ORDER-4");//  Set the association relationship order1.setcustomer (customer); Order2.setcustomer (customer);//Perform save operation: Insert Customer First, then insert Order, 3 insert//first insert 1 One end of the//session.save, and then inserts an end of N, with only the INSERT statement. (customer);////session.save (order1);//session.save (order2);//First insert Order, then insert Customer. 3 Insert, 2 update//First insert one end of n, and then insert the end of 1, will be more than the UPDATE statement!//because at the end of the insertion of many, cannot determine the foreign key value of the end of 1. So you can only wait for one end of 1 to be inserted, and then send an additional UPDATE statement.//recommend inserting one end of 1, then inserting one end of n Session.save (order1); Session.save (order2); Session.save (Customer) ;}}

Package Com.atguigu.hibernate.entities.n21.both;import Org.hibernate.session;import org.hibernate.SessionFactory; Import Org.hibernate.transaction;import Org.hibernate.cfg.configuration;import Org.hibernate.service.serviceregistry;import Org.hibernate.service.serviceregistrybuilder;import Org.junit.After ; Import Org.junit.before;import Org.junit.test;public class Hibernatetest {private Sessionfactory sessionfactory; Private Session session;private Transaction Transaction; @Beforepublic void init () {Configuration configuration = new Configuration (). Configure ();                            Serviceregistry serviceregistry = new Serviceregistrybuilder (). Applysettings (Configuration.getproperties ()) . Buildserviceregistry (); sessionfactory = Configuration.buildsessionfactory (serviceregistry); session = Session Factory.opensession (); transaction = Session.begintransaction ();} @Afterpublic void Destroy () {transaction.commit (); Session.close (); Sessionfactory.close ();} @Testpublic void Testcascade () {Customer CUStomer = (Customer) session.get (Customer.class, 3); Customer.getorders (). Clear (); @Testpublic void Testdelete () {//In the case that there is no cascading relationship, and the object at this end of 1 has an object of n being referenced, you cannot directly delete the object at the end of the 1 customer customer = (customer) session. Get (Customer.class, 1); Session.delete (Customer); } @Testpublic void TestUpdat2 () {Customer customer = (customer) session.get (Customer.class, 1); Customer.getorders (). Iterator (). Next (). Setordername ("GGG"); } @Testpublic void Testupdate () {Order order = (order) Session.get (Order.class, 1); Order.getcustomer (). Setcustomername ( "AAA");} @Testpublic void Testone2manyget () {//1. Use lazy loading for a collection of one end of n the customer customer = (customer) session.get (Customer.class, 7); System.out.println (Customer.getcustomername ()); 2. Returns a collection of multiple ends when Hibernate is built into the collection type. This type has the ability to delay loading and storing proxy objects. System.out.println (Customer.getorders (). GetClass ()); Session.close ();//3. Lazyinitializationexception exceptions may be thrown System.out.println (Customer.getorders (). Size ()); 4. You need to initialize the elements in the collection again. } @Testpublic void Testmany2oneget () {//1. If you query an object at one end of a multiple, the defaultCase, only the objects at one end of the query are queried. Without querying the object associated with that end of the//1! Order order = (order) Session.get (Order.class, 1); System.out.println (Order.getordername ()); System.out.println (Order.getcustomer (). GetClass (). GetName ()); Session.close ();//2. The corresponding SQL statement is sent when the associated object needs to be used. Customer customer = Order.getcustomer (); System.out.println (Customer.getcustomername ()); 3. When querying the Customer object, the lazyinitializationexception exception//4 will occur by default//If the one end of the multiple is navigated to one end of 1//If the session is closed at this time. When you get the Order object, by default, its associated Customer object is a proxy object!} @Testpublic void Testmany2onesave () {Customer customer = new Customer (); Customer.setcustomername ("AA"); Order order1 = New Order (); Order1.setordername ("ORDER-1"); Order Order2 = New Order (); Order2.setordername ("ORDER-2");// Sets the association relationship order1.setcustomer (customer); Order2.setcustomer (customer); Customer.getorders (). Add (Order1); Customer.getorders (). Add (order2);//Perform the save operation: First insert Customer, then insert Order, 3 inserts, 2 update//because one end of 1 and the other side of N maintain the correlation relationship. So there will be more update//. You can specify inverse=true on the set node at one end of the 1 to give the end of the 1 to the Maintenance association!//it is recommended that set inVerse=true, it is recommended to first insert one end of the 1, and then insert many of the end//benefit is not more than the UPDATE statement session.save (customer);//session.save (order1);//session.save ( ORDER2);//First insert Order, then insert Cusomer, 3 Insert, 4 update//session.save (order1);//session.save (order2);////session.save ( customer);}}

Omit the entity class and the corresponding configuration file for testing, because these files are transformed according to the different business.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.