下面列出了怎么用org.hibernate.type.Type的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public boolean onFlushDirty(Object aEntity, Serializable aID, Object[] aCurrentState, Object[] aPreviousState,
String[] aPropertyNames, Type[] aTypes) {
String theCurrentUser = getCurrentUserId();
if (theCurrentUser != null) {
for (int i = 0; i < aPropertyNames.length; i++) {
String thePropertyName = aPropertyNames[i];
if ("lastModificationDate".equals(thePropertyName)) {
aCurrentState[i] = new Timestamp(System.currentTimeMillis());
}
if ("lastModificationUser".equals(thePropertyName)) {
aCurrentState[i] = theCurrentUser;
}
}
return true;
}
return false;
}
public CachedNaturalId(EntityPersister persister, Object[] values) {
this.persister = persister;
this.values = values;
final int prime = 31;
int hashCodeCalculation = 1;
hashCodeCalculation = prime * hashCodeCalculation + persister.hashCode();
final int[] naturalIdPropertyIndexes = persister.getNaturalIdentifierProperties();
naturalIdTypes = new Type[ naturalIdPropertyIndexes.length ];
int i = 0;
for ( int naturalIdPropertyIndex : naturalIdPropertyIndexes ) {
final Type type = persister.getPropertyType( persister.getPropertyNames()[ naturalIdPropertyIndex ] );
naturalIdTypes[i] = type;
final int elementHashCode = values[i] == null ? 0 :type.getHashCode( values[i], persister.getFactory() );
hashCodeCalculation = prime * hashCodeCalculation + elementHashCode;
i++;
}
this.hashCode = hashCodeCalculation;
}
/**
* Warning:
* When there are duplicated property names in the subclasses
* of the class, this method may return the wrong table
* number for the duplicated subclass property (note that
* SingleTableEntityPersister defines an overloaded form
* which takes the entity name.
*/
public int getSubclassPropertyTableNumber(String propertyPath) {
String rootPropertyName = StringHelper.root(propertyPath);
Type type = propertyMapping.toType(rootPropertyName);
if ( type.isAssociationType() ) {
AssociationType assocType = ( AssociationType ) type;
if ( assocType.useLHSPrimaryKey() ) {
// performance op to avoid the array search
return 0;
}
else if ( type.isCollectionType() ) {
// properly handle property-ref-based associations
rootPropertyName = assocType.getLHSPropertyName();
}
}
//Enable for HHH-440, which we don't like:
/*if ( type.isComponentType() && !propertyName.equals(rootPropertyName) ) {
String unrooted = StringHelper.unroot(propertyName);
int idx = ArrayHelper.indexOf( getSubclassColumnClosure(), unrooted );
if ( idx != -1 ) {
return getSubclassColumnTableNumberClosure()[idx];
}
}*/
int index = ArrayHelper.indexOf( getSubclassPropertyNameClosure(), rootPropertyName); //TODO: optimize this better!
return index==-1 ? 0 : getSubclassPropertyTableNumber(index);
}
public IteratorImpl(
ResultSet rs,
PreparedStatement ps,
EventSource sess,
Type[] types,
String[][] columnNames,
HolderInstantiator holderInstantiator)
throws HibernateException, SQLException {
this.rs=rs;
this.ps=ps;
this.session = sess;
this.types = types;
this.names = columnNames;
this.holderInstantiator = holderInstantiator;
single = types.length==1;
postNext();
}
public void validateTypes(SelectClause selectClause) throws QueryException {
Type[] selectTypes = selectClause.getQueryReturnTypes();
if ( selectTypes.length + selectClause.getTotalParameterCount() != types.length ) {
throw new QueryException( "number of select types did not match those for insert" );
}
int parameterCount = 0;
for ( int i = 0; i < types.length; i++ ) {
if ( selectClause.getParameterPositions().contains( i ) ) {
parameterCount++;
}
else if ( !areCompatible( types[i], selectTypes[i - parameterCount] ) ) {
throw new QueryException(
"insertion type [" + types[i] + "] and selection type [" +
selectTypes[i - parameterCount] + "] at position " + i + " are not compatible"
);
}
}
// otherwise, everything ok.
}
/**
* Return the query results, using the query cache, called
* by subclasses that implement cacheable queries
*/
protected List list(
final SharedSessionContractImplementor session,
final QueryParameters queryParameters,
final Set<Serializable> querySpaces,
final Type[] resultTypes) throws HibernateException {
final boolean cacheable = factory.getSessionFactoryOptions().isQueryCacheEnabled() &&
queryParameters.isCacheable();
if ( cacheable ) {
return listUsingQueryCache( session, queryParameters, querySpaces, resultTypes );
}
else {
return listIgnoreQueryCache( session, queryParameters );
}
}
public void validateTypes(SelectClause selectClause) throws QueryException {
Type[] selectTypes = selectClause.getQueryReturnTypes();
if ( selectTypes.length != types.length ) {
throw new QueryException( "number of select types did not match those for insert" );
}
for ( int i = 0; i < types.length; i++ ) {
if ( !areCompatible( types[i], selectTypes[i] ) ) {
throw new QueryException(
"insertion type [" + types[i] + "] and selection type [" +
selectTypes[i] + "] at position " + i + " are not compatible"
);
}
}
// otherwise, everything ok.
}
@Override
public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
List<TypedValue> list = new ArrayList<>();
Type type = criteriaQuery.getTypeUsingProjection(criteria, propertyName);
if (type.isComponentType()) {
CompositeType actype = (CompositeType) type;
Type[] types = actype.getSubtypes();
for (int j = 0; j < values.length; j++) {
for (int i = 0; i < types.length; i++) {
Object subval = values[j] == null ? null : actype.getPropertyValues(values[j], EntityMode.POJO)[i];
list.add(new TypedValue(types[i], subval, EntityMode.POJO));
}
}
} else {
for (int j = 0; j < values.length; j++) {
list.add(new TypedValue(type, values[j], EntityMode.POJO));
}
}
return list.toArray(new TypedValue[list.size()]);
}
/**
* Hibernate Find method. Use this in a transactional context by using your current transaction object.
*
* @param trx
* The current db transaction
* @param query
* The HQL query
* @param values
* The object array containing all search values
* @param types
* The object array containing all Hibernate datatype of the search values
*/
List find(DBTransaction trx, String query, Object[] values, Type[] types) {
List li = null;
try {
long start = 0;
if (log.isDebugEnabled())
start = System.currentTimeMillis();
// old: li = getSession().find(query, values, types);
Query qu = this.getSession().createQuery(query);
qu.setParameters(values, types);
li = qu.list();
if (log.isDebugEnabled()) {
long time = (System.currentTimeMillis() - start);
logQuery("find (time " + time + ", res " + (li == null ? "null" : "" + li.size()) + ")(trans " + trx.hashCode() + ")", values, types, query);
}
} catch (HibernateException e) {
trx.setErrorAndRollback(e);
String msg = "Find failed in transaction. Query: " + query + " " + e;
setError(e);
throw new DBRuntimeException(msg, e);
}
return li;
}
public void end(QueryTranslatorImpl q) throws QueryException {
ignoreInitialJoin = false;
Type propertyType = getPropertyType();
if ( propertyType != null && propertyType.isCollectionType() ) {
collectionRole = ( ( CollectionType ) propertyType ).getRole();
collectionName = q.createNameForCollection( collectionRole );
prepareForIndex( q );
}
else {
columns = currentColumns();
setType();
}
//important!!
continuation = false;
}
int delete(String query, Object value, Type type) {
int deleted = 0;
try {
// old: deleted = getSession().delete(query, value, type);
Session si = getSession();
Query qu = si.createQuery(query);
qu.setParameter(0, value, type);
List foundToDel = qu.list();
int deletionCount = foundToDel.size();
for (int i = 0; i < deletionCount; i++) {
si.delete(foundToDel.get(i));
}
// //
getSession().flush();
if (log.isDebugEnabled()) {
logQuery("delete", new Object[] { value }, new Type[] { type }, query);
}
} catch (HibernateException e) {
setError(e);
throw new DBRuntimeException("Delete error. Query" + query + " Object: " + value, e);
}
return deleted;
}
public QueryParameters(
final Type[] positionalParameterTypes,
final Object[] postionalParameterValues
) {
this(
positionalParameterTypes,
postionalParameterValues,
null,
null,
false,
null,
null,
false,
null
);
}
public Object readFrom(ResultSet rs, CollectionPersister persister, CollectionAliases descriptor, Object owner)
throws HibernateException, SQLException {
Object object = persister.readElement( rs, owner, descriptor.getSuffixedElementAliases(), getSession() );
final Type elementType = persister.getElementType();
final SessionFactoryImplementor factory = persister.getFactory();
String indexNode = getIndexAttributeName(persister);
Element elem = element.addElement( persister.getElementNodeName() );
elementType.setToXMLNode( elem, object, factory );
final Type indexType = persister.getIndexType();
final Object indexValue = persister.readIndex( rs, descriptor.getSuffixedIndexAliases(), getSession() );
final String index = ( (NullableType) indexType ).toXMLString( indexValue, factory );
setIndex(elem, indexNode, index);
return object;
}
@Override
public void register(Dialect dialect) {
logger.debug("IN");
try {
if (function.getCode() != null || !function.getCode().equals("")) {
dialect.registerFunction(function.getName(),
new SQLFunctionTemplate((Type) StandardBasicTypes.class.getField(function.getType()).get(null), function.getCode()));
}
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
logger.error("Error while registering function", e);
throw new SpagoBIEngineRuntimeException("Error while registering function", e);
} finally {
logger.debug("OUT");
}
}
/**
* Set the named parameter's value list for this filter. Used
* in conjunction with IN-style filter criteria.
*
* @param name The parameter's name.
* @param values The values to be expanded into an SQL IN list.
* @return This FilterImpl instance (for method chaining).
*/
public Filter setParameterList(String name, Collection values) throws HibernateException {
// Make sure this is a defined parameter and check the incoming value type
if ( values == null ) {
throw new IllegalArgumentException( "Collection must be not null!" );
}
Type type = definition.getParameterType( name );
if ( type == null ) {
throw new HibernateException( "Undefined filter parameter [" + name + "]" );
}
if ( values.size() > 0 ) {
Class elementClass = values.iterator().next().getClass();
if ( !type.getReturnedClass().isAssignableFrom( elementClass ) ) {
throw new HibernateException( "Incorrect type for parameter [" + name + "]" );
}
}
parameters.put( name, values );
return this;
}
public int[] findDirty(Object entity,
Serializable id,
Object[] currentState,
Object[] previousState,
String[] propertyNames,
Type[] types) {
return null;
}
@Override
public QueryImplementor<X> setParameter(String name, Object val, Type type) {
entityManager.checkOpen( false );
ExplicitParameterInfo<?> parameterInfo = locateParameterByName( name );
parameterInfo.validateBindValue( val );
jpqlQuery.setParameter( name, val, type );
return this;
}
/**
* @see org.hibernate.id.Configurable#configure(org.hibernate.type.Type, java.util.Properties, org.hibernate.dialect.Dialect)
*/
public void configure(Type type, Properties params, Dialect d)
throws MappingException {
propertyName = params.getProperty("property");
entityName = params.getProperty(ENTITY_NAME);
if (propertyName==null) throw new MappingException(
"param named \"property\" is required for foreign id generation strategy"
);
}
protected void addPropertyTypedValue(Object value, Type type, List<TypedValue> list) {
if ( value != null ) {
if ( value instanceof String ) {
String string = (String) value;
if ( isIgnoreCaseEnabled ) {
string = string.toLowerCase(Locale.ROOT);
}
if ( isLikeEnabled ) {
string = matchMode.toMatchString( string );
}
value = string;
}
list.add( new TypedValue( type, value ) );
}
}
public final CompletionStage<Void> doBatchedCollectionLoad(
final SessionImplementor session,
final Serializable[] ids,
final Type type) throws HibernateException {
if ( LOG.isDebugEnabled() ) {
LOG.debugf(
"Batch loading collection: %s",
collectionInfoString( getCollectionPersisters()[0], ids, getFactory() )
);
}
final Type[] idTypes = new Type[ids.length];
Arrays.fill( idTypes, type );
final QueryParameters queryParameters = new QueryParameters( idTypes, ids, ids );
final String sql = StringHelper.expandBatchIdPlaceholder(
sqlTemplate,
ids,
alias,
collectionPersister().getKeyColumnNames(),
session.getJdbcServices().getJdbcEnvironment().getDialect()
);
return doReactiveQueryAndInitializeNonLazyCollections( sql, session, queryParameters )
.handle( (list, err) -> {
CompletionStages.logSqlException( err,
() -> "could not initialize a collection batch: " +
collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ),
getSQLString()
);
LOG.debug("Done batch load");
return CompletionStages.returnNullorRethrow( err );
} );
}
@Override
@SuppressWarnings("unchecked")
public String render(Type argumentType, List args, SessionFactoryImplementor factory) throws QueryException {
final int lastIndex = args.size()-1;
final Object last = args.remove( lastIndex );
if ( lastIndex==0 ) {
return last.toString();
}
final Object secondLast = args.get( lastIndex-1 );
final String nvl = "nvl(" + secondLast + ", " + last + ")";
args.set( lastIndex-1, nvl );
return render( argumentType, args, factory );
}
public String toString(Type[] types, Object[] values) throws HibernateException {
List list = new ArrayList( types.length * 5 );
for ( int i=0; i<types.length; i++ ) {
if ( types[i]!=null ) list.add( types[i].toLoggableString( values[i], factory ) );
}
return list.toString();
}
public boolean needsInserting(Object entry, int i, Type elemType) throws HibernateException {
final java.util.Map sn = (java.util.Map) getSnapshot();
Object oldValue = sn.get(entry);
// note that it might be better to iterate the snapshot but this is safe,
// assuming the user implements equals() properly, as required by the Set
// contract!
return oldValue==null || elemType.isDirty( oldValue, entry, getSession() );
}
public CascadeStyle getCascadeStyle() throws MappingException {
Type type = value.getType();
if ( type.isComponentType() ) {
return getCompositeCascadeStyle( (CompositeType) type, cascade );
}
else if ( type.isCollectionType() ) {
return getCollectionCascadeStyle( ( (Collection) value ).getElement().getType(), cascade );
}
else {
return getCascadeStyle( cascade );
}
}
private static IdentifierGenerator augmentWithReactiveGenerator(IdentifierGenerator generator, Type type, Properties params, ServiceRegistryImplementor serviceRegistry) {
ReactiveIdentifierGenerator<?> reactiveGenerator;
if (generator instanceof SequenceStyleGenerator) {
DatabaseStructure structure = ((SequenceStyleGenerator) generator).getDatabaseStructure();
if (structure instanceof TableStructure) {
reactiveGenerator = new TableReactiveIdentifierGenerator(true);
}
else if (structure instanceof SequenceStructure) {
reactiveGenerator = new SequenceReactiveIdentifierGenerator();
}
else {
throw new IllegalStateException("unknown structure type");
}
}
else if (generator instanceof TableGenerator) {
reactiveGenerator = new TableReactiveIdentifierGenerator(false);
}
else if (generator instanceof SequenceGenerator) {
reactiveGenerator = new SequenceReactiveIdentifierGenerator();
}
else if (generator instanceof SelectGenerator) {
//TODO: this is easy to fix!
throw new HibernateException("SelectGenerator is not yet supported in Hibernate Reactive");
}
else {
//nothing to do
return generator;
}
((Configurable) reactiveGenerator).configure( type, params, serviceRegistry );
return new ReactiveGeneratorWrapper<>( reactiveGenerator, generator );
}
/**
* Figure out the type of the binary expression by looking at
* the types of the operands. Sometimes we don't know both types,
* if, for example, one is a parameter.
*/
public Type getDataType() {
if ( super.getDataType() == null ) {
super.setDataType( resolveDataType() );
}
return super.getDataType();
}
@Override
public String render(Type firstArgumentType, List args, SessionFactoryImplementor factory) throws QueryException {
if ( args.size() != 2 && args.size() != 3 ) {
throw new QueryException( "convert() requires two or three arguments" );
}
final String type = (String) args.get( 1 );
if ( args.size() == 2 ) {
return "{fn convert(" + args.get( 0 ) + " , " + type + ")}";
}
else {
return "convert(" + args.get( 0 ) + " , " + type + "," + args.get( 2 ) + ")";
}
}
private Object throwInvalidColumnTypeException(
int i,
Type type,
Type returnType) throws HibernateException {
throw new HibernateException(
"incompatible column types: " +
type.getName() +
", " +
returnType.getName()
);
}
@Override
public String render(Type firstArgumentType, List arguments, SessionFactoryImplementor sessionFactory) {
final StringBuilder buf = new StringBuilder();
buf.append( getRenderedName( arguments) ).append( '(' );
for ( int i = 0; i < arguments.size(); i++ ) {
buf.append( arguments.get( i ) );
if ( i < arguments.size() - 1 ) {
buf.append( ", " );
}
}
return buf.append( ')' ).toString();
}
public Type aggregateType(List funcTokenList, Type type, QueryTranslatorImpl q) throws QueryException {
Type retType = type;
Type argType;
for ( int i = funcTokenList.size() - 1; i >= 0; i-- ) {
argType = retType;
String funcToken = ( String ) funcTokenList.get( i );
retType = getFunction( funcToken, q ).getReturnType( argType, q.getFactory() );
}
return retType;
}