How can I generate entity (POJO) from database model using IntelliJ IDEA 10. I create "Data source" in IntelliJ but I have not any idea how can I generate the POJO.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
UPDATE:
In IntelliJ 16 this feature in now implemented.
The steps to do it are:
1. Database view context menu
2. Scripted Extensions
3. Generate POJOs
You can read more here:
Feature request: allow "generate classes from database schema" for plain-JDBC developers
First you need tell intelliJ that you are using Hibernate (I guess you are if you need the orm pojo of the table)
- Go to "Project structure" (alt+ctrl+shift+s)
- In "Project settings" select "Modules"
- Press + and add the Hibernate facet in your module.
Now you have setup your hibernate configuration facet you can extract your pojos.
- At your bottom right horizontal panel you will now see a tab called "Persistence" (ιf you can't find Persistence tab you may show it by choosing View > Tool Windows > Persistence)
- There you can right click on the hibernate icon named like your module
- Go to "Generate Persistence Mapping"-"by database schema"
- Now I guess you can find your way...
- In general settings select the datasource that you want to use and now you can see all the tables in your datasource object
- Now you can do many things, add relationships with the + sign, change the name and type of the pojo's properties etc. note: if you get an error and the "OK" is disabled its probably because the data type that intelliJ found for your pojo is invalid. Just change it to the one you need and you are ready to go!
回答2:
The default Scripted Extensions Generate POJOs.groovy
is not very good when dealing with tables with underscore(which is very common).
So I make some modifications.
The main code
def calcFields(DasObject table) {
DasUtil.getColumns(table).reduce([]) { fields, col ->
def spec = Case.LOWER.apply(col.dataType.specification)
def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
fields += [[
name : javaName(col.name, false),
type : typeStr,
annos: """
/**
* $col.comment
*/"""]]
}
}
static String javaName(String str, boolean capitalize) {
def s = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, str);
capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
You can find the whole gist here https://gist.github.com/aristotll/ad799a7462e8b705b26103944cca24a6