In this post under hibernate, I will introduce you to Session’s load and get method and explain their difference.
Similarity
1) Both methods are used to load persistent object from the database
2) Both needs primary key id as a parameter
Difference
1) If the persistent object identified by primary key is not there, then load method throws exception where as get method returns null.
Below is an example of how to use load and get method
Main Class
1 import org.hibernate.ObjectNotFoundException;
2 import org.hibernate.Session;
3 import org.hibernate.SessionFactory;
4
5 public class HibernateDemo5 {
6 public static void main(String[] args) {
7 SessionFactory sessionFactory = HibernateUtil.createSessionFactory();
8 Session session = sessionFactory.openSession();
9 try {
10 Message message1 = session.load(Message.class, 1);
11 System.out.println(message1);
12 } catch(ObjectNotFoundException excep) {
13 excep.printStackTrace();
14 }
15 Message message2 = session.get(Message.class, 1);
16 System.out.println(message2);
17 session.close();
18 HibernateUtil.shutdown();
19 }
20 }
In the above code, at line 10, we are calling load method to load Message object with id 1. This doesn’t exist in the database, so ObjectNotFoundException is thrown.
When we try to load the object with get method (at line 15) instead of throwing the exception it returns null value which is printed at line 16.
Output
1 Mar 24, 2019 10:59:35 AM org.hibernate.Version logVersion
2 INFO: HHH000412: Hibernate Core {5.2.13.Final}
3 Mar 24, 2019 10:59:35 AM org.hibernate.cfg.Environment
4 INFO: HHH000206: hibernate.properties not found
5 Mar 24, 2019 10:59:35 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager
6 INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
7 Mar 24, 2019 10:59:35 AM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
8 WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace
http://www.hibernate.org/dtd/hibernate-mapping instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
9 Mar 24, 2019 10:59:36 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
10 WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
11 Mar 24, 2019 10:59:36 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
12 INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/examples]
13 Mar 24, 2019 10:59:36 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
14 INFO: HHH10001001: Connection properties: {user=root, password=****}
15 Mar 24, 2019 10:59:36 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
16 INFO: HHH10001003: Autocommit mode: false
17 Mar 24, 2019 10:59:36 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections
18 INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
19 Sun Mar 24 10:59:36 IST 2019 WARN: Establishing SSL connection without server’s identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and
5.7.6+ requirements SSL connection must be established by default if explicit option isn’t set. For compliance with existing applications not using SSL the
verifyServerCertificate property is set to ‘false’. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
20 Mar 24, 2019 10:59:36 AM org.hibernate.dialect.Dialect
21 INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
22 Hibernate: drop table if exists Message
23 Mar 24, 2019 10:59:37 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
24 INFO: HHH10001501: Connection obtained from JdbcConnectionAccess
[org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@611df6e3] for (non-JTA) DDL execution was not in auto-commit mode; the Connection ‘local transaction’ will be committed and the Connection will be set into auto-commit mode.
25 Hibernate: create table Message (id integer not null auto_increment, message varchar(255), primary key (id)) engine=MyISAM
26 Mar 24, 2019 10:59:37 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
27 INFO: HHH10001501: Connection obtained from JdbcConnectionAccess
[org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@18a3962d] for (non-JTA) DDL execution was not in auto-commit mode; the Connection ‘local transaction’ will be committed and the Connection will be set into auto-commit mode.
28 Mar 24, 2019 10:59:37 AM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
29 INFO: HHH000476: Executing import script ‘org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@4215838f’
30 Hibernate: select message0_.id as id1_0_0_, message0_.message as message2_0_0_ from Message message0_ where message0_.id=?
31 org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [Message#1]
32 at org.hibernate.boot.internal.StandardEntityNotFoundDelegate.handleEntityNotFound(StandardEntityNotFoundDelegate.java:28)
33 at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:242)
34 at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
35 at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:266)
36 at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:73)
37 at Message_$$jvst896_0.toString(Message$$jvst896_0.java)
38 at java.lang.String.valueOf(Unknown Source)
39 at java.io.PrintStream.println(Unknown Source)
40 at HibernateDemo5.main(HibernateDemo5.java:11)
41 Hibernate: select message0.id as id1_0_0_, message0_.message as message2_0_0_ from Message message0_ where message0_.id=?
42 Mar 24, 2019 10:59:37 AM org.hibernate.event.internal.DefaultLoadEventListener doOnLoad
43 INFO: HHH000327: Error performing load command : org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [Message#1]
44 null
45 Mar 24, 2019 10:59:37 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
46 INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/examples]
In the output, at line 31 ObjectNotFoundException is printed when we call load method with wrong id.
At line 44, null value is printed when we call get method with wrong id.