英文:
how to run some code whenever function from particular class is called in java
问题
我用Java制作了一个简单的控制台应用程序,关于银行,我们可以创建账户,然后存款并在账户内进行其他交易,目前只是内存应用程序,现在我想将账户数据和交易日志存储在pgsql数据库中。
我创建了一个新的DAO文件,以便我可以导入帐户DAO和交易DAO中的函数。
我想要的是在调用任何数据库函数之前运行此代码
```java
conn = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/javaBank", "postgres", "puru2000");
conn.setAutoCommit(false);
以及在函数之后运行这个
conn.close();
我应该只需将此代码写在每个函数的开头和结尾,还是有更有效的方法来实现这一点。
如果需要参考,这是我的项目仓库链接:https://github.com/dexterpuru/java-banking
<details>
<summary>英文:</summary>
I made a simple console application in java, it is about bank, we can create accounts, then deposit money and do other transaction withing account, till now it is just in memory application, now I want to store account data and transaction logs in pgsql db.
I made a new DAO file, so i can import function in account DAO and transaction DAO.
What I want is to run this code before any database functions are called
conn = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/javaBank", "postgres", "puru2000");
conn.setAutoCommit(false);
and this after the the function
conn.close();
Should I just write this code in starting and ending of every function or is there is any efficient method to do this.
Here is my project repo if u need ref.`https://github.com/dexterpuru/java-banking`
</details>
# 答案1
**得分**: 1
我建议您对于这种应用程序使用Spring和Hibernate,如果您不想使用它们,那么您不应该在每个方法中打开连接。全局打开连接并设置`conn.setAutoCommit(true);`,然后在每个方法调用后执行一些命令并自动提交。通常情况下,频繁打开和关闭连接可能会在方法经常被调用时引发问题。
<details>
<summary>英文:</summary>
For this kind of application, I suggest you to use spring and hibernate, if you don't want to use it, then you should not open connection in every method. Open connection globally and set `conn.setAutoCommit(true);` and after each method call some command is executed and automatically commited. Commonly opening and closing connection can make problems if methods are called often.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论