ORM Inheritance

2020-08-13 05:12发布

Has anyone really wanted and used inheritance support on ORM tools, and if yes which one do you think offers the best support?

Or is ORM Inheritance a "pie in the sky" concept?

4条回答
混吃等死
2楼-- · 2020-08-13 05:50

I have used inheritance with Hibernate (and some with Django), and regreted it dearly.

The "composition over inheritance" principle is especially true for domain classes. While I agree that there is a few cases where inheritance makes sense at the model level, in most cases inheritance will give you a very static domain model, where one object will not be able to change to another class.

I also find that most developers are not comfortable with the concept of inheritance at the database level, so maintenance becomes more complicated.

And last, there are some technical problems, like proxies put in place by Hibernate that will hide the actuall class of an object. It makes "instance of" behave stangely. Of course, you might say that "instance of" is a code smell and that maybe it is another hint that composition is probably a better solution ...

查看更多
三岁会撩人
3楼-- · 2020-08-13 05:56

If you're writing complex business software, you need it.

Let's say you want to be able to sell stuff to individuals or organizations. On a sales order, the buyer would be one or the other. How do you do that without inheritance?

With inheritance, you'd do something like this:

@Entity
@Inheritance
public abstract class Party {

  @Id
  private Long id;

  ...
}

@Entity
public class Individual extends Party {
  ...
}

@Entity
public class Organization extends Party {
  ...
}

@Entity
public class SalesOrder {

  private Party buyer;

  ...
}

Then you can do:

salesOrder.setBuyer(someOrganization) or salesOrder.setBuyer(someIndividual)

查看更多
等我变得足够好
4楼-- · 2020-08-13 06:02

If you mean inheritance in the domain classes, I use it all the time with NHibernate and/or Castle ActiveRecord, they support the three mapping strategies:

查看更多
啃猪蹄的小仙女
5楼-- · 2020-08-13 06:11

I like this question a lot. I've used ORM tools (Toplink, now eclipselink, Hibernate) for a while and I've always seen this as referenced in JPA documents but I've never really had a need for it. Basically my philosophy is the ORM is just there to prevent you from writing tedius code to pull out records for the database. That really is the huge timesaver and it prevents you from making stupid mistakes. Sure you can do fancy stuff with this, but why not save it for the controller (if you're following MVC) than stick it in the model?

查看更多
登录 后发表回答