如何在Java中每当特定类的函数被调用时运行一些代码

huangapple go评论72阅读模式
英文:

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&#39;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>



huangapple
  • 本文由 发表于 2020年8月4日 04:53:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63236809.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定