开发者

Good way to get values from Database

开发者 https://www.devze.com 2023-02-19 06:29 出处:网络
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

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 ty开发者_开发问答pe and want to put it in...

do anyone know a good implementation of a database abstraction layer or something which i can use?

thanks!


You have a few options here:

  • JDBC - For low level access to databases
  • ORM like Hibernate - For higher level access

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:

how can i access the database from whole program

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.

how i can get the right object type?

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:

session.createCriteria(MyMappedObject.class).list()

What is the best way to insert or update values?

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:

session.saveOrUpdate(myObject);

do anyone know a good implementation of a database abstraction layer or something which i can use?

Hibernate or most of the other JPA 2.0 ORMs sound like what you need.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号