- Cleaner than adhoc JPQL
- Not required, but focuses on the domain
- Named parameters
Обычно NamedQueries хранятся вместе с моделью которой они касаются:
А уже этими сохраненными именованными запросами пользуется репозиторий:
- Not required, but focuses on the domain
- Named parameters
@NamedQueries({ @NamedQuery(name=Goal.FIND_GOAL_REPORTS,
query="Select new com.domain.model.GoalReport(g.minutes, e.minutes, e.activity) " +
"from Goal g, Exercise e where g.id = e.goal.id"
)})
Обычно NamedQueries хранятся вместе с моделью которой они касаются:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
@Entity
@Table(name="goals")
@NamedQueries({
@NamedQuery(name=Goal.FIND_GOAL_REPORTS, query = "Select new com.domain.model.GoalReport(g.minutes, e.minutes, e.activity) " +
"from Goal g, Exercise e where g.id = e.goal.id"),
@NamedQuery(name=Goal.FIND_ALL_GOALS, query = "Select g from Goal g")
})
public class Goal {
public static final String FIND_ALL_GOALS = "findAllGoals";
public static final String FIND_GOAL_REPORTS = "findGoalReports";
@Id
@GeneratedValue
@Column(name="GOAL_ID")
private Long id;
...
А уже этими сохраненными именованными запросами пользуется репозиторий:
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import com.domain.model.Goal;
import com.domain.model.GoalReport;
@Repository("goalRepository")
public class GoalRepositoryImpl implements GoalRepository {
@PersistenceContext
private EntityManager em;
@Override
public Goal save(Goal goal) {
em.persist(goal);
em.flush();
return goal;
}
@Override
public List loadAll() {
TypedQuery query = em.createNamedQuery(Goal.FIND_ALL_GOALS, Goal.class);
return query.getResultList();
}
@Override
public List findAllGoalReports() {
TypedQuery query = em.createNamedQuery(Goal.FIND_GOAL_REPORTS, GoalReport.class);
return query.getResultList();
}
}
Таким образом у нас получается более наглядный репозиторий с более коротким, понятным описанием, что в нем происходит.
Комментариев нет:
Отправить комментарий