我知道关于这个话题有很多问题,但我找不到适合我需要的答案。 我有一个非常简单的要求:打开与MySQL数据库的连接,进行查询,获取结果并关闭连接。
这是我的代码:
Hibernate文件:
<?xml version='1.0' encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://192.168.254.90:3306/db</property>
<property name="connection.username">user</property>
<property name="connection.password">password</property>
<property name="connection.pool_size">0</property>
<property name="show_sql">false</property>
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
Java类:
final URL resourceUrl = getClass().getClassLoader().getResource("blabla.xml");
final Configuration configuration = new Configuration().configure(new File(resourceUrl.toURI()));
final SessionFactory sessionFactory = configuration.buildSessionFactory();
final Session session = sessionFactory.openSession();
session.setFlushMode(FlushMode.ALWAYS);
final String sqlQueryStr = "SELECT col1 FROM table1 WHERE col2 = 'blabla'";
final Query sqlQuery = session.createSQLQuery(sqlQueryStr);
session.beginTransaction();
final Map<String, Object> result = (Map<String, Object>) sqlQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE).uniqueResult()
final String resultStr = result.get("col1").toString();
session.getTransaction().commit();
session.close();
这段代码让我在MySQL中有一个处于“睡眠”状态的进程,为什么?此外,如果我想重用此会话,它不起作用,因为我关闭它。那么为什么它会让“睡眠”过程,并在同一时间不能使用呢?
谢谢!