Created
March 3, 2011 17:21
-
-
Save emmanuelbernard/853130 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.jamesward; | |
import java.util.List; | |
import org.springframework.flex.remoting.RemotingDestination; | |
import org.springframework.stereotype.Repository; | |
import org.springframework.stereotype.Service; | |
import org.springframework.transaction.annotation.Transactional; | |
import javax.persistence.EntityManager; | |
import javax.persistence.PersistenceContext; | |
import javax.persistence.criteria.CriteriaQuery; | |
import javax.persistence.criteria.Root; | |
@Repository | |
@Service | |
@RemotingDestination | |
public class FooService | |
{ | |
@PersistenceContext | |
private EntityManager entityManager; | |
//in EE 6 | |
@Inject Validator validator; //@Resource works too | |
@Transactional | |
public Foo getFooById(String id) | |
{ | |
return entityManager.find(Foo.class, id); | |
} | |
@Transactional | |
public List<Foo> getAll() | |
{ | |
CriteriaQuery<Foo> criteriaQuery = entityManager.getCriteriaBuilder().createQuery(Foo.class); | |
Root<Foo> rootFoo= criteriaQuery.from(Foo.class); | |
criteriaQuery.select(rootFoo); | |
return entityManager.createQuery(criteriaQuery).getResultList(); | |
} | |
@Transactional | |
public Foo create(Foo foo) | |
{ | |
validate(foo); | |
entityManager.persist(foo); | |
//entityManager.flush(); | |
return foo; | |
} | |
private void validate(Foo foo) | |
{ | |
Set<Constraintviolation<?>> errors = validator.validate(foo); | |
if (errors.size() > 0) { | |
//raise some exception like constraintViolationException | |
} | |
} | |
@Transactional | |
public Foo update(Foo foo) | |
{ | |
validate(foo); | |
entityManager.merge(foo); | |
//entityManager.flush(); | |
return foo; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment