Preface

ORM Framing is not a new topic , It has been with us for many years . It provides a conceptual framework 、 Easy to understand data models , A good mapping relationship is established between the tables in the database and the objects in the memory . stay Java Commonly used ORM There are two main frameworks :Hibernate and iBatis. This article mainly introduces Hibernate How to use , There will be an introduction later iBatis The article .

Conventional MVC Development mode

*
  1. M:Model Include pojo、service、dao.

  2. V:View  Include jsp、html、 Module engine .

  3. C:Controll  Include Our technology of dynamic network resources :Servlet.

*

SSH The role of frameworks in development

*
  • S:Struts/SpringMVC:  It's actually the problem with our controller ( It can be simply said that Servlet Encapsulation ).

  • Spring:  Integrate the rest of the third party framework , Is to  Srvice  Layer provides transactions .

  • Hibernate: In fact, that is DAO Layer solution .

*

You can also look at the rest of the framework (SSM、SSS) The meaning of :

Hibernate What is it?

  1. Hibernate It's a non intrusive ORMapping frame

*

Non intrusive framework : When we use this framework , There is no need to inherit or implement classes or interfaces in this framework , This type of framework is called non intrusive framework , The non intrusive framework is better decoupled from the original framework when it is used

Intrusive frames : When we use this framework , We need to inherit or implement some classes or interfaces in this framework , This kind of framework is called intrusive framework

*
  1. ORMapping analysis

*

O:Object

R:Relation

M:Mapping mapping

  1. Hibernate To be able to Java Objects are mapped to databases through mapped relationships

  2. Hibernate Be able to map database data to Java object

*

Hibernate Is to be able to operate Java Object to achieve the operation of a database technology .


Hibernate Can do

To put it simply : Realize all operations of the database (CRUD), It's the original DAO A solution for layer , It's also an alternative .

Hibernate Simple use

「 Easy to use :」

  • Guide pack , Will download the required+jpa Put the related packages in a file

  • stay src Create below hibernate.cfg.xml The configuration file

 <?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
    <session-factory>
        <!-- The driver -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- Access to the URL-->
        <property name="hibernate.connection.url">jdbc:mysql:///qianyu</property>
        <!-- user name -->
        <property name="hibernate.connection.username">root</property>
        <!-- password -->
        <property name="hibernate.connection.password">root</property>
        <!-- dialect   It means to tell Hibernate The framework is currently   You're going to generate the SQL sentence -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <!-- Create table automatically   create: It means every time   They're all newly created   update: It means   If there is, don't create   Create without -->
        <property name="hibernate.hbm2ddl.auto">update</property>
        
        
        <!-- Configuration mapping file -->
        <mapping resource="com/qy/helloworld/User.hbm.xml"/>
        
    </session-factory>
 
</hibernate-configuration>

  • establish Java Object of class

 public class User implements Serializable{
 private static final long serialVersionUID = -6949433888868762441L;
 private int uId;
 
 private String userName;
 
 private String userPwd;
 public User(int uId, String userName, String userPwd) {
  super();
  this.uId = uId;
  this.userName = userName;
  this.userPwd = userPwd;
 }
 public User() {
  super();
 }
 public int getuId() {
  return uId;
 }
 public void setuId(int uId) {
  this.uId = uId;
 }
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 public String getUserPwd() {
  return userPwd;
 }
 public void setUserPwd(String userPwd) {
  this.userPwd = userPwd;
 }
 @Override
 public String toString() {
  return "User [uId=" + uId + ", userName=" + userName + ", userPwd=" + userPwd + "]";
 }
 
}

  • Writing test classes

@Test
 public void testHelloWord() throws Exception {
  // Import profile
  Configuration cfg=new Configuration().configure("hibernate.cfg.xml");
  // establish SessionFactory object
  SessionFactory sf=cfg.buildSessionFactory();
  // Create a session
  Session session=sf.openSession();
  // Open transaction
  session.beginTransaction();
  // Action object
  
  User user=new User(1," Small feather ","110");
  
  // Start the operation
  session.save(user);
  
  // Commit the transaction
  
  session.getTransaction().commit();
  
  session.close();
 
 }

  • Hibernate Medium hibernate.cfg.xml Details of configuration file

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
    <!-- Configure the connection information of our database -->
    <session-factory>
        <!-- The driver -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- Access to the URL-->
        <property name="connection.url">jdbc:mysql:///qianyu</property>
        <!-- user name -->
        <property name="connection.username">root</property>
        <!-- password -->
        <property name="connection.password">root</property>
        
        
        <!-- dialect   It means to tell Hibernate The framework is currently   You're going to generate the SQL sentence -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <!-- Create table automatically   create: It means every time   They're all newly created   update: It means   If there is, don't create   Create without -->
        <!--create Often used in test environments -->
        <property name="hbm2ddl.auto">update</property>
        <!-- The execution will be SQL The sentence is displayed -->
        <property name="show_sql">true</property>
        <!-- Format this SQL sentence -->
        <property name="format_sql">true</property>
          
        <!-- Configuration mapping file    The configuration is for the mapping file -->
       <mapping resource="com/qy/helloworld/User.hbm.xml"/> 
       
       <!-- When you use annotations, you use this one -->
       <!--  <mapping package="com.qy.helloworld"/> -->
        
    </session-factory>
 
</hibernate-configuration>

  • Hibernate Of xxx.hbm.xml Details of configuration file

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!--package: In general, it needs to be configured    You can not configure   however   Now you're going to write the full path   auto-import="true": If it is not configured, the full path of the class must be written when querying -->
<!--default-lazy: Configure whether the whole entity supports lazy loading    Lazy loading is supported by default -->
<hibernate-mapping package="com.qy.helloworld" default-lazy="true" auto-import="true">
    <!-- The mapping relationship is configured below     take JAVA object   Map directly to the database table
         name: Represents the name of the class
         table: It means the current one JAVA class   What is the name of the table in the corresponding database   This name can be written freely   But it's usually about names
         lazy: At present, when this class performs query operation    To do lazy loading
    -->
 <class name="User" table="t_user"  lazy="true">
 
     <!--
         id: Represents the mapping of primary keys
         name: The name of the primary key in the class
         column: The field of the table corresponding to the primary key
         length: Determine the maximum length of the current field
         type: type ( Is written JAVA Full path of data type in )
         
                   Be careful : Type can be omitted : The omitted type is consistent with the type in the entity
              length: It can be omitted    The default is int The maximum range of   
              column: This can also be omitted   The default is the same as in the class   
         
     -->
  <id name="uId">
      <!-- The primary key grows by itself
      
                    The point above is to remember
          identity: Self growth means : The self growth strategy will be selected according to the underlying database
          assigned: Set this by yourself id Value
          foreign: This means that you want to use someone else's primary key as your own
          uuid: adopt uuid To generate id Primary key  
          
                   Here's how to learn
          increment: Increasing ( This has something to do with the database )
          native: It's incremental ( It's related to the dialect of the underlying database )
          sequence: This represents the completion of the next... Through a sequence of tables id Generation (Oracle database )
       
      -->
   <generator class="identity"/>
  </id>
  
  <!-- The following is a mapping of common attributes
       length: Length of string
       not-null: The current field cannot be empty
       type: type
  -->
  <property name="userName" column="userName" length="20" not-null="true"/>
  <property name="userPwd" length="20" not-null="true" type="java.lang.String"/>  
 </class>
</hibernate-mapping>

  • Hibernate Medium CRUD The implementation of the

 Add data
    session.save(user);  
  session.persist(user);
Modifying data
        session.beginTransaction(); 
  // Query data ( Positive loading )
  User user=session.get(User.class,1);
  // Lazy loading is supported below
  user.setUserName("xxxxx");
  user.setUserPwd("yyyyy");
  session.getTransaction().commit();
Data query
        // Query data ( Positive loading )
  User user=session.get(User.class,1);
  // Lazy loading is supported below
  User user2=session.load(User.class,1); 
    Delete data
       // Query data ( Positive loading )
  User user=session.get(User.class,1);
  session.delete(user);

  • Hibernate In the help class writing

public class HibernateUtils {
 private static Configuration cfg=null;
 private static SessionFactory sf=null;
 private static ThreadLocal<Session> threadLocal=null;
 static{
  // Initializes the local variables of the thread
  threadLocal=new ThreadLocal<Session>();
  // Load profile
  cfg=new Configuration().configure("config/hibernate.cfg.xml");
  // Build our factory
  sf=cfg.buildSessionFactory();
 }
 
 /**
  *  obtain session How to play
  * @Title: getSession   
  * @Description: TODO
  * @param: @return      
  * @return: Session      
  * @throws
  */
 public static Session getSession(){
   Session session=threadLocal.get();
   if(null==session){
    session=sf.openSession();
    session.beginTransaction();
    threadLocal.set(session);
   }
   return session;
 }
 
 /**
  *  close Session
  * @Title: close   
  * @Description: TODO
  * @param:       
  * @return: void      
  * @throws
  */
 public static void close(){
  Session session=threadLocal.get();
  if(null!=session){
   session.getTransaction().commit();
   session.close();
   threadLocal.remove();
  }
 }
}

matters needing attention

*
  1. We hibernate.cfg.xml This in the configuration file includes hibernate. You can omit

  2. Why can you query data without opening a transaction ? Because Default Hibernate There is a read-only transaction , Read only transaction can complete the operation of reading data , If you want to complete the addition, deletion and modification, you need to read and write transactions , At this time, you need to open the transaction

*

Save and Persist The difference between

*
  • Save When saving data , If id It's self growth , You give id And not given id Are all right .

  • Persist When saving data , If id It's self growing , You give id It's a mistake .

*

Conclusion

This article is about Hibernate This is the end of the introduction , There will be more about Hibernate More articles in series , Thank you for your support !

Previous recommendation

Spring Data Development Manual | Hand in hand teaching you to simplify persistence layer development

Spring Data Development Manual |Java Persistence API(JPA) How much do you need to know ?

Dynamic resource technology JSP|Java And Html The beautiful meeting of

Whether can food | The technology is more and more new , I love my old friends jQuery Or love it as always

Farewell to praying programming | Unit test the correct landing position in the project

Component must know must know | The wheels we used for years —Filter and Proxy

ES Development of guidelines | How to get started quickly ElasticSearch

Get along well with Redis| Learn this 10 I'll let you take it every minute Redis, Satisfy all your doubts

If you think that asamura's article will help you , Please search and follow on wechat 「 Shallow feathered IT hut 」 WeChat official account , I'll share my computer information knowledge here 、 Theoretical Technology 、 Tool resources 、 The software is introduced 、 The backend development 、 interview 、 A series of articles, such as thoughts on work and some thoughts on life . What you see and what you get , It's all about life . take your time , Work harder , You and I grew up together ...

 

Point a praise , Prove that you still love me