我是DAO世界的新手。我有3张桌子。
消费者表包含以下字段
比尔表包含
收据表包含
比尔表与消费者表有 多对一 关系,收据 table还与消费者表有 多对一 关系。
目前我已经创建了三个类
为他们创建了DADA,例如ConsumerDAO,BillDAO,ReceiptDAO。它们包含基本的CRUD操作。
现在我想要一个涉及这三个表中数据的消费者列表。我正在使用JOIN SQL查询。它如下:
SELECT c.consumer_id,
c.consumer_name,
c.address,
r.receipt_no,
r.pay_date,
r.paid_amount,
b.bill_date,
b.bill_number,
b.bill_amount
FROM consumer c
LEFT OUTER JOIN
(SELECT r.consumer_id,
r.pay_date,
r.receipt_number,
r.paid_amount,
ROW_NUMBER() OVER (PARTITION BY r.consumer_id
ORDER BY r.pay_date) AS rank
FROM receipt r) r ON (c.consumer_id = r.consumer_id
AND r.rank = 1)
LEFT OUTER JOIN
(SELECT b.consumer_id,
b.bill_number,
b.bill_date,
b.bill_amount,
ROW_NUMBER() OVER (PARTITION BY b.consumer_id
ORDER BY b.bill_date) AS rank
FROM bill b) b ON (c.consumer_id = b.consumer_id
AND b.rank = 1)";
我想知道在哪个DAO我应该放置这个查询?我想在消费者类中添加 比尔字段 和 收据字段 并在 ConsumerDAO 中添加 getCurrentBillAndReceipt() 方法。这是正确的做法吗?
我读了以下问题:
how to create a DAO for join tables
还有一些,但我无法理解。
答案 0 :(得分:5)
如果您需要访问每位消费者的最新收单/收据,而不是尝试像这样进行查询,那么如果您的Consumer
POJO成为以下内容会怎样:
public class Consumer {
private Integer consumerId;
private String consumerName;
private String address;
// join data into these variables
private Set<Bill> bills = new Set<Bill>(0);
private Set<Receipt> recipts = new Set<Receipt>(0);
// add constructor and getter/setter methods here
}
然后,在ConsumerDAO
中,您的find
方法可能具有以下逻辑:
public class ConsumerDAO {
/*
* Find a consumer without any transaction data JOINed in
*/
public Consumer find(Integer consumerId){
// create a new Consumer object
// run SQL query to populate consumerId, consumerName, and address fields of new Consumer object
// return new Consumer object
}
/*
* Find a consumer with all transaction data JOINed in
*/
public Consumer findWithTransactionData(Integer consumerId){
// create new consumer object
// run a query to get the the basic fields of the Consumer POJO, that also uses
// JOINs to get all of the consumer's Bills and Receipts; store all of the latter
// in the Consumer object's Sets
// return consumer object
}
/*** Note that the following two methods could even go in the Consumer class at this point ***/
public Bill getMostRecentBill(Consumer consumer){
// iterate through the consumer's bills, and return the most recent one
}
public Receipt getMostRecentReceipt(Consumer consumer){
// iterate through the consumer's receipts, and return the most recent one
}
}
这是你想要做的吗?我认为最有意义的是找到最新的&#34; Consumer
类本身的方法,因为您不必将任何内容作为参数传递给方法;如果您愿意,可以在getMostRecentBill()
上的Consumer对象上调用findWithTransactionData(Integer)
。然而,这通常被认为是一种糟糕的做法,因为POJO应该是愚蠢的#34;尽可能。因此,您希望如何处理这一点取决于您。