简体   繁体   English

在Hibernate中将两个类映射到一个DB表

[英]map two classes to one DB table in Hibernate

I have 2 class Class1.java and Class2.java. 我有2类Class1.java和Class2.java。 Both are mapped to Class Table. 两者都映射到类表。

@Entity
@Table(name = "Class")
public class Class1 {
 String name;
}

@Entity
@Table(name = "Class")
public class Class2 {
  String name;
}

Now when my sessionfactory will be created at that time both the class will be scanned and both will consume memory. 现在,当我的sessionfactory在那时创建时,两个类都将被扫描,并且两个都将占用内存。

But in my application when it boot up we are deciding at runtime which class will be used in whole application either Class1.java or Class2.java by looking into database. 但是在我的应用程序启动时,我们通过查看数据库来决定在运行时在整个应用程序中使用哪个类(Class1.java或Class2.java)。

So I want hibernate to use either of the class Class1.java or Class2.java so that I can save memory. 因此,我希望休眠使用Class1.java或Class2.java类,以便节省内存。 Please help with this issue. 请帮助解决此问题。

We are able to do it in following way. 我们能够通过以下方式做到这一点。

We are using Spring so used the concept of creating bean by annotation ie JavaConfig. 我们正在使用Spring,因此使用了通过注释即JavaConfig创建bean的概念。

for eg 例如

@Configuration
public class BeanFactory {

@Bean(name = "sessionFactory")
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource); // datasource injected using @Autowire
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;
    String[] packageToScan = new String[] {"your package"};
    try {
        Class.forName("com.mysql.jdbc.Driver");
        connection = DriverManager.getConnection("", "", "");
        statement = connection.createStatement();
        resultSet = statement.executeQuery("query to get packagetoscan property.");
        if (resultSet.next()){
            packageToScan[0] = resultSet.getString(1);
        }
    }catch (Exception e){
        e.printStackTrace();
    }
    sessionFactory.setPackagesToScan(packageToScan);
    sessionFactory.setHibernateProperties(hibernateProperties()); // hibernateProperties() method will return properties.
    return sessionFactory;
}

so this way we can change packagetoscan property in database and when our application is booting up it will get this property from database and we are able to save memory. 因此,通过这种方式,我们可以更改数据库中的packagetoscan属性,并且在应用程序启动时,它将从数据库获取此属性,并且我们可以节省内存。

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

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