Trying to solve Postgresql Array Functions with QueryDSL more cleanly, I've got this far.
// obj.foo is an ArrayPath<String[], String>
bindings.bind(obj.foo).first((path, value) ->
Expressions.booleanTemplate("arraycontains({0}, {1}) = true", path, value));
this ends up as correct-looking SQL
where arraycontains(obj0_1_.foo, ?)=true
but it seems the String[] variable is not passed correctly
org.postgresql.util.PSQLException: ERROR: function arraycontains(character varying[], bytea) does not exist
How can I either (if possible)
get the String[] value to bind as a varchar[]?
express the necessary cast in the booleanTemplate?
Instead of passing the String[] directly, wrap it in a TypedParameterValue.
The hibernate-types library does not yet support varchar[], but you can use it to build something that does:
public class VarcharArrayType extends AbstractHibernateType<String[]> {
public static VarcharArrayType INSTANCE = new VarcharArrayType();
public VarcharArrayType() {
super(ArraySqlTypeDescriptor.INSTANCE, new TypeDescriptor());
}
public String getName() {
return "varchar-array";
}
public static class TypeDescriptor extends StringArrayTypeDescriptor {
#Override
protected String getSqlArrayType() {
return "varchar";
}
}
}
Related
I have a model object that has a getter/setter that accepts a String.
public String getStringValue(String key)
I need to know if it is possible to use that getter with a PropertyModel and if so how do I do it? An example might look something like this:
new PropertyModel<String>(myObj, "StringValue[key]");
There isn't built in way to do it. But you can define your own Wicket Model to do it via reflection.
For example:
public class FunctionReflectionReadOnlyModel<T, R> extends AbstractReadOnlyModel<T> {
private Object object;
private String functionName;
private R key;
private Class<R> keyClass;
public FunctionReflectionReadOnlyModel(Object object, String expression, Class<R> keyClass) {
this.object = object;
this.functionName = getFunctionName(expression);
this.key = getKey(expression);
this.keyClass = keyClass;
}
#Override
public T getObject() {
try {
Method method = object.getClass().getMethod(functionName, keyClass);
return (T)method.invoke(object, key);
} catch (Exception ex) {
//process exception
return null;
}
}
}
You just need implement getFunctionName(String expression) and getKey(String expression) on your needs.
But I think that is better use another variant. It's not particularly what you ask, but it is typified. Also required Java 8.
public class FunctionWithKeyReadOnlyModel<T, R> extends AbstractReadOnlyModel<T> {
private Function<R, T> function;
private R key;
public FunctionWithKeyReadOnlyModel(Function<R, T> function, R key) {
this.function = function;
this.key = key;
}
#Override
public T getObject() {
return function.apply(key);
}
}
And then you can use it like this:
new FunctionWithKeyReadOnlyModel(obj::getStringValue, "key");
I've read about usage only PropertyModel too late. In this case you can inherit your class from PropertyModel and change getModel/setModel like in example FunctionReflectionReadOnlyModel. So you don't need change other classes API. But if you want all features of PropertyModel (nested objects) you need implement it.
As answered by #merz this is not supported by Wicket's PropertyModel, actually by PropertyResolver.
PropertyResolver supports such access if you use a java.util.Map:
public Map<String, String> getProperty() {return theMap;}
Check org.apache.wicket.core.util.lang.PropertyResolver's javadoc.
This is the call in the ProductServices.xml
<update id="resetPassword" parameterType="batchReport">
{ call user_account_mng.enc_reset_password(
#{user_Id,jdbcType=VARCHAR,mode=IN},
#{encrypted_password,jdbcType=VARCHAR,mode=IN},
#{usr_id, dbcType=VARCHAR,mode=IN},
#{salt,jdbcType=VARCHAR,mode=IN},
#{ret_code,jdbcType=CHAR,mode=OUT},
#{pgp_encrypted_password,jdbcType=BLOB,mode=IN}
)}
Now BatchReport is a POJO:
(i have declared an alias for it as batchReport)
public class BatchReport
{
private String user_Id;
private String encrypted_password;
private String usr_id;
private String salt;
private String ret_code;
private byte[] pgp_encrypted_password;
public String getUser_Id() {
return user_Id;
}
public void setUser_Id(String user_Id) {
this.user_Id = user_Id;
}
public String getEncrypted_password() {
return encrypted_password;
}
public void setEncrypted_password(String encrypted_password) {
this.encrypted_password = encrypted_password;
}
public String getUsr_id() {
return usr_id;
}
public void setUsr_id(String usr_id) {
this.usr_id = usr_id;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public String getRet_code() {
return ret_code;
}
public void setRet_code(String ret_code) {
this.ret_code = ret_code;
}
public byte[] getPgp_encrypted_password() {
return pgp_encrypted_password;
}
public void setPgp_encrypted_password(byte[] pgp_encrypted_password) {
this.pgp_encrypted_password = pgp_encrypted_password;
}
}
My main class is like this :
<BatchReport batchReport = new BatchReport();
byte[] byteArray =new byte[]{1,2,3};
batchReport.setUser_Id("CHI");
batchReport.setEncrypted_password("97D6B45");
batchReport.setSalt("71L");
batchReport.setPgp_encrypted_password(byteArray);
String returnCode = productServiceObj.resetPassword(batchReport);
i am getting following error:
Error setting null parameter. Most JDBC drivers require that the JdbcType must be specified for all nullable parameters. Cause: java.sql.SQLException: Invalid column type
The error may involve com.example.services.ProductServices.resetPassword-Inline
ProductServices is a class in which the method resetPassword is declared.
Please help me with this BLOB issue.
What should be the jdbcType in the called procedure.
what value should be passed in this pgp_encrypted_password.
Okay I found the solution to the problem now the jdbcType in the query in .xml file remains the same i.e BLOB.
Next the type which gets set for passing in the values is byte[].
So everything remains same as i have covered up .
Error actually existed as the in .xml file returns an integer indicating the number of rows changed in query and I have given the function return type as String so here goes the solution for the problem it should be of type Object.
I want to convert Optional<BigDecimal> in morphia. I created BigDecimalConverter, and it works fine. Now I want to create OptionalConverter.
Optional can hold any object type. In my OptionalConverter.encode method I can extract underlying object, and I'd like to pass it to default mongo conversion. So that if there is string, I'll just get string, if there is one of my entities, I'll get encoded entity. How can I do it?
There are two questions:
1. How to call other converters?
2. How to create a converter for a generic class whose type parameters are not statically known?
The first one is possible by creating the MappingMongoConveter and the custom converter together:
#Configuration
public class CustomConfig extends AbstractMongoConfiguration {
#Override
protected String getDatabaseName() {
// ...
}
#Override
#Bean
public Mongo mongo() throws Exception {
// ...
}
#Override
#Bean
public MappingMongoConverter mappingMongoConverter() throws Exception {
MappingMongoConverter mmc = new MappingMongoConverter(
mongoDbFactory(), mongoMappingContext());
mmc.setCustomConversions(new CustomConversions(CustomConverters
.create(mmc)));
return mmc;
}
}
public class FooConverter implements Converter<Foo, DBObject> {
private MappingMongoConverter mmc;
public FooConverter(MappingMongoConverter mmc) {
this.mmc = mmc;
}
public DBObject convert(Foo foo) {
// ...
}
}
public class CustomConverters {
public static List<?> create(MappingMongoConverter mmc) {
List<?> list = new ArrayList<>();
list.add(new FooConverter(mmc));
return list;
}
}
The second one is much more difficult due to type erasure. I've tried to create a converter for Scala's Map but haven't found a way. Unable to get the exact type information for the source Map when writing, or for the target Map when reading.
For very simple cases, e.g. if you don't need to handle all possible parameter types, and there is no ambiguity while reading, it may be possible though.
How to implement a GWT ValueListBox inside an Editor with a specific list of objects, my code:
...
#UiField(provided = true)
#Path("address.countryCode")
ValueListBox<Country> countries = new ValueListBox<Country>(
new Renderer<Country>() {
#Override
public String render(Country object) {
return object.getCountryName();
}
#Override
public void render(Country object, Appendable appendable)
throws IOException {
render(object);
}
},
new ProvidesKey<Country>() {
#Override
public Object getKey(Country item) {
return item.getCountryCode();
}
});
...
The Country class
public class Country {
private String countryName;
private String countryCode;
}
But, during the GWT compilation I'm getting this error:
Type mismatch: cannot convert from String to Country
The problem is that you are trying to edit the address.countryCode (looking at the path annotation) with editor for Country.
To make this work, you should change the path to address.country and do the assignment of the address.countryCode after editorDriver.flash(). Something like:
Address address = editorDriver.flush();
address.setCountryCode(address.getCountry().getCountryCode());
To support this, the Address class should have the Country object as property.
You may have assumed that the ValueListBox will work like classical select where the key is assigned to the property. Here the whole object is assigned. So in your case Country object can not be assigned to address.countryCode and vice-versa.
Btw. you can correct the renderer (like the code below) and take care of null objects as arguments in the Renderer and Key Provider.
new Renderer<Country>() {
...
#Override
public void render(Country object, Appendable appendable)
throws IOException {
appendable.append(render(object));
}
...
}
I am currently working on a report which needs a group_concat for one of the fields.
CriteriaQuery<GameDetailsDto> criteriaQuery = criteriaBuilder
.createQuery(GameDetailsDto.class);
Root<BetDetails> betDetails = criteriaQuery.from(BetDetails.class);
Expression<String> betSelection = betDetails.get("winningOutcome");
criteriaQuery.multiselect(
// other fields to select
criteriaBuilder.function("group_concat", String.class, betSelection),
// other fields to select
);
//predicate, where clause and other filters
TypedQuery<GameDetailsDto> typedQuery = entityManager.createQuery(criteriaQuery);
this throws a null pointer exception on the line:
TypedQuery<GameDetailsDto> typedQuery = entityManager.createQuery(criteriaQuery);
did i incorrectly use the function method of the criteriaBuilder?
the documentations says:
function(String name, Class<T> type, Expression<?>... args);
I figured out how to do this with Hibernate-jpa-mysql:
1.) created a GroupConcatFunction class extending org.hibernate.dialect.function.SQLFunction (this is for single column group_concat for now)
public class GroupConcatFunction implements SQLFunction {
#Override
public boolean hasArguments() {
return true;
}
#Override
public boolean hasParenthesesIfNoArguments() {
return true;
}
#Override
public Type getReturnType(Type firstArgumentType, Mapping mapping)
throws QueryException {
return StandardBasicTypes.STRING;
}
#Override
public String render(Type firstArgumentType, List arguments,
SessionFactoryImplementor factory) throws QueryException {
if (arguments.size() != 1) {
throw new QueryException(new IllegalArgumentException(
"group_concat shoudl have one arg"));
}
return "group_concat(" + arguments.get(0) + ")";
}
}
2.) i created the CustomMySql5Dialect class extending org.hibernate.dialect.MySQL5Dialect and registered the group_concat class created in step 1
3.) On the app context, i updated the jpaVendorAdapter to use the CustomMySql5Dialect as the databasePlatform
4.) Finally to use it
criteriaBuilder.function("group_concat", String.class,
sampleRoot.get("sampleColumnName"))
Simple solution: instead of creating the whole class, just use SQLFunctionTemplate.
new SQLFunctionTemplate(StandardBasicTypes.STRING, "group_concat(?1)")
and then register this function in your own SQL dialect (eg. in constructor)
public class MyOwnSQLDialect extends MySQL5Dialect {
public MyOwnSQLDialect() {
super();
this.registerFunction("group_concat", new SQLFunctionTemplate(StandardBasicTypes.STRING, "group_concat(?1)"));
}
}
Suggested property:
spring.jpa.properties.hibernate.metadata_builder_contributor = com.inn.core.generic.utils.SqlFunctionsMetadataBuilderContributor
and class:
import org.hibernate.boot.MetadataBuilder;
import org.hibernate.boot.spi.MetadataBuilderContributor;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.stereotype.Component;
#Component
public class SqlFunctionsMetadataBuilderContributor implements MetadataBuilderContributor {
#Override
public void contribute(MetadataBuilder metadataBuilder) {
metadataBuilder.applySqlFunction("config_json_extract",
new StandardSQLFunction("json_extract", StandardBasicTypes.STRING));
metadataBuilder.applySqlFunction("JSON_UNQUOTE",
new StandardSQLFunction("JSON_UNQUOTE", StandardBasicTypes.STRING));
metadataBuilder.applySqlFunction("group_concat",
new StandardSQLFunction("group_concat", StandardBasicTypes.STRING));
}
}