有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java和MySQL如何在涉及外键时设计类

MySQL模式

建筑

id(主键),地址

房间

id(主键),buildingid(FK参考建筑表)

传感器

id(主键),房间id(FK参考房间表),已激活

Java类

public class Building {
    private int id;
    private String address;
    private List<Room> rooms;
}

public class Room {
    private int id;
    private List<Sensor> sensors;
}

public class Sensor {
    private int id;
    private boolean activated;
}

我有一个具有以下签名的方法

public Building getBuilding(int id) {
    // get address from building table
    // get rooms from room table
    // for each room
        // get sensors from sensor table
    // return building object
}

我不确定每次读取全部数据是否是个好主意。这里是否存在固有的设计问题?这里任何指向设计模式或最佳实践的指针都是有用的

另外,我以前没有使用过像Hibernate这样的框架


共 (1) 个答案

  1. # 1 楼答案

    这个问题有点宽泛,但我会试一试

    I am not sure if reading the entire data every time is a good idea

    理想情况下,您应该加载所需的确切数据量。如果你什么都需要,那就没办法了

    如果您有多个用例,需要有关建筑(或其他任何东西)的特定数据,可以创建多个类来表示它们,并使用不同的查询加载它们,例如:

    class BuildingWithAddress {
      int id
      String address;
    }
    
    class BuildingWithSensors {
      int id
      List<Sensor> sensors;
    }
    
    // etc.
    

    Is there an inherent design issue here?

    不需要。你设计的类看起来不错,根据你的用例,可能就足够了

    Any pointers to design patterns or best practices here would be useful.

    • 不要想得太多,从一个简单的解决方案开始
    • 通过多个类或lazy loading加载所需的数据
    • 避免执行多个查询来检索单个逻辑实体
    • 如有必要,denormalize your database