在hibernate中打开会话时,Java有没有可以使用的using语句?
在C#中,它类似于:
using (var session = new Session())
{
}
因此,该对象会超出作用域并自动关闭。
发布于 2010-01-07 05:17:32
Java7引入了Automatic Resource Block Management,它为Java平台带来了这个特性。以前的Java版本没有任何类似using
的东西。
例如,您可以通过以下方式使用实现java.lang.AutoCloseable
的任何变量:
try(ClassImplementingAutoCloseable obj = new ClassImplementingAutoCloseable())
{
...
}
Java实现的java.io.Closeable
接口自动扩展了AutoCloseable
,因此您已经可以在try
块中使用streams,就像在C# using
块中使用它们一样。这相当于C#的using
。
从version 5.0, Hibernate Sessions implement AutoCloseable
开始,可以在ARM块中自动关闭。在Hibernate Session did not implement AutoCloseable
的早期版本中。因此,您需要使用Hibernate >= 5.0才能使用此功能。
发布于 2011-08-24 16:17:41
从Java7开始就是这样:http://blogs.oracle.com/darcy/entry/project_coin_updated_arm_spec
问题中代码的语法为:
try (Session session = new Session())
{
// do stuff
}
请注意,Session
需要实现AutoClosable
或其(多个)子接口之一。
发布于 2010-01-07 05:18:14
从技术上讲:
DisposableObject d = null;
try {
d = new DisposableObject();
}
finally {
if (d != null) {
d.Dispose();
}
}
https://stackoverflow.com/questions/2016299
复制相似问题