Friday, May 16, 2014

Hibernate relationship templates

Here is a list with one-to-many, one-to-one and many-to-many relations templates.

One-to-many:
@Entity(name = "parent")
@Access(AccessType.FIELD)
public class Parent {

    @OneToMany(fetch = FetchType.LAZY, mappedBy="childVarName", orphanRemoval=true)
    protected Set<Child> parentVarName;
}

@Entity(name = "child")
@Access(AccessType.FIELD)
public class Child {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "child", nullable = false)
    protected Parent childVarName;
}

One-to-one:
public class VirtualParent {
    @OneToOne(mappedBy = "virtualParentVar")
    protected VirtualChild virtualChildVar;
    // ...
}

public class VirtualChild {
    @OneToOne
    @JoinColumn(name = "frn_virtual_parent_id")
    protected VirtualParent virtualParentVar;
    // ...
}

Many-to-many:

Wednesday, May 14, 2014

Setting transactional Spring components manually

There is an issue while setting @Transactional Spring components, because of proxies used to generate them. Here is an solution for that:

Setter:        
ReflectionTestUtils.setField( 
    TestUtils.unwrapTransactionalServiceSafe(serviceWithAutowiredComponents), 
    "externalService", newExternalServiceInstance );


Utils:
    public static Object unwrapTransactionalService( Object transactionalService ) throws Exception {
      if(AopUtils.isAopProxy(transactionalService) && transactionalService instanceof Advised) {
          Object target = ((Advised) transactionalService).getTargetSource().getTarget();
          return target;
      }
      return null;
    }
    public static Object unwrapTransactionalServiceSafe( Object transactionalService ){
        try {
            return unwrapTransactionalService( transactionalService );
        } catch (Exception ex) {
            throw new RuntimeException( ex );
        }
    }



Tuesday, May 13, 2014

Spring: setting properties externally

        ReflectionTestUtils.setField( mobileController, "externalService", externalService );