【问题标题】:I really need close the sessionFactory?我真的需要关闭 sessionFactory 吗?
【发布时间】:2017-02-02 16:50:03
【问题描述】:

为了解决我的问题,我使用下面的代码。但我认为这是不对的……

HibernateFactory.buildSessionFactory();
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    @Override
    public void handle(WindowEvent event) {
        HibernateFactory.closeFactory();
    }
});

那是我的依赖 Jar files

还有我的 hibernate.cfg

    <?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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>   
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/ClinicaVet?UseTimezone=true&amp;serverTimezone=UTC</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">jailbreak</property>
        <property name="current_session_context_class">thread</property>
        <!-- Disable the second level cache -->
        <property 

name="cache.provider_class">org.hibernate.cache.internall.NoCacheProvider</property>
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2dd1">update</property>
        <mapping resource="com/arthurpdj/entity/Agendamento.hbm.xml"/>
        <mapping resource="com/arthurpdj/entity/Animal.hbm.xml"/>
    <mapping resource="com/arthurpdj/entity/Cliente.hbm.xml"/>
    <mapping resource="com/arthurpdj/entity/Examinacao.hbm.xml"/>
    <mapping resource="com/arthurpdj/entity/Exame.hbm.xml"/>
    <mapping resource="com/arthurpdj/entity/Vacinacao.hbm.xml"/>
    <mapping resource="com/arthurpdj/entity/Notificacoes.hbm.xml"/>
    <mapping resource="com/arthurpdj/entity/Vacina.hbm.xml"/>
    <mapping resource="com/arthurpdj/entity/Atendimento.hbm.xml"/>
    <mapping resource="com/arthurpdj/entity/Pagamento.hbm.xml"/>
</session-factory>     </hibernate-configuration>

还有我的 HibernateUtil 类(我已经尝试不使用 ServiceRegistry.. 同样的问题..)

public class HibernateUtil {

private static SessionFactory factory = null;
private static Configuration conf;
    private static ServiceRegistry serviceRegistry;

private static SessionFactory buildSessionFactory() {
    try{
        conf = new Configuration();
        conf.configure("com/arthurpdj/database/hibernate.cfg.xml");
                    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
            conf.getProperties()).build();

        System.out.println("Configurou");

        factory = conf.buildSessionFactory(serviceRegistry);
        System.out.println("construi");

        return factory;
    } catch(Throwable ex) {
        ex.printStackTrace();
        throw new ExceptionInInitializerError(ex);
    }

}

public static SessionFactory getSessionFactory(){
    if(factory ==null) {
        factory = buildSessionFactory();


    }
    return factory; 
}

}

日志

fev 02, 2017 3:05:14 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.7.Final}
fev 02, 2017 3:05:14 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
fev 02, 2017 3:05:14 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
fev 02, 2017 3:05:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
fev 02, 2017 3:05:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/ClinicaVet?UseTimezone=true&serverTimezone=UTC]
fev 02, 2017 3:05:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
fev 02, 2017 3:05:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
fev 02, 2017 3:05:15 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Thu Feb 02 15:05:16 BRST 2017 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.
fev 02, 2017 3:05:16 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect

主类

@Override
    public void start(Stage primaryStage) {

        try {
            Parent root = FXMLLoader.load(getClass().getResource("view/FXMLLogin.fxml"));
            Scene scene = new Scene(root, 424, 331);

            primaryStage.setMaximized(false);
            primaryStage.setResizable(false);
            primaryStage.setTitle("Clinica Veterinária BarraVet");
            primaryStage.setScene(scene);
            primaryStage.show();

            HibernateFactory.buildSessionFactory();
            primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    @Override
    public void handle(WindowEvent event) {


        HibernateFactory.closeFactory();
    }
});


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

【问题讨论】:

  • 你能发布你面临的问题吗?比如错误日志之类的
  • 如果我不关闭会话工厂,应用程序不会终止
  • 好的。发布你的主要课程,我可以告诉你在哪里进行更改

标签: java mysql hibernate


【解决方案1】:

只需使用这个初始化:

{ 
//creating configuration object  
    Configuration cfg=new Configuration();  
    cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file  

    //creating seession factory object  
    SessionFactory factory=cfg.buildSessionFactory();  

    //creating session object  
    Session session=factory.openSession();  

    //creating transaction object  
    Transaction t=session.beginTransaction();  

    //Your code of reading/writing to database here.....


    t.commit();//transaction is committed  
    session.close();  

    System.out.println("successful transaction");  

}  
} 

这是最安全的方法...希望对您有所帮助

【讨论】:

  • 甚至在交易之前.. 我​​无法终止我的程序。你能帮我处理这个映射文件吗?
  • 是的。请确保先进行更改。同时发布您的映射文件
  • 正如我告诉你的......即使我没有进行任何交易,我的程序也不会终止。我在没有事务的情况下使用此代码并返回 Null Pointer.. 因为没有打开会话.. 我无法终止它
  • 请。帮帮我
  • 是的..您需要以更简洁的方式打开会话..我将发布如何初始化它的代码
【解决方案2】:

@Akshay,感谢您的尝试。我使用 c3p0 连接池解决了我的问题

【讨论】:

    猜你喜欢
    • 2012-12-19
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    相关资源
    最近更新 更多