Hibernate database operations

Source: Internet
Author: User

Hibernate configuration file: hibernate. cfg. xml (stored in the src directory)

<? Xml version = '1. 0' encoding = 'utf-8'?> <! DOCTYPE hibernate-configuration PUBLIC "-// Hibernate/Hibernate Configuration DTD 3.0 // EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 

Entity class settings student. hbm. xml

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

The load and get methods can only query objects by id

The difference between the two: load uses delayed loading. Only when the object content is used, an SQL statement is issued, while get directly loads data from the database. When querying non-existing data, load reports an error, get returns null. Both get and load query the cache first (level-1 cache). If the cache does not exist, it searches for the database. load also uses level-2 cache, but get won't.

User u1 = (User) session. get (User. class, 2); // If the cache does not exist, an SQL request User u2 = (User) session is sent. load (User. class, 2); System. out. println (u2.getId (); // If the cache does not exist, an SQL request is sent, instead of the previous step.

Save (user): Execute an insert SQL statement at the underlying layer during Session cache cleanup to save the object to the database. When you execute Session. after saving (user), before the Session clears the cache, If you modify the user object attribute value, the value stored in the database will be the last modified value; during this process, the ID cannot be modified;

Delete (user): if the user is a persistent object, the delete operation is performed. Similarly, the underlying database is executed when the Session clears the cache. If the user is a free object: associate the user object with the Session to make it a persistent object, and then execute it according to the process in which the user is a persistent object;

Update (user): After obtaining the object from the database, set directly changes the attribute to be set. Then, when the session is commit, hibernate synchronizes the database by default. If consistency is found, SQL statements that do not send updates will be updated. SQL update statements will be issued only when they are inconsistent. Of course, all fields are updated at this time, and the efficiency is still low;

SaveOrUpdate (Object o); automatically select save or update;

Clear (); is mainly used to clear the session cache. There is no interaction with the database in the middle, and flush is there;

Flush (); force the cache content to be synchronized with the database content. You can set it. By default, the cache content is synchronized only when the session commit is used;

HQL:

Public class HqlTest {private static SessionFactory sessionFactory; private static Session session; @ BeforeClasspublic static void befor () {Configuration cfg = new Configuration (); cfg. configure (); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder (). applySettings (cfg. getProperties ()). buildServiceRegistry (); sessionFactory = cfg. buildSessionFactory (serviceRegistry); session = sessionFactory. get CurrentSession (); // If opensession is used here, no transaction exception or unsaved exception will occur} @ Testpublic void testHQL3 () {session. beginTransaction (); Query q = session. createQuery ("select distinct c from Category c order by name desc"); List <Category> categories = q. list (); for (Category c: categories) System. out. println (c. getName (); session. getTransaction (). commit () ;}@ Testpublic void testHQL4 () {session. beginTransaction (); Query q = session. createQue Ry ("from Category"); List <Category> categories = q. list (); for (Category c: categories) System. out. println (c. getName (); session. getTransaction (). commit () ;}@ Testpublic void testHQL5 () {session. beginTransaction (); Query q = session. createQuery ("from Category c where id>: min and c. id <: max "); // q. setParameter ("min", 2); // q. setParameter ("max", 5); q. setInteger ("min", 2); q. setInteger ("max", 5); // Query q1 = session. cr EateQuery ("from Category c where id>: min and c. id <: max "). setInteger ("min", 2 ). setInteger ("max", 5); List <Category> categories = q. list (); for (Category c: categories) System. out. println (c. getName (); session. getTransaction (). commit () ;}// pagination @ Testpublic void testHQL6 () {session. beginTransaction (); Query q = session. createQuery ("from Category "). setMaxResults (4 ). setFirstResult (2); List <Category> categories = q. list (); For (Category c: categories) System. out. println (c. getName (); session. getTransaction (). commit ();} // only obtain certain fields in a single table @ Testpublic void testHQL7 () {session. beginTransaction (); Query q = session. createQuery ("select c. id, c. name from Category c "); List <Object []> categories = q. list (); for (Object [] o: categories) System. out. println (o [0] + "---" + o [1]); session. getTransaction (). commit ();} // The navigation link @ Test // set ManyToOne to lazy. only c All content in ategory will be queried. The category table public void testHQL8 () {session. beginTransaction (); Query q = session. createQuery ("from Topic t where t. category. id = 1 "); List <Topic> topic = q. list (); for (Topic t: topic) {System. out. println (t. getTitle (); // System. out. println (t. getCategory (). getName ();} session. getTransaction (). commit () ;}@ Test // same as above, navigation relation public void testhqa9 () {session. beginTransaction (); Query q = session. createQuery ("From Msg m where m. topic. category. id = 1 "); List <Msg> msg = q. list (); for (Msg m: msg) {System. out. println (m. getContent (); // System. out. println (t. getCategory (). getName ();} session. getTransaction (). commit () ;}@ Testpublic void testHQL10 () {// is empty not emptysession. beginTransaction (); Query q = session. createQuery ("from Topic t where t. msg is empty "); List <Topic> topic = q. list (); for (Topic t: topic) System. out. p Rintln (t. getTitle (); session. getTransaction (). commit () ;}@ Testpublic void testHQL11 () {// native sqlsession. beginTransaction (); SQLQuery q = session. createSQLQuery ("select * from category "). addEntity (Category. class); List <Category> categories = q. list (); for (Category c: categories) System. out. println (c. getName (); session. getTransaction (). commit () ;}@ AfterClasspublic static void after () {if (sessionFactory! = Null) sessionFactory. close () ;}// the local SQL query can also support connection query. The following program code: String SQL = "select {c. *}, {o. *} from customer c inner join order o where c. id = o. customer_ID "; Query query = session. createSQLQuery (SQL, new String [] {"c", "o"}, new Class [] {Customer. class, Order. class}); List list = query. list (); for (int I = 0; I <list. size (); I ++) {Object objs = (Object []) list. get (I); Customer customer = (Customer) objs [0]; Order order = (Order) o Bjs [1];} // It is worth noting that the result returned by the list () method in the Query code above stores an array of objects, A pair of Customer objects and Order objects are stored in the object array.

Configuration file (hibernate. properties or hibernate. cfg. xml) and ing file (. hbm. xml)

<? Xml version = '1. 0' encoding = 'utf-8'?>
<! DOCTYPE hibernate-configuration PUBLIC
"-// Hibernate/Hibernate Configuration DTD 3.0 // EN"
Http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd>
<Hibernate-configuration>

<Session-factory>

<! -- Database connection settings -->
<Property name = "connection. driver_class"> com. mysql. jdbc. Driver </property>
<Property name = "connection. url"> jdbc: mysql: // localhost/train </property>
<Property name = "connection. username"> root </property>
<Property name = "connection. password"> </property>

<! -- JDBC connection pool (use the built-in) -->
<Property name = "connection. pool_size"> 1 </property>

<! -- SQL dialect -->
<Property name = "dialect"> org. hibernate. dialect. MySQL5Dialect </property>

<! -- Enable Hibernate's automatic session context management -->
<Property name = "current_session_context_class"> thread </property>

<! -- Disable the second-level cache -->
<Property name = "cache. provider_class"> org. hibernate. cache. internal. NoCacheProvider </property>

<! -- Echo all executed SQL to stdout -->
<Property name = "show_ SQL"> true </property>
<Property name = "format_ SQL"> true </property>
<Property name = "hbm2ddl. auto"> validate </property>
<Mapping class = "com. struts2.domain. Message"/>
<Mapping class = "com. struts2.domain. User"/>
</Session-factory>
</Hibernate-configuration>

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.