So our project use PostgreSQL database and we use JPA for operating the database. We have created the entities from the database with automatic creator in Netbeans 7.1.2.
You can also save yourself some effort by writing a script to perform a mass conversion of the generic GenerationType.IDENTITY
to the solution proposed by the selected answer. The below script has some slight dependencies on how the Java source file is formatted and will make modifications without backups. Caveat emptor!
After running the script:
import javax.persistence.Table;
with
import javax.persistence.Table; import javax.persistence.SequenceGenerator;
.Save the following script as update-sequences.sh
or similar:
#!/bin/bash
# Change this to the directory name (package name) where the entities reside.
PACKAGE=com/domain/project/entities
# Change this to the path where the Java source files are located.
cd src/main/java
for i in $(find $PACKAGE/*.java -type f); do
# Only process classes that have an IDENTITY sequence.
if grep "GenerationType.IDENTITY" $i > /dev/null; then
# Extract the table name line.
LINE_TABLE_NAME=$(grep -m 1 @Table $i | awk '{print $4;}')
# Trim the quotes (if present).
TABLE_NAME=${LINE_TABLE_NAME//\"}
# Trim the comma (if present).
TABLE_NAME=${TABLE_NAME//,}
# Extract the column name line.
LINE_COLUMN_NAME=$(grep -m 1 -C1 -A3 @Id $i | tail -1)
COLUMN_NAME=$(echo $LINE_COLUMN_NAME | awk '{print $4;}')
COLUMN_NAME=${COLUMN_NAME//\"}
COLUMN_NAME=${COLUMN_NAME//,}
# PostgreSQL sequence name.
SEQUENCE_NAME="${TABLE_NAME}_${COLUMN_NAME}_seq"
LINE_SEQ_GENERATOR="@SequenceGenerator( name = \"$SEQUENCE_NAME\", sequenceName = \"$SEQUENCE_NAME\", allocationSize = 1 )"
LINE_GENERATED_VAL="@GeneratedValue( strategy = GenerationType.SEQUENCE, generator = \"$SEQUENCE_NAME\" )"
LINE_COLUMN="@Column( name = \"$COLUMN_NAME\", updatable = false )\n"
# These will depend on source code formatting.
DELIM_BEGIN="@GeneratedValue( strategy = GenerationType.IDENTITY )"
# @Basic( optional = false ) is also replaced.
DELIM_ENDED="@Column( name = \"$COLUMN_NAME\" )"
# Replace these lines...
#
# $DELIM_BEGIN
# $DELIM_ENDED
#
# With these lines...
#
# $LINE_SEQ_GENERATOR
# $LINE_GENERATED_VAL
# $LINE_COLUMN
sed -i -n "/$DELIM_BEGIN/{:a;N;/$DELIM_ENDED/!ba;N;s/.*\n/$LINE_SEQ_GENERATOR\n$LINE_GENERATED_VAL\n$LINE_COLUMN/};p" $i
else
echo "Skipping $i ..."
fi
done
When generating the CRUD application using NetBeans, the ID attributes won't include editable input fields.