Hibernate--core configuration

Core API:
 PO objects: Persistent Objects, persistent objects, hibernate is used to operate persistent objects, each persistent object has a mapping file
 VO value object value object, generally used for web layer
 BO business object business object, generally used for service Layer
 PO Persistent object, generally used for dao layer
--- comprehensive name: JavaBean
 OID: Each PO object has a unique identifier, which is used by hibernate to distinguish PO objects.
 Java distinguishes between objects: the addresses are different, if two objects are new, java is different.
 hibernate po object: use OID to distinguish, in time new two objects, as long as the OID value is the same, hibernate considers it to be an object.
 OID is used to store the primary key value in the table.

Core configuration file:
hibernate.cfg.xml , the xml file can configure more content.
hibernate.properties, the content must be k/v, and the key cannot be repeated. Generally not used.
 Reference file: \hibernate-distribution-3.6.10.Final\project\etc\ hibernate.properties
Configuration: Constructor: new Configuration(), which will automatically load the hibernate.properties file
load configuration The main configuration file method
 configure() is used to load hibernate.cfg.xml under src, [commonly used]; configure(String) can load the custom main configuration file under the specified location,
load the mapping file method
config.addResource(“booming/xxx.hbm.xml”) load the xml file ;config.addClass(User.class) Load the class corresponding to the xml file
Note: only one of the three hibernate.cfg.xml <mapping>, addResource and addClass can be used.
Code:
//1 Load the configuration file
  Configuration config = new Configuration().configure();
  // * If the hibernate.cfg.xml configuration <mapping> also loads the mapping file.
  // * There is no configuration map, it needs to be loaded manually
  // Method 1: Load the xml configuration file, equivalent to <mapping resource="cn/xxx/a_hello/User.hbm.xml"/>
  //config.addResource("cn/xxx/a_hello/User.hbm.xml" );
  // Method 2: Load the mapping corresponding to the specified class
  config.addClass(User.class);

SessionFactory:
The Configuration object generates a SessionFactory object according to the current configuration information. The SessionFactory
object saves the current database configuration information and all mapping relationships and predefined SQL statements. The
SessionFactory object is thread-safe. The session factory provides a session (connection) to hibernate, after which the sessionfactory only needs to provide an instance. Thread safety does not have the problem of concurrent access by threads. (The bottom layer uses ThreadLocal to share data between threads)
In general, in order to ensure that the entire program has only one factory, a tool class is provided to initialize the factory.

Session:
Equivalent to the Connection connection in JDBC.
Session is a single-threaded object for the interaction between the application and the database. It is the center of Hibernate's operation.
Session is not thread-safe, and there is a problem of concurrent access to threads. [Avoid using member variables].
All persistent object POs must be managed under the session management before they can perform persistent operations.
 PO objects only have the characteristics of PO objects when they are bound to the session.
The Session object has a level one cache for caching PO objects.
Method 1: openSession() new session
  Configuration config = new Configuration().configure();
  SessionFactory factory =config.buildSessionFactory();
  // Method 1: Open a new session Session
  Session session = factory.openSession();
  Session session2 = factory.openSession();
  System.out.println(session == session2);//false
Method 2: getCurrentSession() To get a local thread, you need to bind the session to the local thread
 Configuration config = new Configuration().configure ();
  SessionFactory factory =config.buildSessionFactory();
  //Method 2: Get the session bound in the local thread (share the session in a thread)
  // * Note: If you want to use getCurrentSession(), you must configure the
  Session session in hibernate.cfg.xml = factory.getCurrentSession();
  Session session2 = factory.getCurrentSession();
  System.out.println(session == session2); //true
hibernate.cfg.xml configuration:
<!-- Bind session to local thread, Fixed writing -->
<property name="hibernate.current_session_context_class">thread</property>
session needs to be closed, session.close();

Transaction:
open transaction: conn.setAutoCommit(false);
 commit transaction: conn.commit()
 rollback transaction: conn.rollback();
transaction object representing database operation

The way to submit a transaction:
provide variables:
Configuration config = new Configuration().configure();
  SessionFactory factory =config.buildSessionFactory();
  Session session = factory.openSession();
  //Open transaction
  Transaction transaction = session.beginTransaction() ;
  //Commit transaction
  transaction.commit();
  //or rollback transaction
  //transaction.rollback();
  session.close();
use getTransaction() method:
Configuration config = new Configuration().configure();
  SessionFactory factory =config.buildSessionFactory();
  Session session = factory.openSession();
  try {
   //Open the transaction
   session.beginTransaction();  
   //.........
   //Submit the transaction
   session.getTransaction().commit();
  } catch (Exception e) {
   //Review
   session.getTransaction().rollback();
  }
  session.close();
CRUD:
save() save
update() update
saveOrUpdate (...) save or update
delete delete
get query by id
createQuery(...).list() query all
Session session = factory.openSession();
  session.beginTransaction();
  
  // * createQuery("hql statement" )
  // * hql statement: hibernate query language, hibernate query statement, object-oriented query statement
  // ** Compared with sql statement: hql uses class name and attribute name, sql uses table name and field name.
  // ** Note: By default, the property names of the class are the same as the fields of the table.
  Query query = session.createQuery("from User");
  //Query all
  List<User> allUser = query.list();
  for (User user : allUser) {
   System.out.println(user);
  }
  session.getTransaction().commit();
  session.close();
paging
query.setFirstResult()
query.setMaxResults()
Session session = factory. openSession();
  session.beginTransaction();
  //Pagination
  // * mysql --> select ... from limit to start indexing, the number displayed per page
  Query query = session.createQuery("from User");
  // * * Set paging data -- the first page
  // 1) Start index
  query.setFirstResult(2); //The first page 0, the second page 2
  // 2) The number of displays per page
  query.setMaxResults(2); / /First page 2 , second page 2
  List<User> allUser = query.list();
  for (User user : allUser) {
   System.out.println(user);
  }
  session.getTransaction().commit();
  session.close();
qbc:session.createCriteria(User.class).list()
Session session = factory.openSession();
  session.beginTransaction();
  //QBC : query by criteria , hibernate提供纯面向对象查询方式。
  // * Criteria 和 Query 提供api相同的
  Criteria criteria = session.createCriteria(User.class);
  criteria.setFirstResult(0);
  criteria.setMaxResults(2);
  List<User> allUser = criteria.list();
  for (User user : allUser) {
   System.out.println(user);
  }
  session.getTransaction().commit();
  session.close();

Detailed explanation of the main configuration file:
<session-factory>
  <!-- 1. Basic 4 items-->
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name=" hibernate.connection.url">jdbc:mysql://localhost:3306/h_day01_db</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.connection.password" >1234</property>
  
  <!-- 2 Bind session to local thread-->
  <property name="hibernate.current_session_context_class">thread</property>
  
  <!-- 3 dialect, dialect + mapping file provides how hibernate Survival sql statement (query statement)
   * The dialect configured is the different implementation classes of hibernate hibernate3.jar/org/hibernate/dialect
  -->
  <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
  
  <!-- 4 sql display, formatting -->
  <property name="hibernate.show_sql">true</property>
  <property name="hibernate.format_sql">true</property>
  
  <!-- 5 How to generate tables, which are automatically created by hibernate.
   Use in learning, not in development. When developing, create a table first, and then write the configuration hbm file
    create-drop. When running the program, delete the table first. When the table is created, if the factory.close() is called at the end of the program, the table will be automatically deleted. [Test]
    create , when running the program, delete the table first and then create the table, when the program ends, the table is not deleted. []
    update , if the table does not exist will create the table, if the table exists will update the table. Only responsible for adding, not responsible for deleting. 【】
    validate, when the program starts to run, check whether the configuration file hbm and table fields match, if they match, it runs normally. An exception will be thrown if there is no match. [Test]
  -->
  <property name="hibernate.hbm2ddl.auto">update</property>
  <!-- 6 Cancel bean verification: If you use a web6.0 project, an exception will be thrown when you right-click to run the program (null pointer , hint: no bean validation factory) -->
  <property name="javax.persistence.validation.mode">none</property>
  <!

 </session-factory>
Persistent object configuration:
<!--
  <hibernate-mapping>
   package is used to determine the package
    <hibernate-mapping package="cn.xxx.e_hbm">
     <class name="Person" table="t_person ">
  <class> Configure the relationship between class and table
   name: The class name
    generally uses the fully qualified name of the class.
    If the root tag configures the package, a simple class name can be used here.
   table: table name
  <property> Common attribute configuration
   name : attribute name (getter)
   column : The name of the column in the table. If you do not write the default value of name, the value of
   length: the length of the column. Default value: 255
   type: type
    1) hibernate type: string/integer, etc.
     date date
     time
     timestamp timestamp (the current record is modified, the time is automatically changed)
    2) java type: java.lang.String etc.
    3) mysql type: varchar (50)
     <
      <column name="name" sql-type="varchar(50)"></column>
     </property>
   not-null : whether it is not empty or not
   unique : whether it is unique
   access : hibernate uses javabean properties or fields, default: properties . (Understand)
    Values: field, property
 
  -->
 <class name="cn.xxx.e_hbm.Person" table="t_person">
  <!-- Configure primary key -->
  <id name="pid">
   <! -- Primary key generation strategy-->
   <generator class="native"></generator>
  </id>
  <!-- Common properties-->
  <property name="pname" column="name" length="50" type="string" not-null="true" unique="true"></property>
  <property name="



  </property>
  <property name="photo" type="binary" length="400000"></property>
  <property name="desc" column="`desc`"></property>
 </class>

Primary key generation strategy:
Configured to hibernate to let hibernate maintain the value of the OID of the PO object.
Primary key classification: surrogate primary key, natural primary key
 Proxy primary key: automatically generated by hibernate or obtained by hibernate through the database, hibernate is set to the PO object.
 Natural primary key: manually maintained by the program (developer). Requirements to master: native, uuid, assigned
<!--
  <id> Used to configure the primary key
   name="bid" oid attribute name
   column="" column name
   length="" length
   type="" type
   access="" Access method: The field or attribute
  <generator class=""> is used to configure the primary key generation strategy
   1) Increment is increased by hibernate itself by first querying (select max(pid)...) and accumulating 1.
    There is a thread concurrent access problem
    <generator class="increment"></generator>




   4) hilo (high low) high and low algorithm, hibernate maintains id (understanding) in an algorithmic way
    table: table name
    column: column name
    max_lo: one operation
    <generator class="hilo">
                 <param name="table">hi_value </param>
                 <param name="column">next_value</param>
                 <param name="max_lo">100</param>
          </generator>
         5) native select identity, sequence or hilo according to the capabilities of the underlying database One. [Master]
         ########### The above operation id type must be: integer long, short or [int]
         6) uuid random string, the type must be String
          <generator class="uuid">< /generator>
         ########### The above proxy primary key
         7) assigned natural primary key, you need to manually set the id value
  -->

  <id name="bid">
   <generator class="assigned"></generator>
  </id>
  <property name="title"></property>
 </class>


There are three states of PO object state
: transient state: There is no cache object in the session, and there is no corresponding data in the database. For example: new User(); OID has no value
persistent Persistent state: session cache object, the database will eventually have it. For example: save(user); OID value
detached Detached state: The session does not have a cached object, but the database does. ;OID value
network other names: temporary state, managed state, free state, deleted state
state transition
transient state
transient state --> persistent state, save() or saveOrUpdate() --> enter insert statement
transient state --> out of control state , Manually set the OID
 If the OID is manually set, but the corresponding value in the database does not exist, it is still considered to be out of control, just to deceive hibernate, and an exception will be thrown in the corresponding operation.
Persistent state
Persistent state --> Transient state, the official regulations execute delete()
Persistent state --> Out of control state, you can disconnect from the session
 session.close() Close
 session.clear() Clear all sessions.evict
 (.. .) Clear the specified object
detached
state --> transient state, manually delete OID
detached state --> persistent state, update() or saveOrUpdate() --> update update statement

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326507764&siteId=291194637