Hibernate often meets questions

How Hibernate works and why should I use it?

How Hibernate works and why should I use it?

  1. Read and parse configuration files
  2. Read and parse the mapping information to create the SessionFactory
  3. Open the Sesssion
  4. Create a transaction Transation
  5. Persistent operation
  6. Commit the transaction
  7. Close the Session
  8. Close the SesstionFactory

Using Hibernate framework does not require us to write a lot of cumbersome SQL statements. Hibernate simplifies our development by implementing ORM, which maps objects to database tables!

How does Hibernate lazy load?

How does Hibernate lazy load?

You can set whether lazy loading is required by setting the property lazy

When Hibernate queries the data, the data does not exist in the memory. When the program really operates on the data, the object exists in the memory, which realizes lazy loading. It saves the memory overhead of the server and improves the performance of the server.

How to implement relationships between classes in Hibernate? (e.g., one-to-many, many-to-many)

How to implement relationships between classes in Hibernate? (e.g., one-to-many, many-to-many)

They implement the association between classes through many-to-one, one-to-many, and many-to-many in the configuration file.

How do you transition between the three states of Hibernate

How do you transition between the three states of Hibernate

State of objects in Hibernate:

  • Temporary/transient state
  • Persistent state
  • The free state

Temporary/transient state

When we directly new the object is temporary/transient..

  • The object has not been persisted.
  • It is not managed by sessions

Persistent state

Objects are persistent when they are stored in a database

  • When the session is called the save/saveOrUpdate/get/load/list method, the object’s persistent state
  • There’s data in the database
  • Managed by the Session
  • When changes are made to object properties, they are reflected in the database!

Let’s test: when changes are made to object properties, they are reflected in the database!


        session.save(idCard);
        idCard.setIdCardName("I'm testing persistent objects.");

Copy the code

The free state

When the Session is closed, the persistent object becomes free…

  • Not in session management
  • There are corresponding records in the database

With that in mind, it’s easy to say what the transition is between them

  • If the new object is transient -> if it is saved to the database (managed by Session), it is persistent -> if the Session is closed, it is free

Compare the advantages and disadvantages of hibernate’s three retrieval strategies

Compare the advantages and disadvantages of hibernate’s three retrieval strategies

Search now:

  • Advantages: It is completely transparent to the application. It is easy for the application to navigate from an object to its associated objects, whether the object is in a persistent state or a free state.
  • Disadvantages: 1. Too many select statements. 2. It may load objects that the application does not need to access and waste a lot of memory space.
  • Search now:lazy=false;

Delayed retrieval:

  • Advantages: The application decides which objects to load, avoids redundant select statements that can be executed, and avoids loading objects that the application does not need to access. Therefore, retrieval performance can be improved and memory space can be saved.
  • Disadvantages: If an application wants to access a free-state proxy instance, it must ensure that it has been initialized while persisting the state.
  • Lazy loading:lazy=true;

Urgent left outer connection search:

  • Advantages: 1 Completely transparent to the application, whether the object is in a persistent state or a free state, the application can easily navigate an object to its associated objects. 2 use external join, the number of select statements is small;
  • Disadvantages: 1. It may load objects that the application does not need to access, wasting a lot of memory space. 2 complex database table join will also affect the retrieval performance;
  • Advance grab:The fetch = "join";

What caching strategies Hibernate supports

What caching strategies Hibernate supports

There are four attributes for usage:

  • The object placed in the level-2 cache is read-only.
  • Nonstrict read/write
  • Reading and writing; Objects placed in the second-level cache can be Read or written (Read/write).
  • Transactional strategy

What is the difference between sorted collection and Ordered Collection in Hibernate

What is the difference between sorted collection and Ordered Collection in Hibernate

sorted collection

  • Is sorted in memory by a Java comparator

ordered collection

  • Is sorted in the database by order by

For large data sets, it is best to use ordered Collection to avoid OutofMemoryErrors in Java when they are ordered in memory.

Let’s talk about Hibernate’s caching mechanism

Let’s talk about Hibernate’s caching mechanism

Level 1 cache:

  • The level 1 cache in Hibenate, also known as the session cache, can reduce the number of database accesses within the session scope! Only valid in the session scope! Session closed, level 1 cache invalid!
  • As long as the object state is persistent, it is managed by the Session, that is, it is in the Session cache!
  • The Session cache is maintained by Hibernate, and the user cannot manipulate the cached content. If you want to manipulate cached content, you must do so through the EVit/Clear method provided by Hibernate.

Level 2 cache:

  • The second-level cache is the application-based cache that all sessions can use
  • Hibernate provides second level caching with a default implementation and is a pluggable caching framework! If the user wants to use the level 2 cache, it only needs to be configured in Hibernt.cfg.xml. If you don’t want to use it, you can remove it without affecting your code.
  • If users find the Framework provided by Hibernate difficult to use, you can switch to another caching framework or implement your own caching framework.
  • Hibernate level 2 cache: Stores commonly used classes

Hibernate queries can be done in several ways

Hibernate queries can be done in several ways

  • Object Navigation Query (ObjectComposition)
  • HQL query
    • 1. Property query
    • 2. Parameter query and named parameter query
    • 3. Implement associated query
    • 4. Paging query
    • 5. Statistical functions
  • The Criteria query
  • SQLQuery Indicates a local SQL query

How to optimize Hibernate?

How to optimize Hibernate?

  • ø Database design adjustment
  • Ø HQL optimization
  • Correct use of APIS (such as selecting different sets and querying apis according to different business types)
  • Main configuration parameters (log, query cache, fetch_size, batch_size, etc.)
  • Mapping file optimization (ID generation strategy, level 2 caching, lazy loading, correlation optimization)
  • ø Level 1 cache management
  • ø There are many specific strategies for level 2 caching

For details, please refer to:

  • www.cnblogs.com/xhj123/p/61…

Talk about the role of Inverse in Hibernate

Talk about the role of Inverse in Hibernate

The default value of the inverse property is false, which means that both sides of the relationship maintain the relationship.

  • For example, Student and Teacher have a many-to-many relationship, maintained with an intermediate table TeacherStudent. Gp)
  • If inverse= “true” on the Student side, then the relationship is maintained by the other Teacher side, which means that the TeacherStudent table (the middle table) is not manipulated when inserting the Student. Operations on intermediate tables are triggered only when Teacher inserts or deletes. Inverse = “true” on both sides is incorrect, resulting in no action affecting the middle table; When both sides = “false” or default, the relationship is inserted twice in the intermediate table.

If the relationship between tables is one-to-many, then inverse can only be configured on the “one” side!

For details, please refer to:

  • Zhongfucheng.bitcron.com/post/hibern…

JDBC Hibernate and IBATIS differences

JDBC Hibernate and IBATIS differences

JDBC: manual

  • Manual writing SQL
  • Delete, INSERT, or update the value of an object should be fetched one by one and passed to SQL.
  • Select: Returns a resultSet, which is extracted from the resultSet row by row and field by field, and then encapsulated into an object instead of directly returning an object.

Ibatis features: semi-automation

  • The SQL should be written manually
  • Delete, INSERT, update: Pass an object directly
  • Select: Returns an object directly

Hibernate: fully automatic

  • Do not write SQL, automatic encapsulation
  • Delete, INSERT, update: Pass an object directly
  • Select: Returns an object directly

How to optimize when conditional queries are slow in a database?

How to optimize when conditional queries are slow in a database?

  1. indexed
  2. Reduce the association between tables
  3. Optimize SQL to allow SQL to locate data as quickly as possible. Do not allow SQL to do full table queries. Instead, use indexes to rank tables with large data volumes first
  4. Simplify the query field, do not use the field, have the control of the return result, as much as possible to return a small amount of data

For details, please refer to:

  • Mp.weixin.qq.com/s?timestamp…GFpCEVLtaLlwjj2HaDOjsCRkTnwfVlUY5cDhSyRi-c8leheofZJVnu6wYQ3IvT*hYyVB1pQCqqnuXIWERaksjXuyNP8=

What is a SessionFactory and is it thread safe

What is a SessionFactory and is it thread safe

SessionFactory is Hibrenate singleton data store and thread-safe so that multiple threads can access it simultaneously. A SessionFactory can only be created once at startup. SessionFactory should wrap various singletons so that it can be easily stored in an application code.

The difference between get and load

The difference between get and load

  • Get () immediately queries

  • Load () lazy loading

  • 1) Get returns null if not found, load raises an exception if not found.
  • 2) Get will first check level-1 cache, then level-2 cache, and then database; Load will look at the level-1 cache first, and if it doesn’t find it, it will create a proxy object and then query the level-2 cache and database as needed.

The meaning of merge:

The meaning of merge:

  • If there are instances of the same persistence identifier in the session, overwrite the old persistent instance with the state of the user-given object
  • If the session does not have a corresponding persistent instance, it attempts to load it from the database, or create a new persistent instance, and finally returns the persistent instance
  • The object given by the user is not associated with the session, it is still unmanaged

For details, please refer to:

  • cp3.iteye.com/blog/786019

The difference between persist and save

The difference between persist and save

  • Persist does not guarantee immediate execution and may wait until flush;
  • Persist does not update the cache.
  • Save, which persists the identifier of a transient instance, is produced in a timely manner, and it returns the identifier, so it performs the Sql INSERT immediately
  • When the save() method is used to save a persistent object, it returns the value of the persistent object’s identity property (that is, the primary key of the corresponding record);
  • When you use the persist() method to hold persistent objects, the method does not return any value.

References:

  • Blog.csdn.net/u010739551/…

What are the primary key generation policies

What are the primary key generation policies

Automatic primary key generation policy

  • Identity self growth (mysql, DB2)
  • Sequence autogrowth (sequence). In Oracle, autogrowth is implemented in a sequential way
  • Native auto-growing [will select identity or sequence according to the underlying database auto-growing way]
    • In the case of mysql database, the self-growth mode is identity
    • For Oracle database, use sequence sequence to achieve self-growth
  • There are problems with concurrent access, which can be problematic when used in server cluster environments.

Specify the primary key generation policy to manually specify the value of the primary key

  • assigned

Specifies the value generated for the UUID by the primary key generation policy

  • uuid

Foreign (foreign key mode)

Describe the difference between getCurrentSession and openSession in Hibernate

Describe the difference between getCurrentSession and openSession in Hibernate

  • 1. GetCurrentSession is bound to the current thread, while openSession is not, because after we give Hibernate to spring, we have transaction configuration, and the thread with the transaction is bound to every session in the current factory. OpenSession is creating a new session.
  • GetCurrentSession transaction is controlled by Spring, whereas openSession requires us to manually open and commit the transaction.
  • GetCurrentSession does not need to be closed manually because the factory will manage it itself, whereas openSession needs to be closed manually.
  • GetCurrentSession requires you to manually set the binding transaction mechanism. There are three ways to set this mechanism. JDBC local Thread, JTA is spring, the third provides transaction management mechanism org. Springframework. Orm. Hibernate4. SpringSessionContext, and srping default to the transaction management mechanism

What is a named SQL query in Hibernate?

What is a named SQL query in Hibernate?

  • Named queries refer to queries that use<sql-query>The tag maps the SQL query defined in the document, which can be called using the session.getNamedQuery () method. Named queries allow you to get a specific query using a name you specify.
  • Named queries in Hibernate can be defined using annotations or the XML priming questions I mentioned earlier. In Hibernate, @namequery is used to define a single named query and @namequeries is used to define multiple named queries.

Why is it important to provide a parameterless constructor in Hibernate entity classes?

Why is it important to provide a parameterless constructor in Hibernate entity classes?

Each Hibernate entity Class must contain a parameterless constructor because the Hibernate framework uses the Reflection API to create instances of these entity classes by calling class.newinstance (). If no parameterless constructor is found in the entity class, this method throws a InstantiationException.

Can Hibernate entity classes be defined as final?

Can Hibernate entity classes be defined as final?

You can make Hibernate entity classes final, but that’s not a good idea. Because Hibernate uses the proxy pattern to improve performance in the case of delayed association, if you define entity classes as final classes, Hibernate can no longer use the proxy because Java does not allow extensions to final classes, thus limiting the means available to improve performance.

The last

References:

  • Blog.csdn.net/qq113762316…
  • Blog.csdn.net/u013842976/…
  • Blog.csdn.net/yubotianxia…

If the article is wrong, welcome to correct, we communicate with each other. Used to read technical articles in wechat, want to get more Java resources, students can follow the wechat public number :Java3y