A brief introduction to using SQL statements in the Hibernate framework for Java

  • 2020-04-01 04:33:50
  • OfStack

Hibernate has an HQL query syntax. However, we are still familiar with SQL statements, so how to get Hibernate to support SQL? We don't need to think about this, the Hibernate team has already done it.
            Don't talk nonsense, straight to the example.


select * from t_user usr 

 
    Above is a SQL statement, again nonsense, is everyone knows. What if we want Hibernate to execute this statement? Look at the code:


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

    And that's it. The rest of it, you should know, is a normal query.
              So what is returned after the query?


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

    Each result returned is an Object[] array,
         
              Then someone came out and said object orientation. Yeah, it's object oriented. Oh, no way.
              Here we go:


select {usr.*} from t_user usr 

    See here, some kid's shoes are probably starting to move. What's that curly brace?
      Take your time. So let's go ahead and look at the code.


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

    What we see instead is that we've added an addEntity, so what does that mean?
      We went straight to the API and saw this list of explanations:

 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

            There's no such thing as a cup. You can only use it yourself.
            The first parameter is the alias of the table, just like the statement above, the alias of our table is usr, so the first parameter is usr, and the second parameter is the result of the query need to map to which class, here because we are mapping to t_user table by TUser in the mapping file, so we of course here is TUser. Then look, there is an SQL statement, and the result is of type TUser.
            What we found was:


org.hibernate.tutorial.domain6.TUser@198cb3d 

    Of course, yours is different from mine. Don't move the chicken.
 
      Maybe we don't need to find out all of them, in this case, we just need to set aliases:


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

    We saw that we used as to specify the alias of the field, and it was the same in the program:


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 easy, not much to say.
 
                As we mentioned earlier, some teams have rules against writing SQL statements in their code, which again requires configuration files.
                We can add:

<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 full package name, otherwise an error will be reported. Here we have the child tag return, which specifies the alias and class name of the table, so we don't need addEntity at run time.
      Look at the code:


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

 
    We'll just go ahead and do it. Notice that we didn't add an addEntity, thanks largely to the configuration in the configuration file.
      Note that if configured in a configuration file, there must be a return subtag specifying the table alias and class name. This is mainly to avoid the repetitive judgments we make when reading statements.
   
 
      All this time, we've been talking about tables with aliases, so what if our table doesn't have aliases, but we want to return results encapsulated in an object?


select * from t_user usr 

    Simply call addEntity's overloaded method, addEntity(Class clazz), and provide a Class name instead of 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 current call is a stored procedure. As I have little contact with the stored procedure, I will study more later and study with you.
   
      When we call session.save and other corresponding methods to manipulate the data, 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 figured it out.
      We directly add:


<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 child tag. We here are all uppercase, is to distinguish with hibernate default statement, no other meaning.
      Let's look at the insert call first:


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 inside the sql-insert tag that we configured
Let's look at the call to update again:


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, and the statement is:
Hibernate:  


UPDATE USER SET USER_NAME=?,AGE=? WHERE uSER_ID=? 

    We see that the output statement is capitalized, that is, the statement we configured is called.
 
      The same configuration applies to the delete statement.

Related articles: