为组合类创建 DAO 类的正确方法是啥
Posted
技术标签:
【中文标题】为组合类创建 DAO 类的正确方法是啥【英文标题】:What's the correct way to create an DAO class for an a composition class为组合类创建 DAO 类的正确方法是什么 【发布时间】:2021-06-27 15:11:58 【问题描述】:我正在做这个“B”类,它具有“C”和/或“D”类公共属性,我将在其父类“A”中实现这些属性,例如继承个人值的客户和员工,在这种情况下,我正在替换组合的继承,现在我不想使用 ORM 框架,我是否会有一个 BDAO 和 CDAO,它会唤起 ADAO 在 BD 中建立关联或在 B 和 C 表中创建每个 A 属性?
public class A
public long ID;
public int attributeA;
public class B
public long ID;
public int attributeB;
A a = new A();
public class C
public long ID;
public int attributeC;
A a = new A();
public class Main
public static void main(String[] args)
B bObject = new B();
bObject.attributeB=0;
A aObject = new A();
aObject.attributeA=1;
bObject.A=a;
public class BDAO
public void add(B b)
Conn.preparedStatement("insert into bTable (id,attributeB,FK_idA)
values("b.ID+","+b.attributeB+","+b.A.id+")").execute();
new ADAO().add(B.a);
public class CDAO
public void add(C C)
Conn.preparedStatement(...
new ADAO().add(A.a);
public class ADAO
public void add(A a)
Conn.preparedStatement("insert into aTable (id,attributeA)
values ("a.ID+","+a.attributeA+")").execute();
【问题讨论】:
【参考方案1】:如果您使用的是 Java 14 及更高版本,则可以使用 record
类来创建 DO。
public record A(long ID, int attributeA)
public record B(long ID, int attributeB, A a)
public record C(long ID, int attributeC, A a)
您不必编写 getter 方法和其他东西。有关详细信息,请参阅 https://blogs.oracle.com/javamagazine/records-come-to-javaTutorial
【讨论】:
这与问题无关。【参考方案2】:我认为你应该像这样使用composite design pattern 和DTO:
import lombok.AllArgsConstructor;
import lombok.ToString;
@ToString
@AllArgsConstructor
class A
public long ID;
public int attributeA;
@ToString
@AllArgsConstructor
class B
public long ID;
public int attributeB;
@ToString
@AllArgsConstructor
class C
public long ID;
public int attributeC;
// DTO class
@AllArgsConstructor
class ABC
public long ID;
public int attributeA;
public int attributeB;
public int attributeC;
class ADAO
public void add(A a)
// query
System.out.println("add a: " + a);
class BDAO
public void add(B b)
// query
System.out.println("add b: " + b);
class CDAO
public void add(C c)
// query
System.out.println("add c: " + c);
// composite class
@AllArgsConstructor
class ABCService
private final ADAO adao;
private final BDAO bdao;
private final CDAO cdao;
public void add(ABC abc)
adao.add(new A(abc.ID, abc.attributeA));
bdao.add(new B(abc.ID, abc.attributeB));
cdao.add(new C(abc.ID, abc.attributeC));
public class Main
public static void main(String[] args)
ABCService abcService = new ABCService(new ADAO(), new BDAO(), new CDAO());
abcService.add(new ABC(1, 123, 456, 789));
【讨论】:
B 包含 A,C 包含 A。以上是关于为组合类创建 DAO 类的正确方法是啥的主要内容,如果未能解决你的问题,请参考以下文章