Loading record in onBeforeInsert

I’m dealing several hours with this.

I have an entity to record Store In/out of products. On onBeforeInsert I firstly need to know if the product exist in the Store using as parameter some fields inserted at GUI.:

-store_id (Store entity)
-product_id (Product entity)
-combination_id (Combination entity)
-location (String)

Here is a snippet:

@Inject
DataManager dm;

@Override
public void onBeforeInsert(Movements entity, EntityManager entityManager) {
	
	Store store=entity.getStore();
	Product product=entity.getProduct();
Combination combination=entity.getCombination();
    String location =entity.getLocation();
	String whereClause=" where s.store_id= '"+store+"' and s.product_id= '"+product+"'";

if (combination==null) {
	whereClause=whereClause+" and s.combination_id is null";
} else {
	whereClause=whereClause+" and s.combination_id= '"+combination+"'";
}
if (location==null) {
	whereClause=whereClause+" and s.location is null";
} else {
	whereClause=whereClause+" and s.location='"+location+"'";
}
	
	
    LoadContext<Stock> loadContext = LoadContext.create(Stock.class)
            .setQuery(LoadContext.createQuery("select s from myapp$Stock s "+whereClause));
    List<Stock> stocks = dm.loadList(loadContext);
    if (stock.size()==0) {
       (create a new record on Store)
   } else {
      (update Store record)
  }

The question is that only store and product properties are required. The other properties can be null and must generate diferent stores records to search (load).

Tried with Datamanager, EntityManager, using myapp$Store or myapp_store, parameters (using Map<,>) or directly building the query string (as shown here). Anything works. Exceptions are thrown: “IllegalArgumentException: MetaClass not found for komerziaerp_stock” or “store is not a valid type”, etc.

I have no clue and I am stucked.

More simply. One of this snippet should work…

Try 1:

    LoadContext<Stock> loadContext = LoadContext.create(Stock.class)
            .setQuery(LoadContext.createQuery("select e from myapp$Stock e where e.almacen_id= :almacen and e.producto_id= :producto and e.combinacion_id= :combinacion  and e.lote_id= :lote)
            		.setParameter("almacen", entity.getAlmacen())
            		.setParameter("producto", entity.getProducto())
            		.setParameter("combinacion", entity.getCombinacion())
            		.setParameter("lote", entity.getLote())
            .setView("stock-view");
    List<Stock> stocks = dm.loadList(loadContext);

Try 2:

    LoadContext<Stock> loadContext = LoadContext.create(Stock.class)
            .setQuery(LoadContext.createQuery("select e from myapp$Stock e where e.almacen_id= :almacen and e.producto_id= :producto and e.combinacion_id= :combinacion  and e.lote_id= :lote)
            		.setParameter("almacen", entity.getAlmacen().getId())
            		.setParameter("producto", entity.getProducto().getId())
            		.setParameter("combinacion", entity.getCombinacion().getId())
            		.setParameter("lote", entity.getLote().getId()))
            .setView("stock-view");
    List<Stock> stocks = dm.loadList(loadContext);

… but it doesnt work. Both throws this exception:

JPQLException:
Exception Description: Problem compiling [select e from komerziaerp$Stock e where e.almacen_id= :almacen and e.producto_id= :producto and e.combinacion_id= :combinacion and e.lote_id= :lote].
[40, 52] The state field path ‘e.almacen_id’ cannot be resolved to a valid type.
[68, 81] The state field path ‘e.producto_id’ cannot be resolved to a valid type.
[127, 143] The state field path ‘e.combinacion_id’ cannot be resolved to a valid type.
[186, 195] The state field path ‘e.lote_id’ cannot be resolved to a valid type.

Got a solution… after several hours of investigation.

public void onBeforeInsert(Movimientos entity, EntityManager entityManager) {
	
	Combinaciones combinacion=entity.getCombinacion();
	Lotes lote=entity.getLote();
	String pasillo=entity.getPasillo();
	String estante=entity.getEstante();
	String altura=entity.getAltura();
	String cadenaWhere="select e from myapp_stock e where e.almacen_id= ?almacen and e.producto_id= ?producto";
	
	if (combinacion==null) {
		cadenaWhere=cadenaWhere+" and e.combinacion_id is null";
	}else {
		cadenaWhere=cadenaWhere+" and e.combinacion_id= ?combinacion";
	}
	if (lote==null) {
		cadenaWhere=cadenaWhere+" and e.lote_id is null";
	}else {
		cadenaWhere=cadenaWhere+" and e.lote_id= ?lote";
	}


	TypedQuery<Stock> query=entityManager.createNativeQuery(cadenaWhere, Stock.class)
		.setParameter("almacen", entity.getAlmacen().getId())
		.setParameter("producto", entity.getProducto().getId());
		if (combinacion!=null) {
			query.setParameter("combinacion", entity.getCombinacion().getId());
		}
		if (lote!=null) {
			query.setParameter("lote", entity.getLote().getId());
		}
	List<Stock> stocks = query.getResultList();

It works, but I would prefer using JPSQL.

In JPQL, you should use names of attributes, not columns. So if your Stock class has almacen attribute, the following JPQL should work:

select e from myapp$Stock e where e.almacen = :almacen

Oh my!!

Was obsessed with e.almacen_id and didnt try e.almacen… Will try and let you know. Thanks.

@knstvk, Still doesn’t work for me…

public void onBeforeInsert(Movimientos entity, EntityManager entityManager) {
		Combinaciones combinacion=entity.getCombinacion();
		Lotes lote=entity.getLote();
                String cadenaWhere="select e from myapp$Stock e where e.almacen= :almacen and e.producto= :producto";
    	
		if (combinacion==null) {
			cadenaWhere=cadenaWhere+" and e.combinacion is null";
		}else {
			cadenaWhere=cadenaWhere+" and e.combinacion= :combinacion";
		}
		if (lote==null) {
			cadenaWhere=cadenaWhere+" and e.lote is null";
		}else {
			cadenaWhere=cadenaWhere+" and e.lote= :lote";
		}


		Almacen almacen = (Almacen) entity.getAlmacen();
		Productos producto = (Productos) entity.getProducto();
        LoadContext<Stock> loadContext = LoadContext.create(Stock.class)
                .setQuery(LoadContext.createQuery(cadenaWhere)
                		.setParameter("almacen", almacen)
                		.setParameter("producto", producto));
         		if (combinacion!=null) {
           			loadContext.getQuery().setParameter("combinacion", combinacion);
           		}
           		if (lote!=null) {
           			loadContext.getQuery().setParameter("lote", lote);
          		}
        List<Stock> stocks = dm.loadList(loadContext);    	
}

Exception:

IllegalArgumentException: You have attempted to set a value of type class java.util.UUID for parameter almacen with expected type of class com.company.myapp.entity.Almacen from query string select e from myapp$Stock e where e.almacen= :almacen and e.producto= :producto and e.combinacion= :combinacion and e.lote is null

Seems I must stick with the previous solution.

hi,

and e.combinacion.id = :combinacion should do the trick. Although i’m not 100% sure why without .id it does not work (it should imho).

Bye
Mario

@mario, using e..id works. Why? a bug? something i did wrong?.. i dont know, but it works.

Not a bug, rather a feature. It is explained here:

setParameter() – sets a value to a query parameter. If the value is an entity instance, implicitly converts the instance into its identifier.

Note that the entity is passed as a parameter while comparison in the query is done using identifier. A variant of the method with implicitConversions = false does not perform such conversion.

Actually, this behavior is a legacy of our previous ORM implementation - OpenJPA, where you couldn’t compare references, only their attributes. We made this implicit conversion for convenience, but now it is useless and we should get rid of it in a future version, just providing a backward compatibility toggle for old projects.

@knstvk

Then, did I got it if i think I should toggle implicitConversions to false and dont use “.id” in comparison?

Yes you can, but it makes no difference. It will produce the same SQL as when you write e.combinacion.id = :combinacion and use default implicit conversion. Just be aware of it.

1 Like

@knstvk but e.combinacion = :combinacion will not work, correct?

This is at least what I experiences sometimes (cannot really remember). In case - why not? Shouldn’t it?

Perhaps I misunderstood your above explanation, but it seems more towards why e. combinacion.id = :combinacion works and not why e.combinacion = :combinacion does not work, correct?

@mario, it should work if you set the parameter without implicit conversion. See for example Added test for query on reference without implicit conversion · cuba-platform/cuba@5823b85 · GitHub

So I think it’s a more natural way of expressing condition than using identifiers, and we should make it the default way in the future.

Hello everyone, I’ m tryng to load a set of entities (MembershipFee) to do port-validation of user input in editor.
I’m trying with DataManager as in manual Example I’ll attach mine in following lines:

Manual:
https://doc.cuba-platform.com/manual-6.9/dataManager.html

----------------------------- Code: get a List of existing MembershipFee in MemberFee editor --------
@Inject
private DataManager dataManager

private List loadMembershipFees(UUID artistId) {
LoadContext loadContext = LoadContext.create(MembershipFee.class)
.setQuery(LoadContext.createQuery(“select f from contacts$MembershipFee f where f.artistInfo.id = :artistId”)
.setParameter(“artistId”, artistId))
.setView(“membershipFee-basic”)
return dataManager.loadList(loadContext)
}
----------------------------- Code: get a List of existing MembershipFee in MemberFee editor --------

  1. I’m receiving contactsMembershipFee metaclass doesn’ t exists and I do not understand why (it seems JQL query is not correctly written)

  2. can I use simply _local view? How to specify it il setView(String)

Thank you in advance,
Fabrizio

Did you Import MembershipFee class? Seems it’s not, or it’s not written properly,

BTW, I would create a new post for this question and add full error message

Hello thank you for assistance.
Yes I obviously imported model class MembershipFee.

I tried to create a service, but I obtain same error.
Then observing error detail I supposed problem was in Metadata and I debugged this code I added to editor:

/* Session session = metadata.getSession()
MetaClass metaClass1 = session.getClassNN(“contacts$MembershipFee”)*/

Same result…
To avoid Mispelled names I copied from Studio…
Last thing I can imagine is there is some not visible charachter in some of code (I can try linux/unic od to investigate) or the clas name is not in some restriction not known to me.

------- Complete Error Message Using DataManager in code, not custom service -------------------
java.lang.IllegalArgumentException: MetaClass not found for contactsclass
at com.haulmont.cuba.core.sys.CachingMetadataSession.getClassNN(CachingMetadataSession.java:70)
at com.haulmont.cuba.core.sys.MetadataImpl.getClassNN(MetadataImpl.java:319)
at com.haulmont.cuba.core.sys.PersistenceSecurityImpl.applyConstraints(PersistenceSecurityImpl.java:75)
at sun.reflect.GeneratedMethodAccessor164.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:84)
at com.haulmont.cuba.core.sys.PerformanceLogInterceptor.aroundInvoke(PerformanceLogInterceptor.java:29)
at sun.reflect.GeneratedMethodAccessor163.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:627)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:616)
at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:168)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy55.applyConstraints(Unknown Source)
at com.haulmont.cuba.core.app.DataServiceQueryBuilder.applyConstraints(DataServiceQueryBuilder.java:187)
at com.haulmont.cuba.core.app.DataServiceQueryBuilder.getQuery(DataServiceQueryBuilder.java:127)
at com.haulmont.cuba.core.app.RdbmsStore.createQuery(RdbmsStore.java:633)
at com.haulmont.cuba.core.app.RdbmsStore.loadList(RdbmsStore.java:224)
at com.haulmont.cuba.core.app.DataManagerBean.loadList(DataManagerBean.java:74)
at com.haulmont.cuba.core.app.DataServiceBean.loadList(DataServiceBean.java:54)
at sun.reflect.GeneratedMethodAccessor166.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:84)
at com.haulmont.cuba.core.sys.ServiceInterceptor.aroundInvoke(ServiceInterceptor.java:117)
at sun.reflect.GeneratedMethodAccessor121.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:627)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:616)
at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:168)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy85.loadList(Unknown Source)
at sun.reflect.GeneratedMethodAccessor165.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.haulmont.cuba.core.sys.remoting.LocalServiceInvokerImpl.invoke(LocalServiceInvokerImpl.java:94)
at com.haulmont.cuba.web.sys.remoting.LocalServiceProxy$LocalServiceInvocationHandler.invoke(LocalServiceProxy.java:154)
at com.sun.proxy.$Proxy257.loadList(Unknown Source)
at com.haulmont.cuba.client.sys.DataManagerClientImpl.loadList(DataManagerClientImpl.java:57)
at com.haulmont.cuba.core.global.DataManager$loadList.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:128)
at pro.sysonline.contacts.web.membershipfee.MembershipFeeEdit.loadMembershipFees(MembershipFeeEdit.groovy:75)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:210)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:59)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:51)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:157)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:169)
at pro.sysonline.contacts.web.membershipfee.MembershipFeeEdit.postValidate(MembershipFeeEdit.groovy:50)
at com.haulmont.cuba.gui.components.WindowDelegate.postValidate(WindowDelegate.java:208)
at com.haulmont.cuba.web.gui.WebWindow.handleValidationErrors(WebWindow.java:435)
at com.haulmont.cuba.web.gui.WebWindow.validateAll(WebWindow.java:428)
at com.haulmont.cuba.gui.components.AbstractWindow.validateAll(AbstractWindow.java:217)
at com.haulmont.cuba.web.gui.WebWindow$Editor.commitAndClose(WebWindow.java:1770)
at com.haulmont.cuba.gui.components.AbstractEditor.commitAndClose(AbstractEditor.java:111)
at com.haulmont.cuba.gui.components.EditorWindowDelegate.lambda$wrapBy$1(EditorWindowDelegate.java:94)
at com.haulmont.cuba.gui.components.actions.BaseAction.actionPerform(BaseAction.java:228)
at com.haulmont.cuba.web.gui.components.WebButton.performAction(WebButton.java:46)
at com.haulmont.cuba.web.gui.components.WebButton.lambda$new$61446b05$1(WebButton.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:510)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:200)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:163)
at com.vaadin.server.AbstractClientConnector.fireEvent(AbstractClientConnector.java:1037)
at com.vaadin.ui.Button.fireClick(Button.java:377)
at com.haulmont.cuba.web.toolkit.ui.CubaButton.fireClick(CubaButton.java:69)
at com.vaadin.ui.Button$1.click(Button.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:158)
at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:119)
at com.vaadin.server.communication.ServerRpcHandler.handleInvocation(ServerRpcHandler.java:444)
at com.vaadin.server.communication.ServerRpcHandler.handleInvocations(ServerRpcHandler.java:409)
at com.vaadin.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:274)
at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:90)
at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:41)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1435)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:361)
at com.haulmont.cuba.web.sys.CubaApplicationServlet.serviceAppRequest(CubaApplicationServlet.java:312)
at com.haulmont.cuba.web.sys.CubaApplicationServlet.service(CubaApplicationServlet.java:203)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CompositeFilter$VirtualFilterChain.doFilter(CompositeFilter.java:107)
at org.springframework.web.filter.CompositeFilter.doFilter(CompositeFilter.java:73)
at com.haulmont.cuba.web.sys.CubaHttpFilter.doFilter(CubaHttpFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)

------- Complete Error Message Using DataManager in code, not custom service -------------------

------- Full Editor Controller source--------------------------------------------------

package pro.sysonline.contacts.web.membershipfee

import com.haulmont.cuba.core.global.DataManager
import com.haulmont.cuba.core.global.LoadContext
import com.haulmont.cuba.core.global.Messages
import com.haulmont.cuba.gui.components.AbstractEditor
import com.haulmont.cuba.gui.components.ValidationErrors
import com.sun.xml.internal.ws.api.model.MEP
import pro.sysonline.contacts.entity.ArtistInfo
import pro.sysonline.contacts.entity.MembershipFee
import pro.sysonline.contacts.entity.MembershipFeeType

import javax.inject.Inject

class MembershipFeeEdit extends AbstractEditor {

private ArtistInfo a

@Inject
private DataManager dataManager

@Inject
private Messages messages

/* @Inject
private MembershipFeeService memberShipService

@Inject
protected Metadata metadata

*/

@Override
void init(Map<String, Object> params) {
    super.init(params)
    a = (ArtistInfo) params.get("artist")
}

// Initialize Editor for new MembershipFee Item
@Override
protected void initNewItem(MembershipFee item) {
    item.artistInfo = a
}

@Override
void postValidate(ValidationErrors errors) {
    Integer MAX_YEARLY_FEE = 5
    MembershipFee it
    List<MembershipFee> l = new ArrayList<MembershipFee>()
    l = loadMembershipFees(a)

    if ((l != null) && (!l.isEmpty())) {

        // First Year already present
        if (item.type.equals(MembershipFeeType.FIRST_YEAR))
            if (l.any() { it.type == MembershipFeeType.FIRST_YEAR })
                errors.add(messages.getMessage(getClass(), "errorFY"))

        // All Fees presents
        if (l.count() { it.type == MembershipFeeType.NEXT_YEAR } == MAX_YEARLY_FEE)
            errors.add(messages.getMessage(getClass(), "errorMAX_YF"))

    }
}

private List<MembershipFee> loadMembershipFees(ArtistInfo a) {

/*    Session session = metadata.getSession()
    MetaClass metaClass1 = session.getClassNN("contacts$MembershipFee")*/

    LoadContext<MembershipFee> loadContext = LoadContext.create(MembershipFee.class)
            .setQuery(LoadContext.createQuery("select f from contacts$MembershipFee f where f.artistInfo.id = :artistId")
            .setParameter("artistId", a.id))
            .setView("membershipFee-basic")
    //return dataManager.loadList(loadContext)  DATAMANAGER

    //return memberShipService.getMemberShipFeesForArtist(a)  SERVICE

    // Temporary Workaround
    return null

}

}

------- Service source--------------------------------------------------

package pro.sysonline.contacts.service

import com.haulmont.cuba.core.EntityManager
import com.haulmont.cuba.core.Persistence
import com.haulmont.cuba.core.Transaction
import org.slf4j.Logger
import org.springframework.stereotype.Service
import pro.sysonline.contacts.entity.ArtistInfo
import pro.sysonline.contacts.entity.MembershipFee

import javax.inject.Inject

@Service(MembershipFeeService.NAME)
public class MembershipFeeServiceBean implements MembershipFeeService {

@Inject
Logger log

@Inject
private Persistence persistence




@Override
List<MembershipFee> getMemberShipFeesForArtist(ArtistInfo a) {
    EntityManager em = null
    Transaction tx = null
    com.haulmont.cuba.core.Query query = null
    List<MembershipFee>  l
    String queryStr = "select f from contacts$MembershipFee f where f.artistInfo = :artistId"

    try {

        tx = persistence.createTransaction()
        em = persistence.getEntityManager()

        query = em.createQuery(queryStr)
        query.setParameter("artistId",a.id)

q
l = (List) query.getResultList()

        tx.commit()

    } catch (Exception ex) {
        log.debug(Class.getName())
    } finally {
        tx.end()
    }

    return ((null != l)  ? l : new ArrayList<MembershipFee>())
}

}

Please start a new topic and format your message appropriately. It’s almost unreadable now.

Sorry, I’ll create a new topic from scratch and better explain what I’m trying to do…
In order to format source code do I have to use tags? I saw something similar in other posts…

Just use ``` before and after code block.

Thanks, tomorrow or later I’ll open a more comprensible post.