简体   繁体   中英

What is the best design for a class that is responsible for CRUD operations on the database?

I want to create a class User that will manipulate data on the user table in my database. But I don't know if I should make it a Singleton or just bundle a bunch of static methods.

class UserSingleton {
    private static instance;

    private UserSingleton() {
        // stablish connection and prepare statements
    }

    public static getInstance() {
        if (instance == null) {
            instance = new UserSingleton();
        }

        return instance;
    }

    public void create() {};
    public void delete() {};
    // and so on...
}

class UserStatic {
    public static initialize() {
         // Stablish connection and prepare statements. 
         // These properties would be static.
    }

    public static void create() {};
    public static void delete() {};
    // and so on...
}

I really don't know what would be the best approach here or the pros and cons of each of them. While the singleton class seems more elegant and cool, the static class API would be easier to use since I don't have to instantiate an object. Also it resembles me of mongoose, where such methods are static, eg: Model.create() , Model.findById() , and so on...

What do you think? Or I should do it in a completely different manner? Some context about the app:

  • It's a small/medium desktop app made with JavaFX
  • The database is SQLite
  • Tests aren't a priority (some people may point out that Singleton is bad because it makes testing harder)

Take a look at JPA, Spring Data with eclipselink as implementation or Hibernate. If it is just for educational purpouses have a look at the spring orm implementaions.

  1. Avoid singletons at any cost
  2. You need to specify your API with interfaces. It appears that you have Users and User which could be defined like that
interface User {
    long id();
    String name();
}
interface Users {
    Iterable<User> iterate();
    User create(String name);
    void delete(User user);
    Optional<User> findById(long id);
}
  1. Implement these interfaces with plain jdbc or with help of a library such as jOOQ or jcabi-jdbc
  2. Avoid ORM and thinking about your business task in terms of databases and SQL. Use OOP tactics to design your objects and how they work with each other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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