tags:

views:

414

answers:

5

Does Java have a using statement that can be used when opening a session in hibernate?

In C# it is something like:

using (var session = new Session())
{


}

So the object goes out of scope and closes automatically.

+10  A: 

Sorry. No. Java does not have an equivalent to the using statement.

Not exactly the same but somewhat related, Java 7 (coming soon) will include Automatic Resource Block Management.

Asaph
+1  A: 

No, Java has no using statement equivalent.

Rich Adams
+2  A: 

Technically:

DisposableObject d = null;
try {
    d = new DisposableObject(); 
}
finally {
    if (d != null) {
        d.Dispose();
    }
}
ChaosPandion
Not the best way to do it. http://stackoverflow.com/questions/1909662/java-exception-handling-style
Mark Byers
This would essentially be equivalent. I don't care if it is the best way.
ChaosPandion
+2  A: 

As of now, no.

However there is a proposal of ARM for Java 7.

missingfaktor
+3  A: 

Any code inside a code block in Java will go out of scope outside of the code block - so for example you could use

{
    Session session = new Session();

    // session is in scope here.
}
// session is now out of scope and will be cleaned up by the GC at some point.
cgull
Not quite the same - as it'll get cleaned up at some random point in the future here. Whereas the c# cleans it up (by calling dispose) immediately on leaving that block, which is useful for handling eg database connections.
Chris