Showing posts with label spring. Show all posts
Showing posts with label spring. Show all posts

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 );

Tuesday, April 22, 2014

Spring repositories with native queries - Supported keywords inside findBy method names



KeywordSampleJPQL snippet
AndfindByLastnameAndFirstname… where x.lastname = ?1 and x.firstname = ?2
OrfindByLastnameOrFirstname… where x.lastname = ?1 or x.firstname = ?2
BetweenfindByStartDateBetween… where x.startDate between 1? and ?2
LessThanfindByAgeLessThan… where x.age < ?1
GreaterThanfindByAgeGreaterThan… where x.age > ?1
After
findByStartDateAfter… where x.startDate > ?1
Before
findByStartDateBefore… where x.startDate < ?1
IsNullfindByAgeIsNull… where x.age is null
IsNotNull,NotNullfindByAge(Is)NotNull… where x.age not null
LikefindByFirstnameLike… where x.firstname like ?1
NotLikefindByFirstnameNotLike… where x.firstname not like ?1
StartingWithfindByFirstnameStartingWith… where x.firstname like ?1 (parameter bound with appended %)
EndingWithfindByFirstnameEndingWith… where x.firstname like ?1 (parameter bound with prepended %)
ContainingfindByFirstnameContaining… where x.firstname like ?1 (parameter bound wrapped in %)
OrderByfindByAgeOrderByLastnameDesc… where x.age = ?1 order by x.lastname desc
NotfindByLastnameNot… where x.lastname <> ?1
InfindByAgeIn(Collection<Age> ages)… where x.age in ?1
NotInfindByAgeNotIn(Collection<Age> age)… where x.age not in ?1
TruefindByActiveTrue()… where x.active = true
FalsefindByActiveFalse()… where x.active = false


Source: http://docs.spring.io/spring-data/jpa/docs/1.4.3.RELEASE/reference/html/jpa.repositories.html

Tuesday, February 25, 2014

Avoiding CORS security issues

CORS is security policy, according which a page could not be iframe-d from page from another site.

ajax requests are implemented via iframe, so if we want to do ajax requests to another site, we encounter CORS error.

How to enable this?

Solution is to tell server to allow the page/JSON/webservice to be iframed. This is done this way:
    public String getUserById(@PathVariable("id") Long id, HttpServletResponse httpResponse) throws JsonProcessingException {
        httpResponse.addHeader("Access-Control-Allow-Origin", "*");
        // do real work

    }

Access-Control-Allow-Origin is the header that allows this. Check wikipedia for other solutions.

solved: Spring + Hibernate used with JPA and EntityManager => HibernateException: collection is not associated with any session

When I started using lazy loading in Spring + Hibernate project, I encounter this error.

What does NOT solve my issue:
  • @Transactional annotation
  • OpenSessionInViewInterceptor


The error message was:

HTTP ERROR 500

Problem accessing /user/1. Reason:
    Server Error

Caused by:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: collection is not associated with any session
 at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)


Solution for Spring with JPA approach and EntityManager, is to use OpenEntityManagerInViewFilter. Register it in web.xml this way: