1
//$Id: OneToManyPersister.java 10040 2006-06-22 19:51:43Z steve.ebersole@jboss.com $
2
package org.hibernate.persister.collection;
4
import java.io.Serializable;
5
import java.sql.PreparedStatement;
6
import java.sql.SQLException;
7
import java.util.Iterator;
9
import org.hibernate.HibernateException;
10
import org.hibernate.MappingException;
11
import org.hibernate.jdbc.Expectation;
12
import org.hibernate.jdbc.Expectations;
13
import org.hibernate.cache.CacheConcurrencyStrategy;
14
import org.hibernate.cache.CacheException;
15
import org.hibernate.cfg.Configuration;
16
import org.hibernate.collection.PersistentCollection;
17
import org.hibernate.engine.SessionFactoryImplementor;
18
import org.hibernate.engine.SessionImplementor;
19
import org.hibernate.engine.SubselectFetch;
20
import org.hibernate.exception.JDBCExceptionHelper;
21
import org.hibernate.loader.collection.BatchingCollectionInitializer;
22
import org.hibernate.loader.collection.CollectionInitializer;
23
import org.hibernate.loader.collection.SubselectOneToManyLoader;
24
import org.hibernate.loader.entity.CollectionElementLoader;
25
import org.hibernate.mapping.Collection;
26
import org.hibernate.persister.entity.Joinable;
27
import org.hibernate.persister.entity.OuterJoinLoadable;
28
import org.hibernate.pretty.MessageHelper;
29
import org.hibernate.sql.Update;
30
import org.hibernate.util.ArrayHelper;
33
* Collection persister for one-to-many associations.
37
public class OneToManyPersister extends AbstractCollectionPersister {
39
private final boolean cascadeDeleteEnabled;
40
private final boolean keyIsNullable;
41
private final boolean keyIsUpdateable;
43
protected boolean isRowDeleteEnabled() {
44
return keyIsUpdateable && keyIsNullable;
47
protected boolean isRowInsertEnabled() {
48
return keyIsUpdateable;
51
public boolean isCascadeDeleteEnabled() {
52
return cascadeDeleteEnabled;
55
public OneToManyPersister(Collection collection,
56
CacheConcurrencyStrategy cache,
58
SessionFactoryImplementor factory)
59
throws MappingException, CacheException {
60
super( collection, cache, cfg, factory );
61
cascadeDeleteEnabled = collection.getKey().isCascadeDeleteEnabled() &&
62
factory.getDialect().supportsCascadeDelete();
63
keyIsNullable = collection.getKey().isNullable();
64
keyIsUpdateable = collection.getKey().isUpdateable();
68
* Generate the SQL UPDATE that updates all the foreign keys to null
70
protected String generateDeleteString() {
72
Update update = new Update( getDialect() )
73
.setTableName( qualifiedTableName )
74
.addColumns( keyColumnNames, "null" )
75
.setPrimaryKeyColumnNames( keyColumnNames );
77
if ( hasIndex && !indexContainsFormula ) update.addColumns( indexColumnNames, "null" );
79
if ( hasWhere ) update.setWhere( sqlWhereString );
81
if ( getFactory().getSettings().isCommentsEnabled() ) {
82
update.setComment( "delete one-to-many " + getRole() );
85
return update.toStatementString();
89
* Generate the SQL UPDATE that updates a foreign key to a value
91
protected String generateInsertRowString() {
93
Update update = new Update( getDialect() )
94
.setTableName( qualifiedTableName )
95
.addColumns( keyColumnNames );
97
if ( hasIndex && !indexContainsFormula ) update.addColumns( indexColumnNames );
99
//identifier collections not supported for 1-to-many
100
if ( getFactory().getSettings().isCommentsEnabled() ) {
101
update.setComment( "create one-to-many row " + getRole() );
104
return update.setPrimaryKeyColumnNames( elementColumnNames )
105
.toStatementString();
109
* Not needed for one-to-many association
111
protected String generateUpdateRowString() {
116
* Generate the SQL UPDATE that updates a particular row's foreign
119
protected String generateDeleteRowString() {
121
Update update = new Update( getDialect() )
122
.setTableName( qualifiedTableName )
123
.addColumns( keyColumnNames, "null" );
125
if ( hasIndex && !indexContainsFormula ) update.addColumns( indexColumnNames, "null" );
127
if ( getFactory().getSettings().isCommentsEnabled() ) {
128
update.setComment( "delete one-to-many row " + getRole() );
131
//use a combination of foreign key columns and pk columns, since
132
//the ordering of removal and addition is not guaranteed when
133
//a child moves from one parent to another
134
String[] rowSelectColumnNames = ArrayHelper.join(keyColumnNames, elementColumnNames);
135
return update.setPrimaryKeyColumnNames( rowSelectColumnNames )
136
.toStatementString();
139
public boolean consumesEntityAlias() {
142
public boolean consumesCollectionAlias() {
146
public boolean isOneToMany() {
150
public boolean isManyToMany() {
154
protected int doUpdateRows(Serializable id, PersistentCollection collection, SessionImplementor session)
155
throws HibernateException {
157
// we finish all the "removes" first to take care of possible unique
158
// constraints and so that we can take better advantage of batching
162
if ( isRowDeleteEnabled() ) {
163
boolean useBatch = true;
164
PreparedStatement st = null;
165
// update removed rows fks to null
169
Iterator entries = collection.entries( this );
171
Expectation expectation = Expectations.NONE;
172
while ( entries.hasNext() ) {
174
Object entry = entries.next();
175
if ( collection.needsUpdating( entry, i, elementType ) ) { // will still be issued when it used to be null
177
String sql = getSQLDeleteRowString();
178
if ( isDeleteCallable() ) {
179
expectation = Expectations.appropriateExpectation( getDeleteCheckStyle() );
180
useBatch = expectation.canBeBatched();
182
? session.getBatcher().prepareBatchCallableStatement( sql )
183
: session.getBatcher().prepareCallableStatement( sql );
184
offset += expectation.prepare( st );
187
st = session.getBatcher().prepareBatchStatement( getSQLDeleteRowString() );
190
int loc = writeKey( st, id, offset, session );
191
writeElementToWhere( st, collection.getSnapshotElement(entry, i), loc, session );
193
session.getBatcher().addToBatch( expectation );
196
expectation.verifyOutcome( st.executeUpdate(), st, -1 );
203
catch ( SQLException sqle ) {
205
session.getBatcher().abortBatch( sqle );
211
session.getBatcher().closeStatement( st );
216
if ( isRowInsertEnabled() ) {
217
Expectation expectation = Expectations.appropriateExpectation( getInsertCheckStyle() );
218
boolean callable = isInsertCallable();
219
boolean useBatch = expectation.canBeBatched();
220
String sql = getSQLInsertRowString();
221
PreparedStatement st = null;
222
// now update all changed or added rows fks
225
Iterator entries = collection.entries( this );
226
while ( entries.hasNext() ) {
227
Object entry = entries.next();
229
if ( collection.needsUpdating( entry, i, elementType ) ) {
233
st = session.getBatcher().prepareBatchCallableStatement( sql );
236
st = session.getBatcher().prepareBatchStatement( sql );
242
st = session.getBatcher().prepareCallableStatement( sql );
245
st = session.getBatcher().prepareStatement( sql );
249
offset += expectation.prepare( st );
251
int loc = writeKey( st, id, offset, session );
252
if ( hasIndex && !indexContainsFormula ) {
253
loc = writeIndexToWhere( st, collection.getIndex( entry, i, this ), loc, session );
256
writeElementToWhere( st, collection.getElement( entry ), loc, session );
259
session.getBatcher().addToBatch( expectation );
262
expectation.verifyOutcome( st.executeUpdate(), st, -1 );
269
catch ( SQLException sqle ) {
271
session.getBatcher().abortBatch( sqle );
277
session.getBatcher().closeStatement( st );
284
catch ( SQLException sqle ) {
285
throw JDBCExceptionHelper.convert(
286
getSQLExceptionConverter(),
288
"could not update collection rows: " +
289
MessageHelper.collectionInfoString( this, id, getFactory() ),
290
getSQLInsertRowString()
295
public String selectFragment(
300
String collectionSuffix,
301
boolean includeCollectionColumns) {
302
StringBuffer buf = new StringBuffer();
303
if ( includeCollectionColumns ) {
304
// buf.append( selectFragment( lhsAlias, "" ) )//ignore suffix for collection columns!
305
buf.append( selectFragment( lhsAlias, collectionSuffix ) )
308
OuterJoinLoadable ojl = ( OuterJoinLoadable ) getElementPersister();
309
return buf.append( ojl.selectFragment( lhsAlias, entitySuffix ) )//use suffix for the entity columns
314
* Create the <tt>OneToManyLoader</tt>
316
* @see org.hibernate.loader.collection.OneToManyLoader
318
protected CollectionInitializer createCollectionInitializer(java.util.Map enabledFilters) throws MappingException {
319
return BatchingCollectionInitializer.createBatchingOneToManyInitializer( this, batchSize, getFactory(), enabledFilters );
322
public String fromJoinFragment(String alias,
324
boolean includeSubclasses) {
325
return ( ( Joinable ) getElementPersister() ).fromJoinFragment( alias, innerJoin, includeSubclasses );
328
public String whereJoinFragment(String alias,
330
boolean includeSubclasses) {
331
return ( ( Joinable ) getElementPersister() ).whereJoinFragment( alias, innerJoin, includeSubclasses );
334
public String getTableName() {
335
return ( ( Joinable ) getElementPersister() ).getTableName();
338
public String filterFragment(String alias) throws MappingException {
339
String result = super.filterFragment( alias );
340
if ( getElementPersister() instanceof Joinable ) {
341
result += ( ( Joinable ) getElementPersister() ).oneToManyFilterFragment( alias );
347
protected CollectionInitializer createSubselectInitializer(SubselectFetch subselect, SessionImplementor session) {
348
return new SubselectOneToManyLoader(
350
subselect.toSubselectString( getCollectionType().getLHSPropertyName() ),
351
subselect.getResult(),
352
subselect.getQueryParameters(),
353
subselect.getNamedParameterLocMap(),
354
session.getFactory(),
355
session.getEnabledFilters()
359
public Object getElementByIndex(Serializable key, Object index, SessionImplementor session, Object owner) {
360
return new CollectionElementLoader( this, getFactory(), session.getEnabledFilters() )
361
.loadElement( session, key, incrementIndexByBase(index) );