How can I customize the DDL generated with Hibernate's hbm2ddl (using annotations)?
Here's what I want to do:
I'm using Hibernate (3.3.2) to map my Ingres 10 database. My java entities are generated after a meta model, so we decided to use annotations to ease things. What we want to do after the code generatio开发者_开发知识库n is generate the DDL instructions to create the database so we use the hbm2ddl tool and we have something like:drop table xxx;
create table xxx ...;
What I miss here are extra SQL statement to e.g. add privileges on tables, something like:
drop table xxx;
create table xxx ...;
grant xxx on table xxx;
I know I could use something called database-object to generate such statements but I think it's only available with the XML mapping. Can you confirm this?
If that is confirmed, do you see a better solution for doing such a thing? Many thanks to all.A little late, and not the prettiest solution, but here's a quick and dirty bash script to run in conjunction with maven. Hopefully it helps someone else grappling with this issue.
#!/bin/bash
SQL_FILE=$1
GROUP=$2
COMPILED=$1.tmp
SCHEMA_DROP=$3
if [ "$3" == "" ]; then
SCHEMA_DROP="true"
fi
mvn hibernate3:hbm2ddl -Dschema.file=$SQL_FILE -Dschema.drop=$SCHEMA_DROP
if [ "$SQL_FILE" == "" ] || [ "$GROUP" == "" ] ; then
echo "Usage: $0 {SQL_FILE} {GROUP} [DROP_SCHEMA]"
echo "Where: "
echo "SQL_FILE: path to sql file relative to the root of the project"
echo "GROUP: the predefined database group on which to grant access"
echo "DROP_SCHEMA: true|false per the hbm2ddl 'drop' parameter. Defaults to true"
echo "NOTE: In order for this to work properly, the pom configuration of the hibernatetool should be parameterized. For example:"
echo '<hbm2ddl outputfilename="../../../${schema.file}" format="true" drop="${schema.drop}" />'
exit;
fi
echo "" > $COMPILED
GRANT=""
while read line
do
echo $line >> $COMPILED
if [[ $line =~ .*create.table.([A-Za-z_-]*) ]]; then
GRANT="$GRANT\ngrant all on table ${BASH_REMATCH[1]} to group $GROUP;" >> $COMPILED
fi
done < $SQL_FILE
echo -e $GRANT >> $COMPILED
mv $COMPILED $SQL_FILE
I like to put my schema file into a src directory for check-in, such as src/main/db/myschema.sql, hence the dir up values in the outputfilename attribute (see the NOTE in the usage comments). To run this script with file name "genSchema.sh" from the root of the project in cygwin:
./genSchema.sh src/main/db/myschema.sql mygroup
The regexp and generated grant lines are for the postgresql dialect. They'd probably need a slight modification for other dialects.
I don't know Hibernate (only NHibernate) that much and I don't know these annotations stuff very well. But I'm pretty sure that this is only available in XML mapping files.
You may find a way to combine annotations and XML mappings. If this is not possible, consider to switch to XML entirely, it is generally more powerful and you get more control.
精彩评论