与为每个实体编写单独的方法相比,编写一个将Entity类作为参数的方法是一种好习惯吗?

Recently I'm using such methods that takes Entity class as a parameter than having separate method for each Entity class.

For example: if I've two Entity classes Client and Product.

  public void saveEntity(Object object) {
    try ( Session session = sessionFactory.openSession()) {
        Transaction transaction = session.beginTransaction();
        session.save(object);
        transaction.commit();
    }
}  

客户代码:

saveEntity(new Client("Sam"));

saveEntity(new Product("Retail Fx"));  

与编写类似的单独方法相比,这不会浪费时间和冗长的时间:

public void saveClient(Client client) { ...}
public void saveProduct(Product product) { ...}

那是个好习惯吗?

评论
  • qquasi
    qquasi 回复

    那正是您应该使用泛型的地方。防爆码:

    public <T> void saveEntity(T t) {
        try ( Session session = sessionFactory.openSession()) {
            Transaction transaction = session.beginTransaction();
            session.save(t);
            transaction.commit();
        }
    }