Existe alguma forma de criar automaticamentec com uso do Ant e a partir de SQL-DDL ou mapeamentos XML, os POJOS já com Annotation? Como devo proceder? Exemplos…
Obrigado e até breve : )
Olha com a DDL eu não conheço e creio que até agora não dê. Mas o que vc precisa é gerar código Java apartir de mapeamentos em XML?
Muitas vezes trabalho com banco de dados já pré-definidos grandes, e com dados já inseridos. Bem, do banco de dados consigo gerar os arquivos de mapeamento (hbm.xml) usando o middlegen. E dele gero os pojos com hbm2java, ambos pelo Ant. Já que tenho o banco de dados já pré-definido, é muito chato, repetitivo e muito propenso a erros ter que gerar os Annotations na mão.
Mesmo assim, obrigado pela resposta!
Estou no aguardo de outras : )
Ah, sim, e preciso gerar o código java POJO, (ou beans, aquelas classes simples com getters e setters) mas já “anotadas”.
Use o HibernateToolTask. Você poderá fazer varias tarefas no banco com essa feature
Infelizmente só tenho exemplo do contrário, criar um *.hbm.xml, mas vou comentar onde provávelmente mudará:
<project basedir="." default=“init” name=“Test”>
<property name=“build.dir” value="."/>
<path id=“toolslib”>
<path location=“hibernate-tools.jar” />
<path location=“hibernate3.jar” />
<path location=“freemarker.jar” />
<path location=“mysql.jar” />
<path location=“javassist.jar” />
<path location=“commons-logging-1.0.4.jar”/>
<path location=“hibernate-annotations.jar”/>
<path location=“dom4j-1.6.1.jar”/>
<path location=“hibernate-commons-annotations.jar”/>
<path location=“ejb3-persistence.jar”/>
<path location=“commons-collections-2.1.1.jar”/>
<path location=“jtidy-r8-20060801.jar”/>
</path>
<taskdef name=“hibernatetool"
classname=“org.hibernate.tool.ant.HibernateToolTask"
classpathref=“toolslib” />
<target name=“init”>
<hibernatetool destdir=”${build.dir}/generated”>
<classpath>
<!-- it is in this classpath you put your classes dir, and/or jpa persistence compliant jar -->
<path location="${build.dir}/classes" />
</classpath>
<annotationconfiguration configurationfile=“hibernate.cfg.xml”/>
<hbm2hbmxml/> <!-- vai ficar tipo: hbmxml2hbm -->
</hibernatetool>
</target>
</project>
Fiz testes com o HibernateToolTask, mas não existe a tag “hbmxml2hbm”, ou algo parecido. Pesquisei no site do próprio hibernate em http://www.hibernate.org/hib_docs/tools/reference/en/html/ant.html. Se tiver mais sugestões, mande para eu ler.
Obrigado pela ajuda, e estou no aguardo de mais sugestões de todos.
Se você observar a documentação no link que enviou http://www.hibernate.org/hib_docs/tools/reference/en/html/ant.html verá que existe um paramentro 6 - “One or more of the exporters must be specified” : exportadores que serão utilizados.
Você deverá mesclar a configuração padrão a parte 4.4.2. POJO java code exporter <hbm2java> e 4.3.3. JPA based configuration <jpaconfiguration> .
<hbm2java> is a java codegenerator
Tag: <hbm2java> + <jpaconfiguration>.
As modificações estão enumeradas por linha.
Quando eu disse: “vai ficar tipo: hbmxml2hbm” não quer dizer: “vai ficar exatamente”, foi só uma intuição bem proxíma…
Manda ver…
Sds
Obrigado pela ajuda Fábio. Com ela consegui encontrar a solução para o que preciso, e deixarei aqui trecho do meu target responsável por converter os *.hbm.xml para Pojo + Annotation.
<target name="hbm2java" description="Generate .java from .hbm files.">
<taskdef name="hibernatetool"
classname="org.hibernate.tool.ant.HibernateToolTask"
classpathref="thisProject.classpath"/>
<hibernatetool destdir="${dest.model}">
<configuration>
<fileset dir="${src}">
<include name="**/*.hbm.xml"/>
</fileset>
</configuration>
<hbm2java jdk5="true" ejb3="true"/>
</hibernatetool>
</target>
Vejam que o importante neste exemplo é o a tag “hbm2java” com a prorpriedade ejb3=“true”. Esta propriedade que é responsável por gerar os Pojos anotados.
Até breve
Seguinte… tentei fazer o mesmo que você…
porém está exibindo a seguinte msg
[hibernatetool] Executing Hibernate Tool with a Standard Configuration
[hibernatetool] 1. task: hbm2java (Generates a set of .java files)
[hibernatetool] log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
[hibernatetool] log4j:WARN Please initialize the log4j system properly.
[hibernatetool] An exception occurred while running exporter #2:hbm2java (Generates a set of .java files)
[hibernatetool] To get the full stack trace run ant with -verbose
[hibernatetool] org.hibernate.tool.hbm2x.ExporterException: Error while processing Entity: com.ccne.bo.UF with template pojo/Pojo.ftl
[hibernatetool] freemarker.template.TemplateModelException: Method public java.lang.String org.hibernate.tool.hbm2x.pojo.BasicPOJOClass.getJavaTypeName(org.hibernate.mapping.Property,boolean) threw an exception when invoked on Entity: com.ccne.bo.UF
[hibernatetool] java.lang.reflect.InvocationTargetException
[hibernatetool] java.lang.NoSuchMethodError: org.apache.log4j.Logger.isTraceEnabled()Z
Eu adicionei as seguites libs no path.
hibernate-tools.jar
freemarker.jar
hibernate-annotations.jar
hibernate-commons-annotations.jar
ejb3-persistence.jar
hibernate3.jar
slf4j-api-1.5.2.jar
slf4j-log4j12.jar
javassist-3.4.GA.jar
dom4j-1.6.1.jar
jta-1.1.jar
antlr-2.7.6.jar
Sabe o que pode estar faltando?
[]´s