Spring Jpa Specification and Eager loading - spring

How can i get list of tiket with its categories through Jpa Specification
Example model:
#Entity
#Table(name = "tickets")
public class Ticket {
#Id
private Integer id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "category_id")
private Category
}
Method of service:
public Page<Ticket> findAll(Pageable pageable) {
return ticketRepository.findAll((root, query, cb) -> {
root.join("category");
return query.getRestriction();
}, pageable);
}

I was able to eager load the collection by using a fetch instead of a join.
public Page<Ticket> findAll(Pageable pageable) {
return ticketRepository.findAll((root, query, cb) -> {
root.fetch("category");
return query.getRestriction();
}, pageable);
}
The fetch method will use the default join type (inner). If want to load tickets with no category, you'll have to pass JoinType.LEFT as the second parameter.

as they say, stackoverflow giveth, stackoverflow taketh..
I took this class off SO quite some time ago, feel free to recycle it..
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.commons.beanutils.PropertyUtils;
import org.hibernate.Hibernate;
public class BeanLoader {
/**
* StackOverflow safe, if called before json creation, cyclic object must be avoided
*/
public static void eagerize(Object obj) {
if(!Hibernate.isInitialized(obj))
Hibernate.initialize(obj);
PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(obj);
for (PropertyDescriptor propertyDescriptor : properties) {
Object origProp = null;
try {
origProp = PropertyUtils.getProperty(obj, propertyDescriptor.getName());
} catch (IllegalAccessException e) {
// Handled, but hopefully dead code
origProp=null;
} catch (InvocationTargetException e) {
// Single catch for obsolete java developers!
origProp=null;
} catch (NoSuchMethodException e) {
// Single catch for obsolete java developers!
origProp=null;
}
if (origProp != null
&& origProp.getClass().getPackage().toString().contains("domain")) {
eagerize(origProp, new ArrayList<String>());
}
if (origProp instanceof Collection) {
for (Object item : (Collection) origProp) {
if (item.getClass().getPackage().toString().contains("domain")){
eagerize(item, new ArrayList<String>());
}
}
}
}
}
/**
* StackOverflows if passed a bean containing cyclic fields. Call only if sure that this won't happen!
*/
public static void eagerizeUnsafe(Object obj) {
if(!Hibernate.isInitialized(obj))
Hibernate.initialize(obj);
PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(obj);
for (PropertyDescriptor propertyDescriptor : properties) {
Object origProp = null;
try {
origProp = PropertyUtils.getProperty(obj, propertyDescriptor.getName());
} catch (IllegalAccessException e) {
// Handled, but hopefully dead code
origProp=null;
} catch (InvocationTargetException e) {
// Single catch for obsolete java developers!
origProp=null;
} catch (NoSuchMethodException e) {
// Single catch for obsolete java developers!
origProp=null;
}
if (origProp != null
&& origProp.getClass().getPackage().toString().contains("domain")) {
eagerize(origProp);
}
if (origProp instanceof Collection) {
for (Object item : (Collection) origProp) {
if (item.getClass().getPackage().toString().contains("domain")){
eagerize(item);
}
}
}
}
}
private static void eagerize(Object obj, ArrayList<String> visitedBeans) {
if (!visitedBeans.contains(obj.getClass().getName())){
visitedBeans.add(obj.getClass().getName());
} else {
return;
}
if(!Hibernate.isInitialized(obj))
Hibernate.initialize(obj);
PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(obj);
for (PropertyDescriptor propertyDescriptor : properties) {
Object origProp = null;
try {
origProp = PropertyUtils.getProperty(obj, propertyDescriptor.getName());
} catch (IllegalAccessException e) {
// Handled, but hopefully dead code
origProp=null;
} catch (InvocationTargetException e) {
// Single catch for obsolete java developers!
origProp=null;
} catch (NoSuchMethodException e) {
// Single catch for obsolete java developers!
origProp=null;
}
if (origProp != null
&& origProp.getClass().getPackage().toString().contains("domain")) {
eagerize(origProp, visitedBeans);
}
if (origProp instanceof User){
((User) origProp).setRelatedNra(null);
User u=(User) origProp;
if (u.getRelatedMps()!=null)
u.getRelatedMps().clear();
if (u.getRelatedDps()!=null)
u.getRelatedDps().clear();
}
if (origProp instanceof Collection) {
for (Object item : (Collection) origProp) {
if (item.getClass().getPackage().toString().contains("domain")){
eagerize(item, (ArrayList<String>) visitedBeans.clone());
}
}
}
}
}
}
modify it as you see fit.. the method you'll call is "eagerizeUnsafe".
YMMV, but this should to the trick to eagerize all the collections of a lazily initialized bean.

Related

Custom annotation Quarkus

We are building the following method that copies values from one entity to another and then persists the changes which works fine for us.
private void copyProperties(E orig, E dest) {
try {
for (Field origField : orig.getClass().getDeclaredFields()) {
try {
origField.setAccessible(true);
Object value = origField.get(orig);
if (value != null) {
Field destField = dest.getClass().getDeclaredField(origField.getName());
destField.setAccessible(true);
destField.set(dest, value);
}
} catch (IllegalAccessException | NoSuchFieldException ex) {
System.out.println("IllegalAccessException ");
ex.printStackTrace();
}
}
} catch (SecurityException ex) {
System.out.println("SecurityException ");
ex.printStackTrace();
}
}
But now we need to update only the properties that have present a specific annotation called #updatable.
#Documented
#Target({ElementType.FIELD, ElementType.TYPE_USE})#Retention(RetentionPolicy.RUNTIME)public #interface Updatable {
#Nonbindingboolean nullable() default false;
}
private void copyProperties(E orig, E dest) {
try {
for (Field origField : orig.getClass().getDeclaredFields()) {
Updatable annotation = origField.getAnnotation(Updatable.class);
if (annotation != null) {
System.out.println("Field "+origField.getName()+" annotation present");
try {
origField.setAccessible(true);
Object value = origField.get(orig);
if (value != null || annotation.nullable()) {
Field destField = dest.getClass().getDeclaredField(origField.getName());
destField.setAccessible(true);
destField.set(dest, value);
}
} catch (IllegalAccessException | NoSuchFieldException ex) {
System.out.println("IllegalAccessException ");
ex.printStackTrace();
}
}
}
} catch (SecurityException ex) {
System.out.println("SecurityException ");
ex.printStackTrace();
}
}
The problem is that when we analyze the annotation and return by reference the destination entity with the updated properties, the merge method in quarkus does not detect the changes.

Hibernate mapping: Get collection on runtime with nullSafeGet overrided method

To make the mapping between hibernate and my database work, I have this mapping :
<property name="userRolesV2" column="user_roles_v2">
<type name="io.markethero.repository.CommaSeparatedGenericEnumType">
<param name="enumClassName">io.markethero.model.UserLoginRoleV2</param>
<param name="collectionClassName">java.util.Set</param>
</type>
</property>
The idea is to directly get the Collection in my field class instead of doing the mapping each time.
For example, the field in the class could be a Set, a List, or a Queue.
In the database, the value is like "enumValue1,enumValue2,enumValue3".
To do that, my class CommaSeparatedGenericEnumType is like this:
public class CommaSeparatedGenericEnumType implements UserType, ParameterizedType {
private Class enumClass = null;
private Class targetCollection = null;
public void setParameterValues(Properties params) {
String enumClassName = params.getProperty("enumClassName");
String collectionClassName = params.getProperty("collectionClassName");
if (enumClassName == null) {
throw new MappingException("enumClassName parameter not specified");
}
if (collectionClassName == null) {
throw new MappingException("collectionClassName parameter not specified");
}
try {
this.enumClass = Class.forName(enumClassName);
} catch (ClassNotFoundException e) {
throw new MappingException("enumClass " + enumClassName + " not found", e);
}
try {
this.targetCollection = Class.forName(collectionClassName);
} catch (ClassNotFoundException e) {
throw new MappingException("targetCollection " + collectionClassName + " not found", e);
}
}
#Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
String commaSeparatedValues = rs.getString(names[0]);
List<Object> result = new ArrayList<>();
if (!rs.wasNull()) {
String[] enums = commaSeparatedValues.split(",");
for (String string : enums) {
result.add(Enum.valueOf(enumClass, string));
}
}
return result;
}
#Override
#SuppressWarnings("unchecked")
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
if (null == value) {
st.setNull(index, Types.VARCHAR);
} else {
List<Object> enums = (List) value;
StringBuilder sb = new StringBuilder("");
for (Object each : enums) {
sb.append(each.toString()).append(",");
}
if (sb.toString().isEmpty()) {
st.setNull(index, Types.VARCHAR);
} else {
String commaSeparatedIds = sb.toString().substring(0, sb.toString().length() - 1);
st.setString(index, commaSeparatedIds);
}
}
}
}
I would like to be able to parametrize which collection nullSafeGet and nullSafeSet are going to use, because for now, it's only working with a list.
Thank you!
Maybe my question was asked was oddly, but here what I did:
For the getter, I used the factory pattern already implemented by Spring : CollectionFactory.
#Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
String commaSeparatedValues = rs.getString(names[0]);
Collection<Object> result = CollectionFactory.createCollection(this.targetCollection, 50);
if (!rs.wasNull()) {
String[] enums = commaSeparatedValues.split(",");
for (String string : enums) {
try {
result.add(Enum.valueOf(enumClass, string));
} catch (IllegalArgumentException e) {
throw new MappingException("[CommaSeparatedGenericEnumType::nullSafeGet] No such enum value"+ string +"for enum : " + enumClass, e);
}
}
}
return result;
}
For the setter, I used the reflection API.
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, Types.VARCHAR);
} else {
if (value instanceof Collection) {
try {
StringBuilder sb = new StringBuilder("");
Constructor<?> c = value.getClass().getConstructor(Collection.class);
Collection<Object> enums = (Collection<Object>) c.newInstance((Collection<Object>) value);
for (Object each : enums) {
sb.append(each.toString()).append(",");
}
String commaSeparatedIds = sb.substring(0, sb.toString().length() - 1);
if (sb.length() > 0) {
st.setString(index, commaSeparatedIds);
} else {
st.setNull(index, Types.VARCHAR);
}
} catch (NoSuchMethodException e) {
throw new MappingException("[CommaSeparatedGenericEnumType::nullSafeSet] No such constructor found for class : " + value.getClass(), e);
} catch (InstantiationException e) {
throw new MappingException("[CommaSeparatedGenericEnumType::nullSafeSet] Class : " + value.getClass() + " cannot be instantiate ", e);
} catch (IllegalAccessException e) {
throw new MappingException("[CommaSeparatedGenericEnumType::nullSafeSet] You cannot access to constructor of class : " + value.getClass(), e);
} catch (InvocationTargetException e) {
throw new MappingException("[CommaSeparatedGenericEnumType::nullSafeSet] InvocationTargetException for class : " + value.getClass(), e);
}
} else {
st.setNull(index, Types.VARCHAR);
throw new IllegalArgumentException();
}
}
}

How to fix 'No way to dispatch this command to Redis Cluster because keys have different slots' in Spring

I need to use Redis Cluster in Spring. But I'm getting the following error when I use mget or del on a list of keys: 'No way to dispatch this command to Redis Cluster because keys have different slots'. Showing a part of my Component code using JedisCluster.
It works when I use single key operations but not with multiple keys.
/* Component Code */
public class RedisServiceManager {
#Value("${redis.hosts}")
String hosts;
#Autowired
JedisPoolConfig jedisPoolConfig;
private JedisCluster jedisCluster;
#PostConstruct
private void init() {
List<String> redisHosts = Arrays.asList(hosts.split(","));
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
redisHosts.forEach(redisHost -> {
jedisClusterNode.add(new HostAndPort(redisHost, 6379));
});
jedisCluster = new JedisCluster(jedisClusterNode, jedisPoolConfig);
}
// This works
public String getValueForKey(String key) {
try {
return jedisCluster.get(key);
} catch (Exception e) {
return null;
}
}
// This works
public void delKey(String cacheKey) {
try {
jedisCluster.del(cacheKey);
} catch (Exception e) {
}
}
// This doesn't work
public List<String> getValuesForAllKeys(String... keys) {
try {
return jedisCluster.mget(keys);
} catch (Exception e) {
return new ArrayList<>();
}
}
// This doesn't work
public void delAllKeys(String... keys) {
try {
jedisCluster.del(keys);
} catch (Exception e) {
}
}
}
Can someone help with this?
This is not a bug or an issue, but is the way how redis cluster works. You can find more details in the cluster documentation. But don't worry: there is a "trick": you can use hash as described here

Usage of custom freemarker template

I was wondering if anyone can help me with Apache FreeMarker? I'm trying to use a custom model but I can't figure it out.
Imagine I want to dump the result of a query (java ResultSet in a FreeMarker template). What is the best approach?
I have found on Google the class: ResultSetTemplateModel
import java.sql.ResultSet;
import freemarker.template.SimpleScalar;
import freemarker.template.TemplateHashModel;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateSequenceModel;
public class ResultSetTemplateModel implements TemplateSequenceModel {
private ResultSet rs = null;
public ResultSetTemplateModel(ResultSet rs) {
this.rs = rs;
}
public TemplateModel get(int i) throws TemplateModelException {
try {
rs.next();
} catch(Exception e) {
throw new TemplateModelException(e.toString());
}
TemplateModel model = new Row(rs);
return model;
}
public int size() throws TemplateModelException {
int size=0;
try {
rs.last();
size = rs.getRow();
rs.beforeFirst();
} catch (Exception e ) {
throw new TemplateModelException( e.toString());
}
return size;
}
class Row implements TemplateHashModel {
private ResultSet rs = null;
public Row(ResultSet rs) {
this.rs = rs;
}
public TemplateModel get(String s) throws TemplateModelException {
TemplateModel model = null;
try {
model = new SimpleScalar( rs.getString(s) );
} catch (Exception e) { e.printStackTrace(); }
return model;
}
public boolean isEmpty() throws TemplateModelException {
boolean isEmpty = false;
if ( rs == null ) { isEmpty = true; }
return isEmpty;
}
}
}
And I have a very simple class (I even made it easier than previous):
public static void main(String[] args) {
try {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_27);
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setClassForTemplateLoading(MyCLASS.class, "/");
StringWriter out = new StringWriter();
Map<String, Object> parameters = new TreeMap<>();
ResultSet rs = getResultSet("Select foo, bar FROM my_table");
parameters.put("hello", "World");
parameters.put("result", rs);
Template temp = cfg.getTemplate("template.txt");
temp.process(parameters, out);
System.out.println("out = " + out);
} catch (IOException | TemplateException e) {
e.printStackTrace();
}
}
My template
Hello ${hello}
<#-- how do I specify ResultSet columns here ?? -->
How can I use the custom template?? Any advice?? I know how to load the template file. But I don't know how to specify that it is a custom model in the template.
THank you guys for the support :)
There are two ways of using ResultSetTemplateModel for wrapping ResultSet-s:
Either extend DefaultObjectWrapper by overriding handleUnknownType, where you return new ResultSetTemplateModel((ResultSet) obj) if obj is a ResultSet, otherwise call super. Then use Configuration.setObjectWrapper to actually use it.
Or, add new ResultSetTemplate(rs) to parameters instead of rs; if something is already a TempalteModel, it will not be wrapped again. Note that if you get a ResultSet from somewhere else in the template, this approach will not work as it avoids your manual wrapping, so extending the DefaultObjectWrapper is what you want generally.
Note that the ResultSetTemplateModel implementation shown is quite limited. The ObjectWrapper should be passed to the constructor as well, and stored in a final field. Then, instead of new SimpleScalar( rs.getString(s) ) it should do objectWrapper.wrap(rs.getObject(s)).

spring-data query

public interface AreaRepository extends JpaRepository<Area, Integer>, JpaSpecificationExecutor<Area>{
#Query("from Area where sup is null")
List<Area> findProvinces();
#Query("from Area where sup is null")
Page<Area> findProvinces(Pageable pg);
}
Here is my code. The first method works fine but the second one doesn't. Can anyone tell me how to make it correct?
here doesn't work mean the second query throws an error and can't find out all the data specified by my sql
#Query("from Area where sup is null")
.
Actually what i want to archieve is a qbe pattern using jpa,and i finally got a solution implementing org.springframework.data.jpa.domain.Specification interface.
public class QbeSpec<T> implements Specification<T> {
private final T example;
public QbeSpec(T example) {
this.example = example;
}
#Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
if (example == null) {
return cb.isTrue(cb.literal(true));
}
BeanInfo info = null;
try {
info = Introspector.getBeanInfo(example.getClass());
} catch (IntrospectionException e) {
throw new RuntimeException(e);
}
List<Predicate> predicates = new ArrayList<Predicate>();
for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
String name = pd.getName();
Object value = null;
if (name.equals("class"))
continue;
try {
value = pd.getReadMethod().invoke(example);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (value != null) {
Path<String> path = root.get(name);
// string using like others using equal
if (pd.getPropertyType().equals(String.class)) {
predicates.add(cb.like(path, "%" + value.toString() + "%"));
} else {
predicates.add(cb.equal(path, value));
}
}
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
}

Resources