Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the basic uses of Hibernate

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the basic uses of Hibernate". Friends who are interested may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what are the basic uses of Hibernate.

Basic Hibernate data query

It is a simple thing to use Hibernate data query. Java programmers can query data in the way of object operation, and use a HQL (Hibernate Query Language) similar to SQL to set the query conditions. Unlike SQL, HQL is a language with object-oriented inheritance, polymorphism and other characteristics. Directly use the example to see how to query the database using Hibernate. Before that, please add a few pieces of data to the database according to the previously introduced topic: when we add data query data in Hibernate, we use the find () method of Session, and specify HQL to set the query conditions. The query results will be loaded and returned in the List object. All you need is to take them out one by one. The simplest example is as follows:

HibernateTest.java

Import onlyfun.caterpillar.*;import net.sf.hibernate.*;import net.sf.hibernate.cfg.*;import java.util.*; public class HibernateTest {public static void main (String [] args) throws HibernateException {SessionFactory sessionFactory = new Configuration (). Configure (). BuildSessionFactory (); Session session = sessionFactory.openSession (); List users = session.find ("from User"); session.close (); sessionFactory.close (); for (ListIterator iterator = users.listIterator (); iterator.hasNext () ) {User user = (User) iterator.next (); System.out.println (user.getName () + "\ n\ tAge:" + user.getAge () + "\ n\ tSex:" + user.getSex ());}

The "from User" in find (), that is, HQL,User refers to the User category. Through the mapping file, it will query the data in the USER table, which is equivalent to SELECT * FROM USER in SQL. In fact, our User category is located under onlyfun.caterpillar, and Hibernate will automatically check whether the package name in import matches the category name. You can also specify the package name directly, for example:

Session.find ("from onlyfun.caterpillar.User")

The result of this program may be as follows:

Log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment). Log4j:WARN Please initialize the log4j system properly.Hibernate: select user0_.user_id as user_id, user0_.name as name, user0_.sex as sex, user0_.age as age from USER user0_caterpillarAge: 28Sex: MmomorAge: 25Sex: FBushAge: 25Sex: MBeckyAge: 35Sex: F

The query described above is the simplest, only querying all the data from the data table. The data queried by Hibernate is returned as an object to meet the needs of operation in the program. We can also limit some query conditions and return only the fields we specify, such as:

List names = session.find ("select user.name from User as user where age = 25"); for (ListIterator iterator = names.listIterator (); iterator.hasNext ();) {String name = (String) iterator.next (); System.out.println ("name:" + name);}

HQL in find () demonstrates a conditional query, and User as user has an alias for the User category, so we can use user.name to specify the table return field. Where is equivalent to the WHERE clause in SQL. We limit the data in which the query age is equal to 25. This time, the query data has only one field and the type is String, so the returned List content is all String objects. A running example is as follows:

Log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment) .log4j:WARN Please initialize the log4j system properly.Hibernate: select user0_.name as x0room0 _ from USER user0_ where (age=25) name: momorname: Bush

If you want to return more than two fields, which is not a problem, let's take a look at an example:

List results = session.find ("select user.name, user.age from User as user where sex ='F'"); for (ListIterator iterator = results.listIterator (); iterator.hasNext ();) {Object [] rows = (Object []) iterator.next (); String name = (String) rows [0]; Integer age = (Integer) rows [1]; System.out.println ("name:" + name + "\ n\ t" + age);}

From the above program, it is not difficult to see that when more than two fields are returned, each time ListIterator will return a piece of data as an Object array. We only need to specify the array index and convert it to the appropriate type to get the data. The result of a query is as follows:

Log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment) .log4j:WARN Please initialize the log4j system properly.Hibernate: select user0_.name as x0mm 0, user0_.age as x1mm 0 _ from USER user0_ where (sex='F') name: momor25name: Becky35

You can also use some functions in HQL for result statistics, such as:

List results = session.find ("select count (*), avg (user.age) from User as user"); ListIterator iterator = results.listIterator (); Object [] rows = (Object []) iterator.next (); System.out.println ("number of data pens:" + rows [0] + "\ naverage age:" + rows [1]))

The result of a query is as follows:

Log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment) .log4j:WARN Please initialize the log4j system properly.Hibernate: select count (*) as x0mm, avg (user0_.age) as x1mm 0 _ from USER user0_ number of pens: 4 average age: 28.25

Unsaved-value

Values that can be set include:

◆ any-always save

◆ none-always updated

Save when ◆ null-id is null (default)

◆ valid-id is stored when it is null or when a value is specified

Once this is set, you can use session.saveOrUpdate (updated); instead of the session.update (updated); method of the previous program.

If you want to delete data, just use the delete () method, just look at an example.

HibernateTest.java

Import onlyfun.caterpillar.*;import net.sf.hibernate.*;import net.sf.hibernate.cfg.*;import java.util.*;public class HibernateTest {public static void main (String [] args) throws HibernateException {SessionFactory sessionFactory = new Configuration (). Configure (). BuildSessionFactory (); Session session = sessionFactory.openSession (); List users = session.find ("from User"); User updated = null;for (ListIterator iterator = users.listIterator (); iterator.hasNext ();) {User user = (User) iterator.next () If (updated = = null) updated = user; System.out.println (user.getName () + "\ n\ tAge:" + user.getAge () + "\ n\ tSex:" + user.getSex ());} session.delete (updated); users = session.find ("from User"); session.close (); sessionFactory.close (); for (ListIterator iterator = users.listIterator (); iterator.hasNext ();) {User user = (User) iterator.next () System.out.println (user.getName () + "\ n\ tAge:" + user.getAge () + "\ n\ tSex:" + user.getSex ();}

An example of an execution result is as follows:

Log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment). Log4j:WARN Please initialize the log4j system properly.Hibernate: select user0_.user_id as user_id, user0_.name as name, user0_.sex as sex, ser0_.age as age from USER user0_justinAge: 28Sex: MmomorAge: 25Sex: FBushAge: 25Sex: MBeckyAge: 35Sex: FHibernate: delete from USER where user_id=?Hibernate: select user0_.user_id as user_id, user0_.name as name, user0_.sex as sex Ser0_.age as age from USER user0_momorAge: 25Sex: FBushAge: 25Sex: MBeckyAge: 35Sex: FUser user = (User) session.load (User.class, id)

Hibernate relies on the id value to determine the update and deletion of data. If you know the id value, you can use the load () method to load the data.

At this point, I believe you have a deeper understanding of "what are the basic uses of Hibernate?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report