java - Hibernate - 将关系及其管理委托(delegate)给子类以保持整洁

标签 java hibernate spring-boot relationship

现在我有一个 User 实体,其中包含其特定字段,如 id、name、password。用户也是 Item 实体的所有者,它们是多对一关系,反之亦然:

@Entity
@Table(name="users")
public class User {
    /* Id, name, password etc - strictly User specified */



    private List<Item> ownedItems;
    private List<Bike> ownedConsumables;


    @OneToMany(fetch = FetchType.EAGER, mappedBy = "owner")
    @Fetch(FetchMode.SELECT)
    public List<Item> getOwnedItems() {
        return ownedItems;
    }

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "owner")
    @Fetch(FetchMode.SELECT)
    public List<Consumable> getOwnedConsumables() {
        return ownedConsumables;
    }




    // a lot of methods to manage collections to keep one-to-many consistency 
    // which are not related to strictly to User entity
}

由于与此类组织(双向)相关的许多一致性问题,我想通过正确实现 addItem、removeItem 等方法来自行管理它们。这些与 User 实体没有直接关系,我认为我应该将此责任移交给另一个类(class)。我想到了:

@Table(name="users")
public class User {
    /* Id, name, password etc - strictly User specified */

    private Inventory inventory;
}




public class Inventory {
    private User owner; // if needed - I think it will

    private List<Item> ownedItems;
    private List<Bike> ownedConsumables;


    @OneToMany(fetch = FetchType.EAGER, mappedBy = "owner")
    @Fetch(FetchMode.SELECT)
    public List<Item> getOwnedItems() {
        return ownedItems;
    }

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "owner")
    @Fetch(FetchMode.SELECT)
    public List<Consumable> getOwnedConsumables() {
        return ownedConsumables;
    }

    // a lot of methods to manage collections to keep one-to-many consistency 
}

这可能与 Hibernate 有关吗?如何映射所有内容以正确填充这些集合?

另一个想法是创建一个类来检索 User 对象并管理集合,但这需要通过 getter 公开ownedItems 和ownedConsumables 字段。看起来更糟糕。

最佳答案

您可以通过使用 @Embeddable 注释该类并使用 @Embedded 注释字段 inventory 来实现此目的。

关于java - Hibernate - 将关系及其管理委托(delegate)给子类以保持整洁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43868964/

相关文章:

java - Spring Boot 测试类可以重用应用程序上下文以更快地运行测试吗?

spring-boot - 无法在 spring-boot 应用程序中从 Consul 读取配置

java - 在 Eclipse 的 persistence.xml 中设置环境变量值

java - CascadeType 与 FetchType

java - 使用 PHP 脚本在 Java 中创建树结构

hibernate - 如何在 Tapestry 相关项目中测试 DAO 层

多个实例上的 Spring 和计划任务

java - 单个文件中多个顶级 Java 类的用例?

java - DynamoDB 等待表变为 Activity 状态

java - PDF 生成的高级接口(interface)