How to dynamically add Entity in Hibernate?

2020-02-28 00:20发布

I'm a java developer. I'm using spring 4.0.1 and hibernate 4.2.21. I have a class as follow:

@Entity
@Inheritance(...)
public abstract class Feature{
   @Id
   @GeneratedValue
   protected Long id;

   ...

}

Now I have some many class as follow:

Label.java class:

@Entity
public class Label extends Feature{
   protected String str;

   ...
}

Point.java class:

@Entity
public class Point extends Feature{
   protected Integer intg;

   ...
}

I have more than 20 Entity class that extends from Feature class. Is there any way to add dynamically this classes(such as Label and Point) to the project without writing hard code?

update:

For example, Hibernate get data from a database and then according this data, create models.

  1. Is it possible?
  2. How do I do?

7条回答
够拽才男人
2楼-- · 2020-02-28 00:59

Do not repeat yourself.

If you really need those classes use an IDE (like eclipse) to generate the classes. Or use generics and inheritance to create only one class that is capable of storing Strings as well as Integers.

But if you do not actually need classes, generate SQL (not JPQL nor HQL) and to store the data in java.util.Map and similar data structures.

Classes are good for:

  • type safety
  • combining logic (methods) with data (fields)
  • describing relationships

In your case you might only need:

  • store structured data at runtime.
查看更多
家丑人穷心不美
3楼-- · 2020-02-28 01:02

I think you can use Hibernate Reverse Engineering to generate Entity for all the database tables. Please refer this Link. That will explained step by step process to generate entity from database using hibernate reverse engineering.

查看更多
倾城 Initia
4楼-- · 2020-02-28 01:02

I think its not a good database design that needs to be changed dynamically. It sounds verbose and not consistent. Observe your domain again and try to design a proper entity relationships that wouldnt be changed over run time.

查看更多
老娘就宠你
5楼-- · 2020-02-28 01:05

As I understand you need to develop a tool, collects table names that have one-to-one relationship with Feature table.

My suggestion is like that (tested with Oracle):

1) From your DB, get tables metadata who is referancing your Feature table. Below will print your Label, Point, etc tables who has foreign key relation to your table.
If you want to only generate a subset (irrelevant tables might has this relationship too) may be you put a common foreign key column name and filter out non-related tables with a help of such marking.

Connection connection = jdbcTemplate.getDataSource().getConnection();
DatabaseMetaData metaData = connection.getMetaData();

ResultSet exportedKeys = metaData.getExportedKeys(connection.getCatalog(), "<your_schema_name>", "FEATURE");
while (exportedKeys.next()){
    String fkTableName = exportedKeys.getString("FKTABLE_NAME");
    String fkColumnName = exportedKeys.getString("FKCOLUMN_NAME");  
    System.out.println("[fkTableName:" + fkTableName + "], [fkColumnName" + fkColumnName + "]");
}
exportedKeys.close();


2) For the tables you collected above, for each table of our concern, get table metadata for the types and columns.

ResultSet columns = metaData.getColumns(connection.getCatalog(), "<your_schema_name>", "<your_table_name>", null);
while (columns.next()){
    String columnName = columns.getString("COLUMN_NAME");
    String typeName = columns.getString("TYPE_NAME");
    System.out.println("[columnName:" + columnName + "], [typeName" + typeName + "]");
}
columns.close();


3) According to result from 2 generate your Java classes. With fields, getter setters, annotations etc. Then copy them into your source directory. You know the rest :)

Hope this is helpful.

查看更多
贼婆χ
6楼-- · 2020-02-28 01:08

I think you could do this with eclipse, but the classes had to be modified more or less to preserve the inheritance hierarchy.

  • Righ click on the project name and select Properties
  • Use project facets if project facets not enabled

enter image description here

  • Click the JPA if it's not selected, then click OK to close the project properties window.

  • After enabling JPA in project properties, now right click you eclipse project name again, you should see a new context menu item JPA tools appears. Choose Generate Entities from tables

enter image description here

Select a database connection to let Eclipse get the tables used to generated class from.

Here is how to setup db in eclipse

  • It's better to create the entities in a dummy project using the above method and copy the Entity classes to the real project.

  • Eclipse's Class refactoring may be used to preserve the inheritance hierarchy that you want.

Hope this helps.

查看更多
淡お忘
7楼-- · 2020-02-28 01:14

I think you want to generate your entity class at runtime instead of that you have to write your java file and compile it and so on. If this is your requirement you can use a byte code generator like javassist to generate and annotate your class file at runtime. Then you can persist it to your table using JPA, Hibernate and any other ORM framework. I am writting a class generator base on xml file.In future days it will be finished and I will give you a link to my github. So you can use that to generate your entity classes. have a nice day:)

查看更多
登录 后发表回答