2011-09-14 9 views
5

estoy un poco confundido por los JavaDocs en Session.load:¿Qué hace el método load() de Hibernate para IDs no existentes?

Return the persistent instance of the given entity class with the given identifier, assuming that the instance exists. This method might return a proxied instance that is initialized on-demand, when a non-identifier method is accessed.

You should not use this method to determine if an instance exists (use get() instead). Use this only to retrieve an instance that you assume exists, where non-existence would be an actual error.

entiendo que tengo que utilizar conseguir, pero lo que no entiendo es lo que se quiere decir con lo de que inicializa en la demanda cuando se usa un método no identificador.

Para mí, si tengo una clase y uso load(MyClass.class, NonExistingID), y luego imprimir el resultado de la getId() en la instancia devuelta, parece producir automáticamente una nueva instancia con NonExistingID cada vez. ¿Por qué es esto?

Estoy tratando de entender, ¿es getId() un método no identificable?

Respuesta

5

'Método no identificador' significa un método que devuelve algo además del identificador (como en la identificación de la clave principal) para el objeto. load le da un proxy, donde el proxy solo consulta la base de datos una vez que le pide algo además del identificador. Entonces getId es un método de identificación, Hibernate no consulta la base de datos por su valor (no tiene que hacerlo porque lo pasó a la llamada al método load).

Encontramos este fragmento en the hibernate forums:

An important scenario under which you need to contrast the load and get methods of the Hibernate Session has to do with what happens when you provide a primary key that doesn't actually exist in the database. Well, with the get method, you are simply returned a null object, which is no big deal.

With the load method, there's also no initial problem when you provide an invalid primary key to the method. From what you can tell, Hibernate appears to hand you back a valid, non-null instance of the class in which you are interested. However, the problems start when you actually try to access a property of that instance - that's where you run into trouble.

Remember how I said the load method doesn't hit the database until a property of the bean is requested? Well, if you've provided a primary key that doesn't exist in your database to the load method, when it does go to the database for the first time, it won't be able to find the non-existent, associated record, and your code will cough up big time. In fact, looking up a field based upon a non-existent primary key with the Hibernate Session's load method triggers the following error:

org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [User#123]

por lo que suena como si han utilizado la carga para conseguir un proxy para un objeto que no existe, pero ya que no ha llamado a los 'métodos nonidentifier' en él, se no ha obligado al proxy a golpear la base de datos y no ha recibido un error.

6

sólo para hacer el cuento largo:

Session.load creará objeto proxy que se inicializa cuando se llama a cualquier captador de posición de clase clave no primaria.

session.get devolverá nulo si el objeto no existe y devolverá el objeto completo si existe.

Cuestiones relacionadas