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
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");
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(); }
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
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);
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
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
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
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);
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>
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();
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
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>
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);
When we call save, hibernate’s statement is:
Hibernate:
INSERT INTO USER(USER_NAME,AGE) values(?,?)
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);
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=?
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!