从数据库获取值的好方法
有没有从java数据库中获取值的最佳实践? 我的特殊问题是:
- 我如何从整个程序访问数据库(我使用带有 init 方法的静态类,该方法被调用一次,然后同步块)
- 如何获得正确的对象类型?使用像
Object getSingeValue(String query)...
这样的方法,然后在该方法中使用 ResultMetaSet 进行比较,这是一个好方法吗? - 插入或更新值的最佳方法是什么?我知道类型并想将其放入...
有人知道数据库抽象层的良好实现或我可以使用的东西吗?
谢谢!
is there a best practise to get values from a database in java?
my special questions are:
- how can i access the database from whole programm (i use static class with init method which is called once and then sycronized blocks)
- how i can get the right object type? is it a good way to have a method like
Object getSingeValue(String query)...
and then make comperison inside this method which type it is with ResultMetaSet? - What is the best way to insert or update values? I know the type and want to put it in...
do anyone know a good implementation of a database abstraction layer or something which i can use?
thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在这里有几个选择:
根据您的问题,听起来您想使用对象到关系映射工具(如 Hibernate 或其他工具之一)基于 JPA 的 ORM 工具。这些通常会为您提供一种高级方法来查询数据库并返回完全形成的 Java 对象。
回答您的问题:
这通常不是由数据库层解决的问题,而是由诸如依赖注入之类的设计模式解决的问题,它为您提供了一种构建所有对象并将适当的依赖项传递给它们的方法(例如数据库连接)。有关 DI 实际应用的示例,请参阅 Spring 框架。
ORM 工具通常会在特定表和 Java 对象之间建立关系。也就是说,即使使用 ORM,您也将提交所需对象的“模板”,因此如果您编写自己的对象,通常会使用这样的模式:
同样,ORM 会有所帮助,并且该模式通常只是交出您想要保存的对象。您可以使用 XML 或注释等外部配置,以便对象到关系映射层知道如何将对象转换为适当的行和列。在像 Hibernate 这样的标准 ORM 中保存或更新就非常简单:
Hibernate 或大多数其他 JPA 2.0 ORM 听起来就像您所需要的。
You have a few options here:
Based on your question, it sounds like you'd like to use an Object to Relational mapping tool like Hibernate or one of the other JPA based ORM tools. These will typically give you a high level way to query your database and return fully formed Java Objects.
To answer your questions:
This is usually not a problem solved by a database layer but instead by a design pattern like Dependency Injection which gives you a way to construct all of your objects and hand the appropriate dependencies to them (e.g. a database connection). See the Spring Framework for an example of DI in action.
ORM tools will typically set up a relationship between a particular table and a Java Object. That said, even with ORMs, you're going to hand in a 'template' of the object you want, so if you're writing your own, a pattern like this is often used:
Again, an ORM is going to help and the pattern is typically just to hand in the object you'd like to save. You can use external configuration like XML or annotations so that your object to relational mapping layer knows how to transform your object into the appropriate rows and columns. A save or update in a standard ORM like Hibernate is then as simple as:
Hibernate or most of the other JPA 2.0 ORMs sound like what you need.