Hibernate unit test framework

Source: Internet
Author: User

Hibernate is very uncertain when writing database configuration files. It is necessary to perform necessary tests to ensure the correctness of the database structure. Therefore, junit can be used for testing.

It is very easy to use junit. eclipse only needs to right-click the project to create a junit test case (enter the class name and package name ). Then, write the corresponding code at the corresponding location to run the test.

A common hibernate testing framework is provided 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 Configuration = new Configuration (). configure (); Ser ViceRegistry 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 (); pay. setMonthlyPay (1, 1000); pay. setYearPay (1, 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 stre Am = new FileInputStream ("Hydrangeas.jpg"); // Blob image = Hibernate. getLobCreator (session )//. createBlob (stream, stream. 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 Date (). 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 the stored procedure .}});} /*** evict: removes the specified persistent 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: delete an operation. as long as the OID corresponds to a record in the data table, the delete operation is ready. * If the OID does not have a corresponding record in the data table, an exception is thrown. ** you can set the hibernate configuration file hibernate. use_identifier_rollback is true. * after deleting an object, set its OID to null */@ Testpublic void testDelete () {/News 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 corresponding records in the table. an exception is thrown. * 2. understanding: the object whose OID value is equal to the unsaved-value property value of id is also considered as a free object */@ Testpublic void testSaveOrUpdate () {News news News = new News ("FFF ", "fff", new Date (); news. setId (11); session. saveOrUpdate (news);}/*** update: * 1. if you update a persistent object, you do not need to call the update method. when calling the commit () method of Transaction *, the flush method of the session will be executed first. * 2. to update a free object, you must call the update method of the session explicitly. note that you can change a free object * To A Persistent Object **: * 1. The UPDATE statement is sent no matter whether the free object to be updated is consistent with the record of the data table. * How can the updat method not blindly start the update statement? In. hbm. * select-before-update = true (false by default) is set for the class node of the xml file ). however, you do not need to set this attribute. ** 2. if no corresponding record exists in the data table but the update method is also called, an exception is thrown. ** 3. when the update () method is associated with a free object, * If a persistence object with the same OID already exists in the Session cache, an exception is thrown. because in the Session cache, * There cannot be two objects with the same OID! **/@ Testpublic void testUpdate () {News news = (News) session. get (News. class, 1); transaction. commit (); session. close (); // news. setId (100); session = sessionFactory. openSession (); transaction = session. beginTransaction (); // news. setAuthor ("SUN"); News news2 = (News) session. get (News. class, 1); session. update (news);}/*** get VS load: ** 1. run the get method to load the object immediately. * execute the load method. If this object is not applicable, the query operation is not performed immediately, and a proxy object is returned. ** Get indicates instant retrieval, while load indicates delayed retrieval. ** 2. the load method may throw the LazyInitializationException: The Session has been closed before the * proxy object needs to be initialized ** 3. if no corresponding record exists in the data table, the Session is not closed. * get returns null * load. If no attribute of the object is used, no problem occurs. If Initialization is required, an exception is thrown. * // @ 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 (): * before calling the persist method, if the object already has an id, INSERT is not executed, and an exception */@ 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 ). change a temporary object to a persistent object * 2 ). assign an ID to the object. * 3 ). an INSERT statement will be sent during the flush cache. * 4 ). the id before the save method is invalid * 5 ). the ID of the Persistent 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 (): clear 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 forcibly sent to make the status of the objects in the Session cache consistent with the records 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: Make the records in the data table consistent with the status of the objects in the Session cache. to maintain consistency, the corresponding SQL statement may be sent. * 1. in the commit () method of Transaction: First call the flush method of the session, and then commit the Transaction * 2. the flush () method may send SQL statements but does not commit transactions. * 3. note: when a transaction is not committed or the session is called explicitly. before the flush () method, it is also possible to perform the flush () operation. * 1 ). Execute the HQL or QBC query to perform the flush () operation first to obtain the latest record of the data table * 2 ). if the record ID is generated by the underlying database in auto-increment mode, the INSERT statement is immediately sent when the save () method is called. * After the save method, the Object ID must 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. transact Ion; 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 () {policatio N 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 (); sess IonFactory. close () ;}@ Testpublic void testDelete () {// if there is no cascading relationship, and the object at the end of 1 has n objects being referenced, the Customer customer = (Customer) session object at the end of 1 cannot be directly deleted. 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 multiple ends, only objects at multiple ends are queried by default. no associated/queries/ The object at the end of/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 only when the associated object is used. customer customer = order. getCustomer (); System. out. println (customer. getCustomerName (); // 3. when you query a Customer object and navigate from multiple ends to one end, // if the session is closed, the LazyInitializationException will occur by default. // 4. obtain By default, the associated Customer object is a proxy object !} @ Testpublic void testMany2OneSave () {Customer 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); // execute the save operation: insert Customer first, then insert Order, 3 INSERT // INSERT the end of 1 first, then INSERT the end of n, only INSERT statements. // session. save (customer); // se Ssion. save (order1); // session. save (order2); // insert Order first and then Customer. 3 INSERT, 2 UPDATE // INSERT n first, and then INSERT 1, there will be more UPDATE statements! // When multiple ends are inserted, the foreign key value of one end cannot be determined. therefore, an UPDATE statement can only be sent after one end is inserted. // We recommend that you insert one end and n end sessions first. 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 Configuration = new Configuration (). configure (); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder (). applySettings (configuration. getProperties ()). buildServiceRegistry (); sessionFactory = configuration. buildSessionFactory (serviceRegistry); session = sessionFactory. openSession (); t Ransaction = 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 () {// if there is no cascading relationship, and n objects at the end of 1 are being referenced, the Customer customer = (Customer) session object at the end of 1 cannot be directly deleted. get (Customer. class, 1); se Ssion. 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 the delayed loading of Customer customer = (Customer) session for the set at one end of n. get (Customer. class, 7); System. out. println (customer. getCustomerName (); // 2. hibernate built-in set type when multiple end sets are returned. // This type has the function of delaying loading and storing proxy objects. system. out. println (customer. getOrders (). getClass (); // session. close (); // 3. the System may throw a LazyInitializationException. out. println (customer. getOrders (). size (); // 4. initialization is required when elements in the set are used .} @ Testpublic void testMany2OneGet () {// 1. if you query an object at multiple ends, only objects at multiple ends are queried by default. no associated query // The object at the end of 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 only when the associated object is used. customer customer = order. getCustomer (); System. out. println (customer. getCustomerName (); // 3. when you query a Customer object and navigate from multiple ends to one end, // if the session is closed, the LazyInitializationException will occur by default. // 4. obtain By default, the associated Customer object is a proxy object !} @ Testpublic void testMany2OneSave () {Customer customer Customer = new customer (); Customer. setCustomerName ("AA"); Order order1 = new Order (); order1.setOrderName ("ORDER-1"); Order order2 = new Order (); order2.setOrderName ("ORDER-2"); // set the association relationship order1.setCustomer (customer); order2.setCustomer (customer); customer. getOrders (). add (order1); customer. getOrders (). add (order2); // execute the save operation: First INSERT Customer, then INSERT Order, 3 INSERT, Two updates // because one end of 1 maintains an association with the other end of n. so there will be more updates // you can specify inverse = true on the set node at the end of 1, so that the end of 1 will not maintain the association relationship! // We recommend that you set inverse to true. We recommend that you first insert one end, and then insert multiple ends. // The advantage is that there will be no more UPDATE statement sessions. save (customer); // session. save (order1); // session. save (order2); // INSERT Order first, then Cusomer, 3 INSERT, 4 UPDATE // session. save (order1); // session. save (order2); // session. save (customer );}}

The entity class and corresponding configuration files used in the test are omitted, because these files need to be transformed according to different services.


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.