下面列出了怎么用org.hibernate.engine.ResultSetMappingDefinition的API类实例代码及写法,或者点击链接到github查看源代码。
public NamedQueryRepository(
Iterable<NamedQueryDefinition> namedQueryDefinitions,
Iterable<NamedSQLQueryDefinition> namedSqlQueryDefinitions,
Iterable<ResultSetMappingDefinition> namedSqlResultSetMappings,
Map<String, ProcedureCallMemento> namedProcedureCalls) {
final HashMap<String, NamedQueryDefinition> namedQueryDefinitionMap = new HashMap<String, NamedQueryDefinition>();
for ( NamedQueryDefinition namedQueryDefinition : namedQueryDefinitions ) {
namedQueryDefinitionMap.put( namedQueryDefinition.getName(), namedQueryDefinition );
}
this.namedQueryDefinitionMap = Collections.unmodifiableMap( namedQueryDefinitionMap );
final HashMap<String, NamedSQLQueryDefinition> namedSqlQueryDefinitionMap = new HashMap<String, NamedSQLQueryDefinition>();
for ( NamedSQLQueryDefinition namedSqlQueryDefinition : namedSqlQueryDefinitions ) {
namedSqlQueryDefinitionMap.put( namedSqlQueryDefinition.getName(), namedSqlQueryDefinition );
}
this.namedSqlQueryDefinitionMap = Collections.unmodifiableMap( namedSqlQueryDefinitionMap );
final HashMap<String, ResultSetMappingDefinition> namedSqlResultSetMappingMap = new HashMap<String, ResultSetMappingDefinition>();
for ( ResultSetMappingDefinition resultSetMappingDefinition : namedSqlResultSetMappings ) {
namedSqlResultSetMappingMap.put( resultSetMappingDefinition.getName(), resultSetMappingDefinition );
}
this.namedSqlResultSetMappingMap = Collections.unmodifiableMap( namedSqlResultSetMappingMap );
this.procedureCallMementoMap = Collections.unmodifiableMap( namedProcedureCalls );
}
/**
* Resolve the given result set mapping names
*
* @param context The context for the resolution. See {@link ResultSetMappingResolutionContext}
* @param resultSetMappingNames The names of the result-set-mappings to resolve
*/
public static void resolveResultSetMappings(ResultSetMappingResolutionContext context, String... resultSetMappingNames) {
for ( String resultSetMappingName : resultSetMappingNames ) {
log.tracef( "Starting attempt resolve named result-set-mapping : %s", resultSetMappingName );
final ResultSetMappingDefinition mapping = context.findResultSetMapping( resultSetMappingName );
if ( mapping == null ) {
throw new UnknownSqlResultSetMappingException( "Unknown SqlResultSetMapping [" + resultSetMappingName + "]" );
}
log.tracef( "Found result-set-mapping : %s", mapping.traceLoggableFormat() );
context.addQueryReturns( mapping.getQueryReturns() );
final SQLQueryReturnProcessor processor =
new SQLQueryReturnProcessor( mapping.getQueryReturns(), context.getSessionFactory() );
final SQLQueryReturnProcessor.ResultAliasContext processResult = processor.process();
context.addQuerySpaces( processResult.collectQuerySpaces() );
}
}
@Override
public void addResultSetMapping(ResultSetMappingDefinition resultSetMappingDefinition) {
if ( resultSetMappingDefinition == null ) {
throw new IllegalArgumentException( "Result-set mapping was null" );
}
final String name = resultSetMappingDefinition.getName();
if ( name == null ) {
throw new IllegalArgumentException( "Result-set mapping name is null: " + resultSetMappingDefinition );
}
if ( defaultSqlResultSetMappingNames.contains( name ) ) {
return;
}
applyResultSetMapping( resultSetMappingDefinition );
}
/**
* Constructs a SQLQueryImpl given a sql query defined in the mappings.
*
* @param queryDef The representation of the defined <sql-query/>.
* @param session The session to which this SQLQueryImpl belongs.
* @param parameterMetadata Metadata about parameters found in the query.
*/
SQLQueryImpl(NamedSQLQueryDefinition queryDef, SessionImplementor session, ParameterMetadata parameterMetadata) {
super( queryDef.getQueryString(), queryDef.getFlushMode(), session, parameterMetadata );
if ( queryDef.getResultSetRef() != null ) {
ResultSetMappingDefinition definition = session.getFactory()
.getResultSetMapping( queryDef.getResultSetRef() );
if (definition == null) {
throw new MappingException(
"Unable to find resultset-ref definition: " +
queryDef.getResultSetRef()
);
}
this.queryReturns = Arrays.asList( definition.getQueryReturns() );
}
else {
this.queryReturns = Arrays.asList( queryDef.getQueryReturns() );
}
this.querySpaces = queryDef.getQuerySpaces();
this.callable = queryDef.isCallable();
}
@Override
public <T> ResultSetMapping<T> getResultSetMapping(Class<T> resultType, String mappingName) {
ResultSetMappingDefinition mapping = getFactory().getNamedQueryRepository()
.getResultSetMappingDefinition( mappingName );
if (mapping==null) {
throw new IllegalArgumentException("result set mapping does not exist: " + mappingName);
}
if ( resultType!=null ) {
Class<?> mappedResultType = getResultType(mapping);
if ( !resultType.equals(mappedResultType) ) {
throw new IllegalArgumentException("incorrect result type for result set mapping: "
+ mappingName + " has type " + mappedResultType.getName() );
}
}
return new ResultSetMapping<T>() {
@Override
public String getName() {
return mappingName;
}
@Override
public Class<T> getResultType() {
return resultType;
}
};
}
protected void reset() {
implicitNamingStrategy = ImplicitNamingStrategyJpaCompliantImpl.INSTANCE;
physicalNamingStrategy = PhysicalNamingStrategyStandardImpl.INSTANCE;
namedQueries = new HashMap<String,NamedQueryDefinition>();
namedSqlQueries = new HashMap<String,NamedSQLQueryDefinition>();
sqlResultSetMappings = new HashMap<String, ResultSetMappingDefinition>();
namedEntityGraphMap = new HashMap<String, NamedEntityGraphDefinition>();
namedProcedureCallMap = new HashMap<String, NamedProcedureCallDefinition>( );
standardServiceRegistryBuilder = new StandardServiceRegistryBuilder( bootstrapServiceRegistry );
entityTuplizerFactory = new EntityTuplizerFactory();
interceptor = EmptyInterceptor.INSTANCE;
properties = new Properties( );
properties.putAll( standardServiceRegistryBuilder.getSettings());
}
public NamedQueryRepository(
Map<String,NamedQueryDefinition> namedQueryDefinitionMap,
Map<String,NamedSQLQueryDefinition> namedSqlQueryDefinitionMap,
Map<String,ResultSetMappingDefinition> namedSqlResultSetMappingMap,
Map<String, ProcedureCallMemento> namedProcedureCallMap) {
this.namedQueryDefinitionMap = Collections.unmodifiableMap( namedQueryDefinitionMap );
this.namedSqlQueryDefinitionMap = Collections.unmodifiableMap( namedSqlQueryDefinitionMap );
this.namedSqlResultSetMappingMap = Collections.unmodifiableMap( namedSqlResultSetMappingMap );
this.procedureCallMementoMap = Collections.unmodifiableMap( namedProcedureCallMap );
}
/**
* Constructs a NativeQueryImpl given a sql query defined in the mappings.
*
* @param queryDef The representation of the defined <sql-query/>.
* @param session The session to which this NativeQuery belongs.
* @param parameterMetadata Metadata about parameters found in the query.
*/
public NativeQueryImpl(
NamedSQLQueryDefinition queryDef,
SharedSessionContractImplementor session,
ParameterMetadata parameterMetadata) {
super( session, parameterMetadata );
this.sqlString = queryDef.getQueryString();
this.callable = queryDef.isCallable();
this.querySpaces = queryDef.getQuerySpaces() == null ? null : new ArrayList<>( queryDef.getQuerySpaces() );
if ( queryDef.getResultSetRef() != null ) {
ResultSetMappingDefinition definition = session.getFactory()
.getNamedQueryRepository()
.getResultSetMappingDefinition( queryDef.getResultSetRef() );
if ( definition == null ) {
throw new MappingException(
"Unable to find resultset-ref definition: " +
queryDef.getResultSetRef()
);
}
this.queryReturns = new ArrayList<>( Arrays.asList( definition.getQueryReturns() ) );
}
else if ( queryDef.getQueryReturns() != null && queryDef.getQueryReturns().length > 0 ) {
this.queryReturns = new ArrayList<>( Arrays.asList( queryDef.getQueryReturns() ) );
}
else {
this.queryReturns = new ArrayList<>();
}
this.queryParameterBindings = QueryParameterBindingsImpl.from(
parameterMetadata,
session.getFactory(),
session.isQueryParametersValidationEnabled()
);
}
@Override
public NativeQuery setResultSetMapping(String name) {
ResultSetMappingDefinition mapping = getProducer().getFactory().getNamedQueryRepository().getResultSetMappingDefinition( name );
if ( mapping == null ) {
throw new MappingException( "Unknown SqlResultSetMapping [" + name + "]" );
}
NativeSQLQueryReturn[] returns = mapping.getQueryReturns();
queryReturns.addAll( Arrays.asList( returns ) );
return this;
}
/**
* The result-set-mapping(s) return form
*
* @param session The session
* @param procedureName The name of the procedure to call
* @param resultSetMappings The names of the result set mappings making up the result
*/
public ProcedureCallImpl(final SharedSessionContractImplementor session, String procedureName, String... resultSetMappings) {
super( session, null );
this.procedureName = procedureName;
this.globalParameterPassNullsSetting = session.getFactory().getSessionFactoryOptions().isProcedureParameterNullPassingEnabled();
final List<NativeSQLQueryReturn> collectedQueryReturns = new ArrayList<>();
final Set<String> collectedQuerySpaces = new HashSet<>();
Util.resolveResultSetMappings(
new Util.ResultSetMappingResolutionContext() {
@Override
public SessionFactoryImplementor getSessionFactory() {
return session.getFactory();
}
@Override
public ResultSetMappingDefinition findResultSetMapping(String name) {
return session.getFactory().getNamedQueryRepository().getResultSetMappingDefinition( name );
}
@Override
public void addQueryReturns(NativeSQLQueryReturn... queryReturns) {
Collections.addAll( collectedQueryReturns, queryReturns );
}
@Override
public void addQuerySpaces(String... spaces) {
Collections.addAll( collectedQuerySpaces, spaces );
}
},
resultSetMappings
);
this.queryReturns = collectedQueryReturns.toArray( new NativeSQLQueryReturn[ collectedQueryReturns.size() ] );
this.synchronizedQuerySpaces = collectedQuerySpaces;
this.parameterMetadata = new ProcedureParameterMetadata( this );
this.paramBindings = new ProcedureParamBindings( parameterMetadata, this );
}
@Override
public void processResultSetMappings() {
for ( ResultSetMappingBindingDefinition resultSetMappingBinding : documentRoot.getResultset() ) {
final ResultSetMappingDefinition binding = ResultSetMappingBinder.bind( resultSetMappingBinding, this );
getMetadataCollector().addResultSetMapping( binding );
}
}
/**
* Build a ResultSetMappingDefinition given a containing element for the "return-XXX" elements.
* <p/>
* This form is used for ResultSet mappings defined outside the context of any specific entity.
* For {@code hbm.xml} this means at the root of the document. For annotations, this means at
* the package level.
*
* @param resultSetMappingSource The XML data as a JAXB binding
* @param context The mapping state
*
* @return The ResultSet mapping descriptor
*/
public static ResultSetMappingDefinition bind(
ResultSetMappingBindingDefinition resultSetMappingSource,
HbmLocalMetadataBuildingContext context) {
if ( resultSetMappingSource.getName() == null ) {
throw new MappingException(
"ResultSet mapping did not specify name",
context.getOrigin()
);
}
final ResultSetMappingDefinition binding = new ResultSetMappingDefinition( resultSetMappingSource.getName() );
bind( resultSetMappingSource, binding, context );
return binding;
}
/**
* Build a ResultSetMappingDefinition given a containing element for the "return-XXX" elements
*
* @param resultSetMappingSource The XML data as a JAXB binding
* @param context The mapping state
* @param prefix A prefix to apply to named ResultSet mapping; this is either {@code null} for
* ResultSet mappings defined outside of any entity, or the name of the containing entity
* if defined within the context of an entity
*
* @return The ResultSet mapping descriptor
*/
public static ResultSetMappingDefinition bind(
ResultSetMappingBindingDefinition resultSetMappingSource,
HbmLocalMetadataBuildingContext context,
String prefix) {
if ( StringHelper.isEmpty( prefix ) ) {
throw new AssertionFailure( "Passed prefix was null; perhaps you meant to call the alternate #bind form?" );
}
final String resultSetName = prefix + '.' + resultSetMappingSource.getName();
final ResultSetMappingDefinition binding = new ResultSetMappingDefinition( resultSetName );
bind( resultSetMappingSource, binding, context );
return binding;
}
private static void bind(
ResultSetMappingBindingDefinition resultSetMappingSource,
ResultSetMappingDefinition binding,
HbmLocalMetadataBuildingContext context) {
int cnt = 0;
for ( Object valueMappingSource : resultSetMappingSource.getValueMappingSources() ) {
if ( JaxbHbmNativeQueryReturnType.class.isInstance( valueMappingSource ) ) {
binding.addQueryReturn(
extractReturnDescription( (JaxbHbmNativeQueryReturnType) valueMappingSource, context, cnt++ )
);
}
else if ( JaxbHbmNativeQueryCollectionLoadReturnType.class.isInstance( valueMappingSource ) ) {
binding.addQueryReturn(
extractReturnDescription( (JaxbHbmNativeQueryCollectionLoadReturnType) valueMappingSource, context, cnt++ )
);
}
else if ( JaxbHbmNativeQueryJoinReturnType.class.isInstance( valueMappingSource ) ) {
binding.addQueryReturn(
extractReturnDescription( (JaxbHbmNativeQueryJoinReturnType) valueMappingSource, context, cnt++ )
);
}
else if ( JaxbHbmNativeQueryScalarReturnType.class.isInstance( valueMappingSource ) ) {
binding.addQueryReturn(
extractReturnDescription( (JaxbHbmNativeQueryScalarReturnType) valueMappingSource, context )
);
}
}
}
public void applyResultSetMapping(ResultSetMappingDefinition resultSetMappingDefinition) {
final ResultSetMappingDefinition old = sqlResultSetMappingMap.put(
resultSetMappingDefinition.getName(),
resultSetMappingDefinition
);
if ( old != null ) {
throw new DuplicateMappingException(
DuplicateMappingException.Type.RESULT_SET_MAPPING,
resultSetMappingDefinition.getName()
);
}
}
@Override
public void addDefaultResultSetMapping(ResultSetMappingDefinition definition) {
final String name = definition.getName();
if ( !defaultSqlResultSetMappingNames.contains( name ) && sqlResultSetMappingMap.containsKey( name ) ) {
sqlResultSetMappingMap.remove( name );
}
applyResultSetMapping( definition );
defaultSqlResultSetMappingNames.add( name );
}
public void addResultSetMapping(ResultSetMappingDefinition sqlResultSetMapping) {
final String name = sqlResultSetMapping.getName();
if ( resultSetMappings.containsKey(name) ) {
throw new DuplicateMappingException("resultSet", name);
}
resultSetMappings.put(name, sqlResultSetMapping);
}
/**
* Build a ResultSetMappingDefinition given a containing element for the "return-XXX" elements
*
* @param resultSetElem The element containing the return definitions.
* @param path No clue...
* @param mappings The current processing state.
* @return The description of the mappings...
*/
protected static ResultSetMappingDefinition buildResultSetMappingDefinition(Element resultSetElem, String path, Mappings mappings) {
String resultSetName = resultSetElem.attribute( "name" ).getValue();
if ( path != null ) {
resultSetName = path + '.' + resultSetName;
}
ResultSetMappingDefinition definition = new ResultSetMappingDefinition( resultSetName );
int cnt = 0;
Iterator returns = resultSetElem.elementIterator();
while ( returns.hasNext() ) {
cnt++;
Element returnElem = (Element) returns.next();
String name = returnElem.getName();
if ( "return-scalar".equals( name ) ) {
String column = returnElem.attributeValue( "column" );
String typeFromXML = HbmBinder.getTypeFromXML( returnElem );
Type type = null;
if(typeFromXML!=null) {
type = TypeFactory.heuristicType( typeFromXML );
if ( type == null ) {
throw new MappingException( "could not determine type " + type );
}
}
definition.addQueryReturn( new NativeSQLQueryScalarReturn( column, type ) );
}
else if ( "return".equals( name ) ) {
definition.addQueryReturn( bindReturn( returnElem, mappings, cnt ) );
}
else if ( "return-join".equals( name ) ) {
definition.addQueryReturn( bindReturnJoin( returnElem, mappings ) );
}
else if ( "load-collection".equals( name ) ) {
definition.addQueryReturn( bindLoadCollection( returnElem, mappings ) );
}
}
return definition;
}
public SQLQuery setResultSetMapping(String name) {
ResultSetMappingDefinition mapping = session.getFactory().getResultSetMapping( name );
if ( mapping == null ) {
throw new MappingException( "Unknown SqlResultSetMapping [" + name + "]" );
}
NativeSQLQueryReturn[] returns = mapping.getQueryReturns();
int length = returns.length;
for ( int index = 0 ; index < length ; index++ ) {
queryReturns.add( returns[index] );
}
return this;
}
@Override
public ResultSetMappingDefinition getResultSetMapping(final String name) {
return metadata.getResultSetMapping(name);
}
@Override
public Map<String, ResultSetMappingDefinition> getResultSetMappingDefinitions() {
return metadata.getResultSetMappingDefinitions();
}
public ResultSetMappingDefinition getResultSetMappingDefinition(String mappingName) {
return namedSqlResultSetMappingMap.get( mappingName );
}
/**
* @deprecated (since 5.2) Use {@link NamedQueryRepository#getResultSetMappingDefinition} instead.
*/
@Deprecated
default ResultSetMappingDefinition getResultSetMapping(String name) {
return getNamedQueryRepository().getResultSetMappingDefinition( name );
}
@Override
public ResultSetMappingDefinition getResultSetMapping(String name) {
return delegate.getResultSetMapping( name );
}
@SuppressWarnings({"unchecked", "WeakerAccess"})
protected void resultClassChecking(Class resultType, NamedSQLQueryDefinition namedQueryDefinition) {
final NativeSQLQueryReturn[] queryReturns;
if ( namedQueryDefinition.getQueryReturns() != null ) {
queryReturns = namedQueryDefinition.getQueryReturns();
}
else if ( namedQueryDefinition.getResultSetRef() != null ) {
final ResultSetMappingDefinition rsMapping = getFactory().getNamedQueryRepository().getResultSetMappingDefinition( namedQueryDefinition.getResultSetRef() );
queryReturns = rsMapping.getQueryReturns();
}
else {
throw new AssertionFailure( "Unsupported named query model. Please report the bug in Hibernate EntityManager");
}
if ( queryReturns.length > 1 ) {
throw new IllegalArgumentException( "Cannot create TypedQuery for query with more than one return" );
}
final NativeSQLQueryReturn nativeSQLQueryReturn = queryReturns[0];
if ( nativeSQLQueryReturn instanceof NativeSQLQueryRootReturn ) {
final Class<?> actualReturnedClass;
final String entityClassName = ( (NativeSQLQueryRootReturn) nativeSQLQueryReturn ).getReturnEntityName();
try {
actualReturnedClass = getFactory().getServiceRegistry().getService( ClassLoaderService.class ).classForName( entityClassName );
}
catch ( ClassLoadingException e ) {
throw new AssertionFailure(
"Unable to load class [" + entityClassName + "] declared on named native query [" +
namedQueryDefinition.getName() + "]"
);
}
if ( !resultType.isAssignableFrom( actualReturnedClass ) ) {
throw buildIncompatibleException( resultType, actualReturnedClass );
}
}
else if ( nativeSQLQueryReturn instanceof NativeSQLQueryConstructorReturn ) {
final NativeSQLQueryConstructorReturn ctorRtn = (NativeSQLQueryConstructorReturn) nativeSQLQueryReturn;
if ( !resultType.isAssignableFrom( ctorRtn.getTargetClass() ) ) {
throw buildIncompatibleException( resultType, ctorRtn.getTargetClass() );
}
}
else {
log.debugf( "Skiping unhandled NativeSQLQueryReturn type : " + nativeSQLQueryReturn );
}
}
@Override
public ResultSetMappingDefinition getResultSetMapping(String name) {
return delegate.getResultSetMapping( name );
}
@Override
public Map<String, ResultSetMappingDefinition> getResultSetMappingDefinitions() {
return delegate.getResultSetMappingDefinitions();
}
public static void processNamedNativeQuery(
final HbmLocalMetadataBuildingContext context,
JaxbHbmNamedNativeQueryType namedQueryBinding,
String prefix) {
final String queryName = prefix + namedQueryBinding.getName();
final NamedSQLQueryDefinitionBuilder builder = new NamedSQLQueryDefinitionBuilder()
.setName( queryName )
.setComment( namedQueryBinding.getComment() )
.setCacheable( namedQueryBinding.isCacheable() )
.setCacheMode( namedQueryBinding.getCacheMode() )
.setCacheRegion( namedQueryBinding.getCacheRegion() )
.setTimeout( namedQueryBinding.getTimeout() )
.setReadOnly( namedQueryBinding.isReadOnly() )
.setFlushMode( namedQueryBinding.getFlushMode() )
.setFetchSize( namedQueryBinding.getFetchSize() )
.setCallable( namedQueryBinding.isCallable() )
.setResultSetRef( namedQueryBinding.getResultsetRef() );
final ImplicitResultSetMappingDefinition.Builder implicitResultSetMappingBuilder
= new ImplicitResultSetMappingDefinition.Builder( queryName );
boolean foundQuery = false;
for ( Object content : namedQueryBinding.getContent() ) {
final boolean wasQuery = processNamedQueryContentItem(
content,
builder,
implicitResultSetMappingBuilder,
namedQueryBinding,
context
);
if ( wasQuery ) {
foundQuery = true;
}
}
if ( !foundQuery ) {
throw new org.hibernate.boot.MappingException(
String.format(
"Named native query [%s] did not specify query string",
namedQueryBinding.getName()
),
context.getOrigin()
);
}
if ( implicitResultSetMappingBuilder.hasAnyReturns() ) {
if ( StringHelper.isNotEmpty( namedQueryBinding.getResultsetRef() ) ) {
throw new org.hibernate.boot.MappingException(
String.format(
"Named native query [%s] specified both a resultset-ref and an inline mapping of results",
namedQueryBinding.getName()
),
context.getOrigin()
);
}
// Building a ResultSet mapping needs access to entity bindings for any entity
// returns it defines. But binding for those entities may have not been
// completed yet. For "normal" ResultSet mappings, this is already handled by
// the fact that MetadataSourceProcessor#processResultSetMappings() is called
// after all entity hierarchies have been processed. However, here we are in
// the middle of processing named-queries (either top-level or entity-level)
// and have no guarantee that any entity bindings we may need here are bound.
// So we add the second-pass to bind the implicit resultSet mapping.
//
// It is possible to know here whether the second-pass is needed or whether we
// can immediately bind the ResultSet mapping.
// todo : consider implementing this (^^) checking
final ImplicitResultSetMappingDefinition implicitResultSetMappingDefinition = implicitResultSetMappingBuilder.build();
builder.setResultSetRef( implicitResultSetMappingDefinition.getName() );
context.getMetadataCollector().addSecondPass(
new SecondPass() {
@Override
public void doSecondPass(Map persistentClasses) throws MappingException {
final ResultSetMappingDefinition resultSetMappingDefinition =
ResultSetMappingBinder.bind( implicitResultSetMappingDefinition, context );
context.getMetadataCollector().addResultSetMapping( resultSetMappingDefinition );
NativeSQLQueryReturn[] newQueryReturns = resultSetMappingDefinition.getQueryReturns();
final NamedSQLQueryDefinition queryDefinition =
context.getMetadataCollector().getNamedNativeQueryDefinition( queryName );
if ( queryDefinition != null ) {
queryDefinition.addQueryReturns( newQueryReturns );
}
}
}
);
}
context.getMetadataCollector().addNamedNativeQuery( builder.createNamedQueryDefinition() );
}
@Override
public Map<String, ResultSetMappingDefinition> getResultSetMappingDefinitions() {
return sqlResultSetMappingMap;
}
@Override
public ResultSetMappingDefinition getResultSetMapping(String name) {
return sqlResultSetMappingMap.get( name );
}