11.4.3. About the INSERT Statement
HQL adds the ability to define
INSERTstatements. There is no JPQL equivalent to this. The BNF for an HQL
insert_statement ::= insert_clause select_statement insert_clause ::= INSERT INTO entity_name (attribute_list) attribute_list ::= state_field[, state_field ]*
attribute_listis analogous to the
column specificationin the SQL
INSERTstatement. For entities involved in mapped inheritance, only attributes directly defined on the named entity can be used in the
attribute_list. Superclass properties are not allowed and subclass properties do not make sense. In other words,
INSERTstatements are inherently non-polymorphic.
select_statementcan be any valid HQL select query, with the caveat that the return types must match the types expected by the insert. Currently, this is checked during query compilation rather than allowing the check to relegate to the database. This may cause problems between Hibernate Types which are equivalent as opposed to equal. For example, this might cause lead to issues with mismatches between an attribute mapped as a
org.hibernate.type.DateTypeand an attribute defined as a
org.hibernate.type.TimestampType, even though the database might not make a distinction or might be able to handle the conversion.
For the id attribute, the insert statement gives you two options. You can either explicitly specify the id property in the
attribute_list, in which case its value is taken from the corresponding select expression, or omit it from the
attribute_listin which case a generated value is used. This latter option is only available when using id generators that operate "in the database"; attempting to use this option with any "in memory" type generators will cause an exception during parsing.
For optimistic locking attributes, the insert statement again gives you two options. You can either specify the attribute in the
attribute_listin which case its value is taken from the corresponding select expressions, or omit it from the
attribute_listin which case the
seed valuedefined by the corresponding
Example 11.3. Example INSERT Query Statements
String hqlInsert = "insert into DelinquentAccount (id, name) select c.id, c.name from Customer c where ..."; int createdEntities = s.createQuery( hqlInsert ).executeUpdate();