第1个回答 2011-01-13
这个就要借助hibernate tools跟xdoclet来完成了;
首先你要在你的java代码里应用xdoclet标签,例如
Java code
private String name;
/**
* @hibernate.property column = "name" length = "50"
*/
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
其中,写到javadoc上的@hibernate.property column = "name" length = "50"
就是xdoclet标签,它需要xdoclet程序来处理,这里就需要用到hibernate tools。
具体做的话一般情况是建一个ant脚本来完成,例如:
XML code
<target name="hibernate-xdoclet" depends="init, init-xdoclet_hibernate"
description="Generate mapping documents">
<echo>+---------------------------------------------------+</echo>
<echo>| |</echo>
<echo>| R U N N I N G H I B E R N A T E D O C L E T |</echo>
<echo>| |</echo>
<echo>+---------------------------------------------------+</echo>
<delete>
<fileset dir="$" includes="hibernate.cfg.xml" />
</delete>
<echo message="hibernate.cfg.xml at $"></echo>
<sleep seconds="1"/>
<hibernatedoclet
destdir="$"
excludedtags="@version,@author,@todo,@see"
addedtags="@xdoclet-generated at $,@copyright The XDoclet Team,@author XDoclet,@version $"
force="false"
verbose="true">
<fileset dir="$">
<include name="com/**/model/**/*.java"/>
</fileset>
<hibernatecfg
version="3.0"
destDir="$"
dialect="org.hibernate.dialect.Oracle9Dialect"
driver="oracle.jdbc.driver.OracleDriver"
jdbcUrl="jdbc:oracle:thin:@localhost:1521:RESDL"
userName="test"
password="123"
showSql="true"
schema="true"
validateXML="true"
/>
<hibernate version="3.0"/>
</hibernatedoclet>
</target>
上面的代码是生成hbm跟cfg文件的,下面再介绍如何从java类到数据库:
XML code
<target name="hibernate-schema" depends="init, init-hibernate-schema"
description="Generate DB schema from the O/R mapping files">
<echo>+---------------------------------------------------+</echo>
<echo>| |</echo>
<echo>| R U N N I N G D B S C H E M A |</echo>
<echo>| |</echo>
<echo>+---------------------------------------------------+</echo>
<echo message="mysql.sql at etc/hbm2doc"></echo>
<sleep seconds="1"/>
<hibernatetool destdir="etc/hbm2doc">
<configuration propertyFile="$/hibernate.properties">
<fileset dir="$">
<include name="com/**/model/**/*.hbm.xml"/>
</fileset>
</configuration>
<hbm2ddl drop="true"
outputfilename="mysql.sql"/>
<hbm2doc/>
</hibernatetool>
</target>
当然ant工程里的一些初始化需要自己定义,我这里只摘录关键部分,具体的东西请查阅相关文档,hibernate tutorail里就有个例子