简体   繁体   English

我无法在Java中使用SQLite获得DAO / DTO模式

[英]I can't get the DAO/DTO pattern with SQLite in java

I've been trying to understand the DAO pattern but now I have not been successful . 我一直在尝试了解DAO模式,但现在没有成功。 Probably because I have not been able to apply what I've found on the internet to problem I try solve. 可能是因为我无法将在互联网上找到的信息应用到我尝试解决的问题上。 I want to encapsulate the database, do the things right. 我想封装数据库,做正确的事。

I did this so far, but i feel it's pretty useless. 到目前为止,我已经做到了,但是我觉得这毫无用处。

My DTO class: 我的DTO课程:

   public class PersonDTO{
        final public static String TABLE = "PEOPLE";
        private int id;
        private String name;
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }

My "DAO" 我的“ DAO”

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

public class PersonDAO {
    private Connection connection;
    private DTO dto;
    private Statement stmt = null;
    private String tableName;
    private Integer id;

    public PersonDAO() {

    }

    public PersonDTO getPerson(int id) {
        connection = ConnectionFactory.getInstance();
        PersonDTO person = new PersonDTO();
        try {
            stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM " + PersonDTO.TABLE +" WHERE ID = '"+id+"'");
            person.setId(rs.getInt("id"));
            person.setName(rs.getString("age"));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        closeConnection();
        return person;
    }

    public void save() {
        throw new UnsupportedOperationException(); //not implemented yet
    }

    public void update() {
        throw new UnsupportedOperationException(); //not implemented yet
    }

    public void delete() {
        throw new UnsupportedOperationException(); //not implemented yet
    }

    public List<DTO> getDTO(String filter) {
        return null;
    }

    protected void closeConnection() {
        try {
            connection.close();
            connection = null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

I can't get: 我不能得到:

  1. Which it is supposed to be the relationship between the DTO class and the DAO class. 它应该是DTO类和DAO类之间的关系。
  2. The DAO class has to have the methods for get the information from the database? DAO类必须具有从数据库中获取信息的方法吗?
  3. What is DTO class for, why just don't use a "Person" class instead?. DTO类的用途是什么,为什么不使用“ Person”类呢?

This is pretty frustrating. 这真令人沮丧。 I will be grateful with any help. 我将不胜感激。

Here in your example having a DTO may be useless, but it's not useless in general. 在您的示例中,拥有DTO可能没有用,但通常并非没有用。

DTO object is supposed to be output of a remote service (RMI/Web service request) . 假定DTO对象是remote service (RMI/Web service request)

An object that carries data between processes in order to reduce the number of method calls. 为了减少方法调用的数量而在进程之间传递数据的对象。

Ref : http://martinfowler.com/eaaCatalog/dataTransferObject.html 参考: http : //martinfowler.com/eaaCatalog/dataTransferObject.html

This object is supposed to carry data to reduce the number of method calls. 该对象应该携带数据以减少方法调用的次数。

As you have used PersonDTO to carry Person table data. 由于使用了PersonDTO来携带Person表数据。 However it's useless to create PersonDTO for just one object, instead just user Person . 但是,只为一个对象而不是用户Person创建PersonDTO是没有用的。

If you had a list of persons, or may be some other data that carries more information regarding the state of the request like below 如果您有一个人员列表,或者可能是一些其他数据,其中包含有关请求状态的更多信息,如下所示

public class PersonDTO {
    public List<Person> personList;
    public Fault fault;

    public class Fault {
        String faultCode;
        String faultMessage
    }

    public Date requestDate;
    public UUID requestId;
    public String requestSignature;

    ...
}

In this case it makes sense to use a DTO object as there's more to the response than just a person. 在这种情况下,使用DTO对象是有意义的,因为响应不仅仅是一个人。

DTO can also carry aggregated data. DTO还可以携带汇总数据。 It's supposed to be the outside view of your remote method. 它应该是您的远程方法的外部视图。 Normal object is private inside view for you only to interact with. 普通对象是内部私有视图,仅供您与之交互。

DAO stands for Data Access Object . DAO代表Data Access Object As its name indicates, its responsibility is the access of data. 顾名思义,它的责任是访问数据。 That means that it knows how to use a data connection to retrieve objects from the data store. 这意味着它知道如何使用数据连接从数据存储中检索对象。

DTO stands for Data Transfer Object . DTO代表Data Transfer Object Its responsibility is to encapsulate the data format in a programming language construct that makes it easy to use in code. 它的责任是将数据格式封装在易于在代码中使用的编程语言构造中。

In my opinion the DAO should deal in your object model, not in DTO 's. 我认为DAO应该处理您的对象模型,而不是DTO的对象模型。 In other words the interface should return Person not PersonDTO . 换句话说,该接口应返回Person而不是PersonDTO Internally to your DAO implementation it may be convenient to use a intermediary DTO object to assist you in fetching and storing your objects. DAO实现的内部,使用中间DTO对象来协助您获取和存储对象可能会很方便。 If you're using Hibernate and/or JPA, you would create a DTO with your JPA annotations on it for example. 如果您使用的是Hibernate和/或JPA,则可以创建一个带有JPA注释的DTO

Here's how I would implement: 这是我的实现方式:

// Define an interface for your DAO so you can mock in unit tests, or swap out an implementation if you decide not to use SQLite
public interface PersonDao {
    Person getPerson(int id) throws PersonDaoException;
}

// Write your implementation for SQLite. I fixed some design/implementation issues
class PersonDaoSqlite implements PersonDao {
    private final DataSource ds;

    public PersonDaoSqlite(DataSource ds) {
        this.ds = ds;
    }

    public Person getPerson(int id) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet result = null;

        // As of Java 7 and onwards, one can use try-with-resources here.
        try {
            connection = ds.getConnection();
            statement = connection.prepareStatement("SELECT * FROM PEOPLE WHERE ID = ?");
            statement .setInt(1, id);
            result = statement .executeQuery();

            Person person = new Person();
            person.setId(rs.getInt("id"));
            person.setName(rs.getString("age"));
        } catch (SQLException e) {
            throw new PersonDaoException(e);
        } finally {
            if (result != null) {
                result.close();
            }

            if (statement != null) {
                statement.close();
            }

            if (connection != null) {
                connection.close();
            }
        }
    }
}

public class PersonDaoException extends Exception {
     public PersonDaoException(Throwable cause) {
          super(cause);
     }
}

public class Person {
    private int id;
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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