Home > Java > javaTutorial > body text

A brief introduction to using SQL statements in Java's Hibernate framework

高洛峰
Release: 2017-01-23 11:32:54
Original
1155 people have browsed it

There is HQL query syntax in Hibernate. But we are more familiar with SQL statements, so how should we make Hibernate support SQL? We don’t need to think about this, the Hibernate team has already done it.
Without further ado, let’s give an example.

select * from t_user usr
Copy after login
Copy after login

The above is a SQL statement, which is nonsense. Everyone knows it. We want Hibernate to execute this statement, what should we do? Look at the code:

Query query = session.createSQLQuery("select * from t_user usr");
Copy after login

That’s it, everyone should know the rest, ordinary queries.
After querying, what is returned?

while(iter.hasNext()){
 Object[] objs = (Object[])iter.next();
 for (int i = 0; i < objs.length; i++) {
 System.out.print(objs[i]);
 }
 System.out.println();
}
Copy after login

all The results of the return are Object [] array,

At this time someone ran out and said that the object -oriented object. Yes, it is object-oriented, alas, there is no way.
Let’s continue watching:

select {usr.*} from t_user usr
Copy after login

Seeing this, I guess some children’s shoes are starting to stir. What are those braces?
Don’t rush, take your time. Let's continue looking at the code first.

Query query = session.createSQLQuery("select {usr.*} from t_user usr").addEntity(TUser.class);
Copy after login

We see that the difference from before is that we added an addEntity. What does it mean?
We went directly to the API and saw a series of explanations like this:

addEntity
SQLQuery addEntity(String tableAlias,
   Class entityType)
Declare a "root" entity
Parameters:
tableAlias - The SQL table alias
entityType - The java type of the entity to add as a root
Copy after login

It’s not the same thing, but it’s a piece of cake. You can only use it yourself.
The first parameter refers to the alias of the table. Just like the above statement, the alias of our table is usr, so the first parameter is usr, and the second parameter refers to which class the query result needs to be mapped to. Here, since we map TUser to the t_user table in the mapping file, of course we have TUser here. Then when I checked, a SQL statement came out, and the result was of type TUser.
The result we found is:

org.hibernate.tutorial.domain6.TUser@198cb3d
Copy after login

Of course, yours must be different from mine. Don't move.

Maybe we don’t need to find out all of them. At this time, all we need is to set the alias:

select u.id as {usr.id},u.name as {usr.name},u.age as {usr.age} from t_user u
Copy after login

We see that we use as designation After removing the alias of the field, the program is still the same:

Query query = session.createSQLQuery("select u.id as {usr.id},u.name as {usr.name},u.age as {usr.age} from t_user u").addEntity("usr",TUser.class);
Copy after login

This is simple, not much to say.

We mentioned before that some teams will stipulate not to write SQL statements in the code, which requires configuration files.
We can add in the configuration file:

<sql-query name="queryTUser">
 <return alias="usr" entity-name="org.hibernate.tutorial.domain6.TUser" />
 select {usr.*} from t_user usr where name=:name
</sql-query>
Copy after login

Note that the entity-name here needs to be the complete package name, otherwise an error will be reported. Here we have the subtag return, which specifies the alias and class name of the table so that we don't need to addEntity at runtime.
Look at the code:

Query query = session.getNamedQuery("queryTUser");
query.setParameter("name","shun");
List list = query.list();
Iterator iter = list.iterator();
Copy after login


We can just do this. Note that we did not add addEntity, mainly due to the configuration in the configuration file.
Note that if configured in the configuration file, there must be a return subtag specifying the table alias and class name. This is mainly to avoid repeated judgments when we read statements.


We have been talking about tables with aliases for so long. So if our table does not have an alias, but we want to encapsulate the returned results in an object, what should we do?

select * from t_user usr
Copy after login
Copy after login

It's very simple, just call the overloaded method addEntity(Class clazz) of addEntity. You only need to provide a class name without the need for a table alias.

Of course, hibernate also supports stored procedures. You only need to set the callable attribute of sql-query to true in the configuration file, which means that the stored procedure is currently being called. Since I don’t have much exposure to stored procedures, I will do more in the future. Study it and then study it with everyone.

When we call session.save and other corresponding data manipulation methods, it will be converted into hibernate's built-in SQL statement, but what if we want to control the format of the SQL statement ourselves?
Hibernate actually thought of it too.
We add it directly to the mapping file:

<sql-insert>
 INSERT INTO T_USER (NAME,AGE) values (?,?)
 </sql-insert>
 <sql-update>
 UPDATE USER SET USER_NAME=?,AGE=? WHERE uSER_ID=?
</sql-update>
Copy after login

Note that this needs to be added within the class tag as a subtag. We use all capital letters here to distinguish them from hibernate's default statements, and have no other meaning.
Let’s first take a look at the insert call:

User user = new User();
user.setName("shun123123");
user.setAge(23);
Copy after login

When we call save, hibernate’s statement is:
Hibernate:

INSERT INTO USER(USER_NAME,AGE) values(?,?)
Copy after login

It calls the statement in the sql-insert tag we configured
Let’s take a look at the update call:

User user = (User)session.get(User.class,new Long(29));
user.setName("shun123123");
user.setAge(23);
session.save(user);
Copy after login

When we call save, it will automatically call update , the statement at this time is:
Hibernate:

UPDATE USER SET USER_NAME=?,AGE=? WHERE uSER_ID=?
Copy after login

We see that the output statement is in uppercase, which means that the statement we configured is called.

The delete statement is also configured in the same way.

For more brief introduction to using SQL statements in Java's Hibernate framework, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!