简体   繁体   English

Java FX中的数据库连接最佳实践

[英]Database Connection Best Practice in Java FX

I am designing a MVC JAVAFX program that has intensive database connection. 我正在设计一个具有密集数据库连接的MVC JAVAFX程序。 I dont know where to put the database connection details. 我不知道在哪里放数据库连接细节。 Whether I should define the connection details info in a Model form and process the connection as a controller or should I put them together in one single model file. 我是否应该在模型表单中定义连接详细信息并将连接作为控制器处理,或者我应该将它们放在一个模型文件中。

In the long run I need that connection as a session throughout the program until the user logoff. 从长远来看,我需要将该连接作为整个程序的会话,直到用户注销。

Is there any simple example that I could study for this matter. 有什么简单的例子我可以研究这件事。 I know using hibernate is the best way but im still learning Java FX and I need someguidance about this. 我知道使用hibernate是最好的方法,但我仍在学习Java FX,我需要一些指导。

Thanks. 谢谢。

At the moment I'm also at an JavaFX application with an database connection. 目前我也在使用数据库连接的JavaFX应用程序。 The way I chose is the following: Create a SQL-Controller -Class. 我选择的方式如下:创建一个SQL-Controller类。 This class should contain everything handling your SQL-Data(For example: a connect -method to open a connection - a close -method is also not wrong). 这个类应该包含处理你的SQL数据的所有东西(例如:一个connect -method来打开一个连接 - 一个close -method也没有错)。 Use this class in all your controller classes to get the data you need or save the data you have. 在所有控制器类中使用此类可以获取所需的数据或保存您拥有的数据。

Here an little example 这里有一个小例子

The SQLController class could look like that: SQLController类看起来像这样:

public class SqlController {

   //Put you connection string with pw, user, ... here
   private static final String YOUR_CONNECTION_STRING = ""; 

   public boolean openConnection() {
       boolean result;
       try {
           // Open your connection
           result = true;
       } catch (Exception e) {
        result = false;
       }
       return result;
   }

   public boolean closeConnection() {
       boolean result;
       try {
           // Close your connection
           result = true;
       } catch (Exception e) {
           result = false;
       }
       return result;
   }

   public YourData getSomeData(){

    //get The Data you want.
    return YourData;
   }
}

You could use the controller in any method of your UI-Controller. 您可以在UI控制器的任何方法中使用控制器。

public void handelSomeUiThing()
{
    SqlController sc = new SqlController();
    sc.openConnection();
    YourData = sc.getSomeData();
    sc.closeConnection();
}

Hope that helps! 希望有所帮助!

PS: Everyone has his own programming-style. PS:每个人都有自己的编程风格。 You have to see what fits for your application and what is the most comfortable way for you. 你必须看看什么适合你的应用程序,什么是最舒适的方式。

如果您正在使用MVC,请下载Spring Boot依赖项并将其放在您的application.properties ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM