首页 > 解决方案 > 休眠实体不同的实现

问题描述

我有一个具有多个实现的项目和一个实体类 Person。在每个实现中都有不同的数据库、不同的表和不同的列。在 DAO 层和业务层,代码是相同的。如何仅更改持久层以具有基于配置文件的 Person 实体类的不同实现并保持其余代码不变?

//I would like to change table and columns based on a profile

@Entity
@Table(name = "person")
public class Person {


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    private Integer id;


    private String first_name;
    private String last_name

    //getters,setters

}


//I would like to keep DAO unchanged no matter the profile
public interface PersonDao {
    public List<Person> listAll() throws Exception;
}

public class PersonDaoImpl implements PersonDao{

    @Override
    public List<Person> listAll() throws Exception{


            CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
            CriteriaQuery<Person> criteria = criteriaBuilder.createQuery(Person.class);
            Root<Person> root = criteria.from(Person.class);

            ...the rest of the code
    }

}

标签: springhibernatemaven

解决方案


有一个通用的抽象 Person 和 PersonDao 将由其他类(例如 MongoPerson、MysqlPersonDao、PersonV2...根据您的要求)扩展/实现。但是在您的服务层中只使用 Person 和 PersonDao。

使用限定符配置自动装配 Spring


推荐阅读