20 common hibernate Problems

Source: Internet
Author: User

1. the following error is always reported during hibernate initialization: Java. Lang. noclassdeffounderror.
Error code During hibernate initialization:
Java. Lang. noclassdeffounderror: net/SF/ehcache/cacheexception
A: This is a common problem for beginners. The reason is that when the default settings are used, the hibernate Library mentioned in the hibernate document is incomplete and the ehcache. jar is missing (used for files supporting ehcache ). Add the above files to the configuration to avoid java. Lang. noclassdeffounderror: net/SF/ehcache/cacheexception exceptions during initialization.

2 Q: hibernate error: "Not binding factory to JNDI, no JNDI name configured"
Run the following programs:
Public static void main (string [] ARGs) throws exception {
Configuration conf = new configuration (). addclass (person. Class );
Error code:
12:15:34, 250 info sessionfactoryobjectfactory: 82-not binding factory to JNDI, no JNDI name configured
Java. Lang. unsupportedoperationexception: the user must supply a JDBC connection
At net. SF. hibernate. Connection. usersuppliedconnectionprovider. getconnection (usersuppliedconnectionprovider. Java: 32)
At net. SF. hibernate. impl. batcherimpl. openconnection (batcherimpl. Java: 289)
At net. SF. hibernate. impl. sessionimpl. Connect (sessionimpl. Java: 3361)
At net. SF. hibernate. impl. sessionimpl. Connection (sessionimpl. Java: 3321)
At net. SF. hibernate. impl. batcherimpl. preparequerystatement (batcherimpl. Java: 66)
At net. SF. hibernate. loader. loader. preparequerystatement (loader. Java: 779)
At net. SF. hibernate. hql. querytranslator. iterate (querytranslator. Java: 864)
At net. SF. hibernate. impl. sessionimpl. iterate (sessionimpl. Java: 1618)
At net. SF. hibernate. impl. queryimpl. iterate (queryimpl. Java: 27)
At com. hibernate. Person. testqueryperson. Main (testqueryperson. Java: 28)
Exception in thread "Main"
A: Modify the main function and specify a configuration file for the program.
Public static void main (string [] ARGs) throws exception {
File file = new file ("./hibernate. cfg. xml ");
Configuration conf = new configuration (). Configure (File );
The configuration file is as follows.
<? XML version = "1.0"?>
<! Doctype hibernate-mapping public
"-// Hibernate/hibernate mapping DTD 3.0 // en"
<! --
This mapping demonstrates content-based discrimination for
Table-per-hierarchy mapping strategy, using a formula
<Hibernate-mapping package = "org. hibernate. Test. array">
<Class name = "A" lazy = "true">
<ID name = "ID">
<Generator class = "native"/>
<Array name = "BS" cascade = "all" Fetch = "join">
<Key column = "a_id"/>
<List-index column = "idx"/>
<One-to-learn class = "B"/>
<Class name = "B" lazy = "true">
<ID name = "ID">
<Generator class = "native"/>

3. When using the development tool Elipse, java. Lang. noclassdeffounderror: ORG/hibernate/session exception is always reported during runtime.
When Elipse is used, the packet used is hibernte 3. It is found that each execution in the action includes:
Session = hibernatesessionfactory. currentsession ();
Java. Lang. noclassdeffounderror: ORG/hibernate/session exception occurs, as follows:
Java. Lang. noclassdeffounderror: ORG/hibernate/session
Hibernate3.hibernate. excuteclass. Search (excuteclass. Java: 17)
Hibernate3.hibernate. excuteclass. test3 (excuteclass. Java: 13)
Hibernate3.hibernate. svlt. doget (svlt. Java: 50)
Javax. servlet. http. httpservlet. Service (httpservlet. Java: 689)
Javax. servlet. http. httpservlet. Service (httpservlet. Java: 802) [/B]
A: This is a common problem for beginners. The reason is that hibernate is not imported. 3. jar package, although the hibernate 3. jar is written to classpath, but it is not copied to lib during deployment. You can copy it manually.

4. "No currentsessioncontext configured" error occurs when the following method is executed:
The "no currentsessioncontext configured" error occurs when the following method is executed:
Public static session currentsession (){
Try {
System. Out. println ("hibernateutil. currentsession ()-start ");
Return getsessionfactory (). getcurrentsession ();
} Catch (hibernateexception ex ){
System. Out. println ("hibernateutil. currentsession ()-failed due to" + ex );
Throw ex;
A: This error is caused by the configuration file. In an environment integrated with hibernate (such as JBoss), add the following in the session-factory segment:
<Property name = "hibernate. current_session_context_class"> JTA </property>
In an environment without hibernate integration (for example, an independent JDBC application), add the following content to the session-factory segment:
<Property name = "hibernate. current_session_context_class"> thread </property>
You can solve this problem.

5 Q: An error occurred while configuring hibernate in JBoss 4.
Hibernate is successfully configured in Tomcat 5, but many problems occur when it is transplanted to JBoss 4. The Hibernate-service.xml and hibernate. cfg. xml files have been placed in the deploy directory, but the startup server still reports the following error.
16:56:54, 046 error [urldeploymentlistener] Incomplete deployment listing:
Packages waiting for a deployer:
Org. JBoss. Deployment. deploymentinfo @ 24bd343 {url = file:/C:/downloads/temp/JBoss-
4.0.0/Server/default/deploy/hibernate. cfg. xml}
Deployer: NULL
Status: NULL
State: init_waiting_deployer
Watch: file:/C:/downloads/temp/Jboss-4.0.0/Server/default/deploy/hibernate. cfg
. Xml
Altdd: NULL
Lastdeployed: 1113987414046
Lastmodified: 1113987414046
Incompletely deployed packages:
Org. JBoss. Deployment. deploymentinfo @ 24bd343 {url = file:/C:/downloads/temp/JBoss-
4.0.0/Server/default/deploy/hibernate. cfg. xml}
Deployer: NULL
Status: NULL
State: init_waiting_deployer
Watch: file:/C:/downloads/temp/Jboss-4.0.0/Server/default/deploy/hibernate. cfg
. Xml
Altdd: NULL
Lastdeployed: 1113987414046
Lastmodified: 1113987414046
A: This is a common problem of using hibernate in JBoss. In a war package of JBoss, Hibernate should be used. cfg. the XML file is placed in % war_dir % WEB-INF/classes, but the factory of hibernate may still prompt hibernate. cfg. XML not found. The solution to this problem is as follows.
Because JBoss has integrated hibernate, a jar package already exists in the hibernate2.jar file in the deploy/lib folder, so the actual war may use the shar hibernate2.jar, because classloader only searches for hibernate in the hiernate2.jar directory at the same level and in the parent directory. cfg. XML, so hibernate does not find hibernate in % war_dir % WEB-INF/classes. cfg. XML file. Delete hibernate2.jar under deploy/lib or use the absolute path to specify hibernate. cfg. xml.
Unless there are other requirements, the deployment of hibernate in JBoss is the same as that in Tomcat, and no other configuration files need to be added.

6. Where can I use cascade = "..."?
A: The cascade attribute is not required for many-to-many relations. It is more convenient to insert or delete objects. You only need to insert or delete objects from the cascade source, all cascade relationships are automatically inserted or deleted. Among them, unsaved-value is a very important attribute. hibernate uses this attribute to determine whether the object should be "save" or "Update". If the Object ID is unsaved-value, it indicates that this object is not a persistence object and must be saved (insert). If the ID is not unsaved-value, it indicates that this object is a persistence object (which already exists in the Database ), you only need to update.

7. Where to use inverse = "true"
A: The default value of the inverse attribute is false, that is, the link is maintained at both ends of the link. This means that there are three tables: student, teacher, and teacherstudent. The student object and teacher object have many-to-many relationships, which are represented by the teacherstudent table.
When will the records in the teacherstudent table be inserted or deleted. When Hibernate is used, operations on the teacherstudent table are not explicitly performed, and the operations on teacherstudent are automatically performed by hibernate. Hibernate is the "who" specified in the HBM file to maintain the relationship. during insertion or deletion, operations on the relational table are triggered. The premise is that the object "who" already knows the link, that is, the object at the other end of the link has been set or added to the object "who.
As mentioned above, the default value of inverse is false, which means that both ends of the link maintain the relationship. Any operation on the link triggers the operation on the table. When inverse = "true" is used at one end of the link, such as the bag or set in student, it indicates that the link is maintained by the other end (teacher ). That is to say, when student is inserted, the teacherstudent table is not operated, even if student already knows the relationship. The Link Table operation is triggered only when the teacher is inserted or deleted. Therefore, it is incorrect to use inverse = "true" at both ends of the link. This will not trigger any operation on the relational table. When both ends are inverse = "false" or default values, explicit link maintenance in the Code is also incorrect, resulting in two relationships inserted in the relational table.

8 Q: What is the difference between cascade and inverse?
A: As you can understand, cascade defines the cascading relationship between objects at both ends of the link and objects. Inverse defines the cascading relationship between the link and objects.

9 Q: The error "net. SF. hibernate. objectdeletedexception: Deleted Object wocould be re-Saved by cascade (remove deleted object from associations)" is reported during the delete operation)
A: To delete a link (for example, to delete a teacher object associated with the student object), this exception is thrown only when Tx. Commit () is used. To prevent this exception, follow these steps.
Cascade is not required on student.
Or use cascade to explicitly Delete the relationships in the object.
Use cascade on the teacher side.

10 Q: the following error occurs: net. SF. hibernate. hibernateexception: identifier of an instance of my. myobject altered from N to n.
A: This exception is not often encountered in many-to-many relationships, but the prompts of this exception are confusing. This is because the ID definition in a Java object is different from that in an HBM file. For example, long is used in Java, and type = "integer" is used in HBM ".

11 Q: Why is part of the data automatically lost when a long string is inserted into the database?
When a new entry is added to the database, it is found that if the number of characters (including English letters and Chinese characters) is extremely large, more than 1000, then Hibernate is used each time, when adding data to a string type field, only a few hundred words can be added. Other words are automatically lost.
A: This is caused by unreasonable Field Length settings. You can use text, longtext, blob, and other field types based on the actual length of the string. The Field Types of different databases are slightly different. For details, refer to the relevant manual. Note that a Chinese character occupies two bytes.

12 Q: Why does it take a very slow time to delete large batches of records using the hibernate batch deletion method?
A: We do not recommend using the batch Delete method of Hibernate to delete a large number of records when using hibernate version 2.x. The reason is that hibernate will execute one query statement and multiple Delete statements that meet the conditions, instead of executing one Delete statement at a time. Therefore, when there is a lot of data to be deleted, there will be a lot of performance bottlenecks. For Versions later than hibernate 3.0, this issue is not stored.

13 Q: Why is it very slow to import the HBM ing file after hibernate 3 is upgraded?
Originally in hibernate 2, the program speed was very fast. After the environment was successfully upgraded from Hibernate 2 to hibernate 3, it was found on the Tomcat console that hibernate 3 was very slow to load HBM ing files, and it took about 10 seconds to load an HBM file.
A: By setting breakpoints in the source code of hibernate, you can find that the Code with low execution efficiency is in line 240th Of The Org. hibernate. cfg. configuration file:
Addinputstream (New fileinputstream (xmlfile ));
The addinputstream function also contains:
Org. dom4j. Document Doc = xmlhelper. createsaxreader ("XML inputstream", errors, entityresolver). Read (New inputsource (xmlinputstream ));
Tracking the function createsaxreader in org. hibernate. util. xmlhelper can draw a conclusion that the crux of the problem lies in this statement:
Org. dom4j. Document Doc = xmlhelper. createsaxreader ()
It can be judged that this is an error occurred during the initialization of the XML file. Check the XML file carefully and you will find that this is the first line of XML to declare the DTD error, because previously hibernate 2 was used, therefore, the DTD of the HBM file points to version 2. After hibernate 3 is upgraded, the old HBM ing file is not replaced with version 3. After the version is changed to version 3, the problem is solved.

14 Q: Why does hql in hibernate 3 fail to query Chinese characters?
With the same code and configuration file, there is no problem at all in hibernate 2. In hibernate 3, the following hql query cannot be used to obtain the correct result set:
String hql = "from story where title like '% Chinese character % '";
Query q = session. createquery (hql );
However, the following hql query can obtain the correct result set:
String hql = "from story where title like '% English % '";
Query q = session. createquery (hql );
A: If hql is spliced, upgrading from Hibernate 2 to hibernate 3 will indeed cause Chinese Character garbled characters. On the console, we can see that the Chinese characters in SQL are garbled:
[Debug] 14:33:58 Org. hibernate. SQL-"select story0 _. content from story as story0 _ Where story0 _. title like '% &-° é-& sher¨ & €'
In hibernate, you should try to use the placeholder Statement (as follows) When querying, which can avoid garbled characters and potential SQL injection attacks:
Gethibernate (). Find ("from story where title like? "," % Chinese character % ")

15 Q: How can I obtain the names of all fields in the database table in hibernate 3?
A: You can use the following program.
Configuration conf = new configuration ();
Conf. Configure ();
Iterator iter = Conf. gettablemappings ();

While (ITER. hasnext ()){
Table = (table) ITER. Next ();

System. Out. println (table. getname ());
Iterator ICS = table. getcolumniterator ();
While (ICS. hasnext ()){
Column Col = (column) ics. Next ();
System. Out. println (Col. getname ());

16 Q: Error code: objectnotfoundexception: no row with the given identifier exists
A: In the following situations, this error may occur.
When you try to use the session. Load () method to load a non-proxy object or access an out-of-range proxy object.
When loading a ing that is not correctly obtained.
When a foreign key field that is not subject to foreign key constraints contains invalid values.
Check the ID of the primary key used for the load and verify the foreign key relationship to confirm that the database already has the corresponding constraint relationship. Adhere to the principle of "processing only one transaction in one session. Because it is easy to make mistakes when multiple transactions are used in a single session. In particular, do not operate on the session after a hibernateexception has been thrown.

17 Q: Error code: invalidobjectexception: cocould not find a sessionfactory named: NULL
A: This error occurs frequently in the following situations.
Attempt to serialize an expired hibernate session and perform deserialization in another virtual machine.
The class loader is reset, for example, re-deploying the program in the application server or web iner that has not been restarted. This problem is often encountered when Tomcat is used, because the application server generally uses JNDI to store sessionfactory, while in Tomcat or some other Web containers, it is through the context overload, disable httpsession serialization. This implementation will cause this error.

18 Q: Error code: org. hibernate. hibernateexception: cglib enhancement failed: <classname>
A: The default method of hibernate 3 is to load all classes by using a proxy. If the class in the Code has a constructor with no private parameters, Hibernate will not be able to load the class in the project code as a subclass at runtime. To avoid this error, the constructors in the class should at least be visible in the package.

19 Q: Why do I add, delete, or modify an object or collection in hibernate, But there is actually no change in the database?
A: This problem often bothers beginners. This is because if hibernate's automatic transaction processing is not used, the transaction must be committed explicitly before the operation can be executed in the database.

20 Q: Why does one store a parent object and its associated objects are not automatically stored in the database?
A: The associated object must call the session explicitly. save () (or session. persist (), or add cascade = "all" or cascade = "Save-Update" (or cascade = "Persist") to the associated ing file to automatically associate and execute.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.