简体   繁体   English

使用Hibernate建模Java类的最佳实践是什么?

[英]What is the best practice for modeling Java classes with Hibernate?

I have a question about what would be the best practice for modeling my Java classes and how they should be related in the database. 我有一个关于对Java类进行建模的最佳实践是什么以及如何在数据库中进行关联的问题。 I'm using Spring-Boot and Spring-Data in the project 我在项目中使用Spring-BootSpring-Data

I have the situation containing professional Administrative, Professional Financial and Professional Developer. 我遇到的情况包括专业的行政,专业财务和专业开发人员。 Each of them have specific characteristics. 它们每个都有特定的特征。

So, I created a Professional class with the attibutos that are common to all employees: 因此,我创建了一个带有所有员工共同的attibutos的Professional类:

Professional Class 专业班

@Entity
@Table(name = "Professional")
@Inheritance(strategy = InheritanceType.JOINED)
public class Professional {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String age;

    ... getters e setters
}

The other classes, extend from the professional class: 其他班级,从专业班级扩展:

Administrative Class 行政班

@Entity
public class Administrative extends Professional {
    private String attribute1;
    private String attribute2;

    ... getters e setters
}

Financial Class 金融类

@Entity
public class Financial extends Professional {
    private String attribute1;
    private String attribute2;

    ... getters e setters
}

Developer Class 开发人员类别

@Entity
public class Developer extends Professional {
    private String attribute1;
    private String attribute2;

    ... getters e setters
}

Is this the most appropriate way to handle this scenario? 这是处理这种情况的最合适的方法吗? Should I use Class Composition instead of Inheritance? 我应该使用类组成而不是继承吗? Could you please share examples? 您能分享一些例子吗?

Thank you 谢谢

Inheritance makes more sense here. 继承在这里更有意义。 As an example, composition makes sense where an entity has another entity, eg 例如,在一个实体具有另一个实体(例如,

class Adult extends Person {
    private List<Animal> pets; // person HAS pets (with are another class)
    private ID identityCard; // person HAS an identity card
}

It wouldn't make sense here for a Person to extend either of Animal or ID because they aren't a subset of either. 在此,对于Person而言,扩展AnimalID都是没有意义的,因为它们不是二者之一。 However, they are a child of the Person class so it makes sense to inherit. 但是,它们是Person类的子级,因此继承是有意义的。

In your case inheritance makes sense because your child classes are a subset of the Professional. 在您的情况下,继承是有意义的,因为子类 Professional的子集。 You wouldn't say that a Developer has a Professional, but they are a Professional. 您不会说开发人员专业人员,但是他们专业人员。

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

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