How To Query Relationship Between Three Entities in Spring JPA - java

I am working on my senior project and my group's client has required that we use Spring Boot, which none of us are familiar with. Right now I'm working on making a paginated, sortable list that will show a logged in user the visits that are associated with their user id. Our models are as follows:
#Entity
#Table(name="users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#JsonView(View.User.class)
private long id;
#Column(name = "full_name")
#NotNull
#JsonView(View.User.class)
private String fullName;
#Column(name = "is_manager")
#NotNull
private boolean isManager;
#ManyToMany(cascade = CascadeType.ALL, mappedBy = "users")
private Set<Visit> visits;
#OneToMany(cascade=CascadeType.ALL, mappedBy="user")
private Set<VisitEntry> visitEntries;
-
#Entity
#Table(name="visits")
public class Visit implements Iterable<VisitEntry> {
static final public String INSPECTION_TYPE_FULL = "Full Inspection";
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#JsonView(View.Visit.class)
private long id;
#Column(name = "visit_number")
#NotNull
#JsonView(View.Visit.class)
private int visitNumber;
#ManyToOne(cascade=CascadeType.ALL)
#NotNull
#JsonView(View.Visit.class)
private Provider provider;
#ManyToOne(cascade=CascadeType.ALL)
private User leader;
#ManyToMany(cascade = {CascadeType.ALL})
#JoinTable(name="users_visits",
joinColumns={#JoinColumn(name="VISIT_ID")},
inverseJoinColumns = #JoinColumn(name = "USER_ID")
)
private Set<User> users;
#OneToMany(cascade=CascadeType.ALL, mappedBy="visit")
#JsonView(View.Visit.class)
#JsonManagedReference
private List<VisitEntry> visitEntries = new ArrayList<>();
#Column(name = "open")
#NotNull
private boolean open;
-
#Entity
#Table(name="visit_entries")
public class VisitEntry {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#JsonView(View.Visit.class)
private long id;
#Column(name = "pre_inspection")
#JsonView(View.Visit.class)
private int preInspectionPrepHours;
#ManyToOne(cascade = CascadeType.ALL)
#NotNull
#JsonBackReference
private Visit visit;
#ManyToOne(cascade=CascadeType.ALL)
#NotNull
#JsonView(View.Visit.class)
private User user;
So we have visits which have many visit entries and each visit entry has a user. What I need is to get all visits associated with a user.
Unfortunately after each reading various tutorials my teammates and I are incredibly confused and have entirely different ideas on how to do this, none of which have actually worked. Based on this question (Joining two table entities in Spring Data JPA) I created the relationship between visits and users thinking that I would then be able to use Page<Visit> findByUsers(User user, Pageable pageable); in my repository, but I always get an empty set. So now we've ended up with this ugly piece of code that works as far as paginating but does not do any sorting:
#RequestMapping(value="/visits/{pageNum}/{sort}/{direction}", method= RequestMethod.GET)
public String visits(#PathVariable int pageNum,
#PathVariable String sort,
#PathVariable String direction,
Model model,
HttpServletRequest request) {
User currentUser = getUser(request);
final int pageSize = 10;
Pageable pageable;
//get direction info from parameters and convert to Sort.Direction enum
if (direction.compareTo("asc") == 0)
pageable = new PageRequest(pageNum - 1, pageSize, Sort.Direction.ASC, sort);
else
pageable = new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, sort);
//get pageable list of visits dependant on current user
Page<Visit> visits;
if(currentUser.isManager()) {
visits = visitRepo.findAll(pageable);
}
else {
//visits = visitRepo.findByUser_Id(currentUser, pageable);
List<VisitEntry> entries = visitEntryDao.findByUser(currentUser);
List<Visit> visitList = new ArrayList<>();
for (int x = 0; x < entries.size(); x++) {
visitList.add(entries.get(x).getVisit());
}
int offset = (pageNum - 1) * pageSize;
int offsetEnd = offset + 10;
if (offsetEnd > visitList.size())
offsetEnd = visitList.size();
List<Visit> content = visitList.subList(offset, offsetEnd);
visits = new PageImpl<Visit>(content, pageable, visitList.size());
}
edu.ewu.timetrackers.util.Page[] pages = new edu.ewu.timetrackers.util.Page[visits.getTotalPages()];
for (int i = 0; i < visits.getTotalPages(); i++) {
pages[i] = new edu.ewu.timetrackers.util.Page(i + 1, pageNum == i + 1);
}
//add visit and number of pages to model
model.addAttribute("visits", visits);
model.addAttribute("pageCount", visits.getTotalPages());
//add sorting and paging info to model
model.addAttribute("pageNum", pageNum);
model.addAttribute("sort", sort);
model.addAttribute("direction", direction);
model.addAttribute("pages", pages);
//below attributes determine previous and next buttons for pagination
if (pageNum > 1)
model.addAttribute("notFirst", pageNum - 1);
if (pageNum < visits.getTotalPages())
model.addAttribute("notLast", pageNum + 1);
return "visits";
}
Can anyone clear up the correct way to do this? We've tried asking around and not found anyone in our community that uses Spring that can help us understand what we're missing here.
Thanks!

Related

#ManyToMany duplicate entries

I have a problem with persisting. I have a Meal class in which is a list of Products. In Product class is a list of Meals -- #ManyToMany relation.
When I try to save it Compiler want to save every product, but then products are duplicated in my DB.
How I can indicate that the products are already there?
Here is my code
#Entity
public class Meal {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#JsonManagedReference
#ManyToMany(cascade = {
CascadeType.MERGE
})
private List<Product> foodList = new ArrayList<>();
#NaturalId
#Column(unique = true, nullable = false)
private String mealName;
private Integer servingWeightGrams = 0;
private Integer servingQty = 0;
private Double nfCalories = 0d;
private Double nfTotalFat = 0d;
...
#Entity
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#JsonBackReference
#ManyToMany(mappedBy = "foodList")
private List<Meal> meals = new ArrayList<>();
#Column(unique = false, nullable = false)
private String foodName;
...
#Service
public class MealManager {
MealService mealService;
ProductService productService;
#Autowired
public MealManager(MealService mealService, ProductService productService)
{
this.mealService = mealService;
this.productService = productService;
}
public Meal saveMeal(List<Food> foodList, String mealName){
Meal newMeal = new Meal();
newMeal.setMealName(mealName);
List<Product> productList = parseFoodToProduct(foodList);
productList.stream().forEach(y -> newMeal.getFoodList().add(y));
for(Product food : productList) {
newMeal.setNfCalories(newMeal.getNfCalories() + food.getNfCalories());
newMeal.setNfCholesterol(newMeal.getNfCholesterol() + food.getNfCholesterol());
newMeal.setNfDietaryFiber(newMeal.getNfDietaryFiber() + food.getNfDietaryFiber());
newMeal.setNfP(newMeal.getNfP() + food.getNfP());
newMeal.setNfPotassium(newMeal.getNfPotassium() + food.getNfPotassium());
newMeal.setNfProtein(newMeal.getNfProtein() + food.getNfProtein());
newMeal.setNfSaturatedFat(newMeal.getNfSaturatedFat() + food.getNfSaturatedFat());
newMeal.setNfSodium(newMeal.getNfSodium() + food.getNfSodium());
newMeal.setNfSugars(newMeal.getNfSugars() + food.getNfSugars());
newMeal.setNfTotalCarbohydrate(newMeal.getNfTotalCarbohydrate() + food.getNfTotalCarbohydrate());
newMeal.setNfTotalFat(newMeal.getNfTotalFat() + food.getNfTotalFat());
newMeal.setServingWeightGrams(newMeal.getServingWeightGrams() + food.getServingWeightGrams());
/*if(! productService.ifExists(food.getFoodName())) */ productService.save(food);
}
return mealService.save(newMeal);
}
You probably don't need to invoke productService.save(food) at the end of your for loop in MealManager.
You can try adding some utility methods in the Meal class, to keep the relationship in sync, as described in this article.
So, in your Meal class, you can add a method like
public void addProduct(Product product) {
foodList.add(product);
product.getMeals().add(this);
}
and call this method inside the for loop in MealManager, instead of simply calling newMeal.getFoodList().add(y).
Because you have CascadeType.MERGE defined for ManyToMany, the relationship will then be synchronized in both entities.
Other observations:
I can't see what the parseFoodToProduct method is doing, but assuming it retrieves the necessary products from the db, you should mark the saveMeal method as #Transactional
you're looping 2 times through the productList in saveMeal... once with stream().forEach() and once with the enhanced for... I'd keep only the enhanced for in this context

Vaadin 8 Grid does not work with too many entries

I created a Vaadin Grid to show some entities, and this worked fine I used a data dataprovider from callback. Now i added 6800000 Entries in the database and grid table is not scrollable anymore, first i tried 1200000 entries and it still worked. I don't understand that because the grid only loads a few entities and not all at ones.
The dataprovider:
this.defaultDataProv = DataProvider.fromCallbacks((query) -> {
// sorting defaults
String sort = "sortId";
Sort.Direction d = Sort.DEFAULT_DIRECTION;
if (!query.getSortOrders().isEmpty()) {
// parsing vaadin sort to spring.hibernate sort
d = (query.getSortOrders().get(0).getDirection() == SortDirection.ASCENDING) ? Sort.Direction.ASC : Sort.Direction.DESC;
sort = query.getSortOrders().get(0).getSorted();
}
Iterable<Article> findAll = this.arService.findAll(query.getOffset(), query.getLimit(), new Sort(d, sort));
return StreamSupport.stream(findAll.spliterator(), true);
}, query -> {
return this.arService.cntArticle();
});
The grid:
private Grid<Article> articleGrid;
this.articleGrid = new Grid<>("Artikel");
this.articleGrid.setSelectionMode(Grid.SelectionMode.SINGLE);
this.articleGrid.setDataProvider(this.defaultDataProv);
Grid.Column<Article, String> nameColumn = this.articleGrid.addColumn(Article::getName).setCaption("Name").setId("name");
this.articleGrid.addColumn(Article::getEan).setCaption("EAN").setId("ean");
this.articleGrid.addColumn(Article::getSortId).setCaption("Sortid").setId("sortId");
// addColum for stocks
this.articleGrid.addColumn((a) -> {
return a.getStocks().size();
}).setCaption("Bestände");
articleGrid.addColumn(Article::getCompleteCntStock).setCaption("Zählbestand");
articleGrid.addColumn(Article::getCompleteOldStock).setCaption("Istbestand");
super.addComponent(this.articleGrid);
super.addComponent(this.searchLayout);
super.addComponent(this.filterLayout);
super.addComponent(this.editLayout);
super.setSizeFull();
this.articleGrid.setHeight(500f, Unit.PIXELS);
this.articleGrid.setWidth(1000f, Unit.PIXELS);
The entity i try to show:
#Entity
#Indexed
#Getter
#Setter
public class Article implements Serializable {
private static final long serialVersionUID = -1812015490640296522L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(nullable = false, unique = true)
#Field(index = Index.YES)
private Long id;
#Field(index = Index.YES)
#Column(nullable = true, unique = true)
private Long sortId;
#Field(index = Index.YES)
#Column(nullable = true, unique = true)
private Long ean;
#Column(nullable = false, unique = false)
private String name;
private String descr;
#Column(nullable = false)
#OneToMany(mappedBy = "article", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#ContainedIn
private List<Stock> stocks;
/**
* Instances the {#link #stocks} with an empty list.
*/
public Article() {
stocks = new ArrayList<>();
}
/**
* #return all Stocks summed up.
*/
public int getCompleteCntStock() {
int re = 0;
for (Stock stock : stocks) {
re += stock.getCntStock();
}
return re;
}
/**
*
* #return all old Stocks summed up.
*/
public int getCompleteOldStock() {
int re = 0;
for (Stock stock : stocks) {
re += stock.getOldStock();
}
return re;
}
}
This is the grid table but it is not scrollable.
Thanks for your help.
The amount of the rows in Grid is limited by maximum size of the scroll bar Div element. This is different depending on the browser. For example with default row height you can have some ~880K rows in Chrome, 235K rows in Firefox and 40K rows in IE11.
There is more information here: https://github.com/vaadin/framework/issues/6290
This limitation applies to Vaadin 7 & 8
In Vaadin Flow (v. 10 and later), Grid is totally re-done and its implementation does not have this limitation.

Hibernate complex data retrieval?

I have nine related tables in my database.i have to retrieve records after filtering user request.
My Entities follows ,
Movie
#Entity
#Table(name = "movie")
public class Movie implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "movie_id")
private int movieId;
#Column(name = "category_id")
private Integer categoryId;
#Column(name = "movie_title")
private String movieTitle;
#Column(name = "movie_description", columnDefinition = "TEXT")
private String movieDescription;
#Column(name = "movie_summary", columnDefinition = "TEXT")
private String movieSummary;
private Integer status;
#Column(name = "language_id")
private Integer languageId;
#Column(name = "banner_image_url")
private String bannerImageUrl;
#Column(name = "imdb_rating")
private Integer imdbRating;
#Column(name = "rotten_tomatoes_rating")
private Integer rottenTomatoesRating;
#Column(name = "user_avg_rating")
private Float userAvgRating;
#Column(name = "main_genre_id")
private Integer mainGenreId;
#Column(name = "secondary_genre_id")
private Integer secondaryGenreId;
#Column(name = "created_by_user_id")
private Integer createdByUserId;
}
Category
#Entity
#Table(name = "category")
public class FetchSubCategory implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "category_id")
private Integer categoryId;
#Column(name = "category_name")
private String categoryName;
}
MovieActorMapping
#Entity
#Table(name = "movie_actor_mapping")
public class MovieActorMapping implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "mapping_id")
private int mappingId;
#Column(name = "movie_id")
private Integer movieId;
#Column(name = "actor_id")
private Integer actorId;
}
MovieActors
#Entity
#Table(name = "movie_actors")
public class MovieActors implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "actor_id")
private int actorId;
#Column(name = "actor_name")
private String actorName;
}
MovieGenre
#Entity
#Table(name = "movie_genre")
public class MovieGenre implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "genre_id")
private int genreId;
#Column(name = "genre_name")
private String genreName;
#Column(name = "created_by_user_id")
private Integer createdByUserId;
}
MovieLanguage
#Entity
#Table(name = "movie_language")
public class MovieLanguage implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "language_id")
private int languageId;
#Column(name = "language_name")
private String languageName;
#Column(name = "created_by_user_id")
private Integer createdByUserId;
#Column(name = "last_updated_user_id")
private Integer lastUpdatedUserId;
}
The user will request like below .all are optional fields ,
{
"subCategory":"New Release",
"language":"Malayalam",
"actor":"allu arjun",
"filmGenre":"'Family'"
}
According to the request i will return the movie list by checking conditions from corresponding table using subquery.
Method
public List<Movie> getFilterMovieList(FilterMovieRequest filterMovieRequest) throws SQLException, ClassNotFoundException, IOException {
List<Movie> movies = null;
try {
String subCategory = filterMovieRequest.getSubCategory();
String language = filterMovieRequest.getLanguage();
String actor = filterMovieRequest.getActor();
String filmGenre = filterMovieRequest.getFilmGenre();
String contained = "where";
String sql = "from Movie as M ";
if (actor.length() > 1) {
sql += contained + " movieId in(select movieId from MovieActorMapping where actorId in(select actorId from MovieActors where actorName='" + actor + "')) ";
contained = "and";
}
if (subCategory.length() > 1) {
sql += contained + " M.categoryId=(select categoryId from FetchSubCategory where categoryName='" + subCategory + "') ";
contained = "and";
}
if (language.length() > 1) {
sql += contained + " M.languageId=(select languageId from MovieLanguage where languageName='" + language + "') ";
contained = "and";
}
if (filmGenre.length() > 1) {
sql += contained + " (M.mainGenreId in(select genreId from MovieGenre where genreName in(" + filmGenre + ")) or M.secondaryGenreId in(select genreId from MovieGenre where genreName in(" + filmGenre + ")))";
contained = "and";
}
if (contained.equals("and")) {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery(sql);
movies = query.list();
}
} catch (Exception e) {
e.printStackTrace();
}
return movies;
}
And it works fine.the problem is now i have to combine with the result in which theaters movies is playing and the show time also.
And my theater related tables follow,
theater_movie_mapping
theater_list
show_timings
you can see in column movie_id in theater_movie_mapping which related to my base table movie. using that we can fetch theater_id and show_id for fetch the theaters and show timing..note that i have a movie list early fetched after checking above conditions.How can i combine theaters from theater_list and show times from show_timings ? being an android developer it seems complex for me.Am totally stucked. Any help will be appreciated.Am using Spring restful webservice.
Now i have getting the result in following format,
[
{
"movieId": 8,
"categoryId": 14,
"movieTitle": "Kanyaka Talkies",
"movieDescription": "CRITICS 3 out of 5 (Good) 3 out of 5 (Good) The composite emotional weather that the film sports makes it maddening and nurturing at once, rendering it an almost enigmatic feel. And it is this ethereal complexity that 'Kanyaka Talkies' inherently has, that makes the film singular. ",
"movieSummary": "The concurrence of the three key characters in 'Kanyaka Talkies' isn't of the traditionalist kind; rather, by throwing the three of them together, the film does achieve the ostensibly improbable feat of placing the unlikeliest of players collectively on board, with their fates irrevocably intertwined with each other. ",
"status": 1,
"languageId": 1,
"bannerImageUrl": "0",
"imdbRating": 1,
"rottenTomatoesRating": 3,
"userAvgRating": 2,
"mainGenreId": 1,
"secondaryGenreId": 2,
"createdByUserId": 16
},
{
"movieId": 9,
"categoryId": 14,
"movieTitle": "Wonderful Journey",
"movieDescription": "Wonderful Journey' is one of the most misdirecting titles as yet for a film this year. Anything but wonderful, this is an absolute cinematic misadventure that will have you pulling out your hair strands in no time. ",
"movieSummary": "Some things in life simply cannot be averted, they say. I do agree, what with the late night show of 'Wonderful Journey' getting cancelled yesterday night and me courageously venturing out for it yet again today noon, only to embark on one of the most horrendous journeys I have ever gone for in my entire life. ",
"status": 1,
"languageId": 1,
"bannerImageUrl": "0",
"imdbRating": 1,
"rottenTomatoesRating": 3,
"userAvgRating": 2,
"mainGenreId": 1,
"secondaryGenreId": 1,
"createdByUserId": 16
},
{
"movieId": 10,
"categoryId": 14,
"movieTitle": "Oru New Generation Pani",
"movieDescription": "Very occasionally does a movie come along that almost makes you vow to stay off the screens for a few weeks, and this year, the one has finally arrived. I'd gladly go ahead with a no-star rating for this one, had it not been for a technical glitch that prevents me from doing so! ",
"movieSummary": "'Oru New Generation Pani' is an atrocity that shocks you with its attempt to spin out a story line that will have you banging you head against the rails. Inauthentic to the core, the film tells a story that will have an insomniac snoring away in no time. ",
"status": 1,
"languageId": 1,
"bannerImageUrl": "0",
"imdbRating": 1,
"rottenTomatoesRating": 3,
"userAvgRating": 2,
"mainGenreId": 1,
"secondaryGenreId": 2,
"createdByUserId": 16
}
]
I have to add the theaters and show time too in every json object ie ,every movie..
Assume theater_movie_mapping is mapped to Class TheaterMovie which contains Movie movie in it
ArrayList<TheaterMovie> list = new ArrayList<TheaterMovie>();
for(int i = 0 ; i < movies.size() ; i++){
list.addAll((ArrayList<TheaterMovie>)createQuery("From TheaterMovie tm where tm.movies = :mo").setParameter("mo",movies.get(i)).getList());
}
Now assume show_timings is mapped to Class ShowTiming which contains Theater theater in it
ArrayList<ShowTiming> showTimeList = new ArrayList<ShowTiming>();
for(int i = 0 ; i < list.size() ; i++){
showTimeList = (ArrayList<ShowTiming>)createQuery("From ShowTiming st where st.theater = :th").setParameter("th",list.get(i).getTheater()).getList();
}
I hope this works well for you

How to handle org.hibernate.ObjectNotFoundException

I am working on a Spring mvc app in which I am using Trip model and TripStop model. Trip model has list of trip stop models. Following is my Trip model:
#Entity
#Table(name = "Trip")
public class TripModel {
#Id
#Column(name = "tripid")
#GeneratedValue
private int tripId;
#Column(name = "tripname")
private String tripName;
#Column(name = "tripdesc")
private String tripDesc;
#Column(name = "createdate")
private Date createDate;
#OneToMany(mappedBy = "tripModel", fetch = FetchType.EAGER)
#Fetch(value = FetchMode.SUBSELECT)
private List<TripStopModel> tripStopList;
}
Following is my trip stop model:
#Entity
#Table(name="TripStop")
public class TripStopModel {
#Id
#Column(name="tripstopid")
#GeneratedValue
private int tripStopId;
#Column(name="datetime")
private String tripStopDateTime;
#Column(name="createts")
private Date tripStopCreateTime;
#ManyToOne(optional=true)
#JoinColumn(name="locationid")
private LocationModel locationModel;
public LocationModel getLocationModel() {
return locationModel;
}
public void setLocationModel(LocationModel locationModel) {
this.locationModel = locationModel;
}
#ManyToOne(optional=true)
#JoinColumn(name="userid")
private UserModel userModel;
#ManyToOne(optional=true)
#JoinColumn(name="tripid")
private TripModel tripModel;
}
This works fine. But when trip id is 0 in TripStop table, it shows following exception:
02:32:43,784 ERROR [stderr] (http--0.0.0.0-8080-5) org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.example.scm.model.TripModel#0]
Is there any option with which we can used trip id = 0 in TripStop table, without any exception? How can I allow this?
The tripID is defaulting to 0 because you are using primitives. Switch to primitive wrappers so these values can default to null and this should solve it

Ljava.lang.Object; cannot be cast when getting multipile fields Hibernate Repository

I fresh on spring technology and hibernate. Some days ago i create query getting all rows from table using repository. Today i was try get 2 fields from database. When i try read data form result list i getting Ljava.lang.Object; cannot be cast. This is my enity
#Entity
#Table(name = "cms")
public class Cms implements Serializable{
private static final long serialVersionUID = 1759832392332242809L;
#Id
#GeneratedValue
private Long id_page;
#Column(nullable = false)
private String title;
private String content;
#Temporal(TemporalType.DATE)
private Date createDate;
#Temporal(TemporalType.DATE)
private Date modifyDate;
#Column(nullable = true)
private int createBy;
#Column(nullable = true)
private int modifedBy;
#Column(nullable = false)
private Boolean inMenu;
public Cms(Long id_page, String title, String content, Date createDate,
Date modifyDate) {
this.id_page = id_page;
this.title = title;
this.content = content;
this.createDate = createDate;
this.modifyDate = modifyDate;
this.createBy = 1;
this.modifedBy = 1;
this.inMenu = true;
}
//getters setters to string
}
Repository
public interface CmsRepository extends Repository<Cms, Long>{
#Query("Select u.id_page,u.title from Cms u")
List<Cms> getMenu();
}
And takie this on controller
List<Cms> menus= cmsservice.menuAll();
System.out.println(menus.get(0).toString()); //error
Some one can explain me on example what is bad and how can fix this, this will helpfull for me.
Thats because you are retrieving individual properties - not the entire Cms Object.
I would use an instance of Query for this:
EntityManager em = emf.createEntityManager();
Query query = em.createQuery("Select u.id_page,u.title from Cms u");
List<Object[]> results = query.getResultList();
for(Object[] elements: results){
Long id = Long.valueOf(String.valueOf(elements[0]));
String title = String.valueOf(elements[1]);
}
SELECT NEW org.agoncal.javaee7.CustomerDTO(c.firstName, c.lastName, c.address.
street1)
FROM Customer c

Categories

Resources