Spring JPA Query to get Data with Count Condition - spring

I have an Order Entity that has many Review Entities. Order has many OrderItem entities that's also has many Review Entities. So User can enter reviews for specific Order as common review or specific Order Item as item review.
Now I want to List the Orders with reviews available and Order with No reviews. For this I have to check Order || OrderItem has reviews in Reviews Table simultaneously. I think count query with Join clause to be performed. Please solve this problem.
OrderDO.java
#Table(name = "ORDER")
public class OrderDO implements Serializable{
#Column(name = "ORDER_NUMBER", nullable = false)
private String orderNumber;
#OneToMany(cascade = CascadeType.ALL, mappedBy="order")
private Set<ReviewDO> reviews = new HashSet<>();
}
OrderItemDO.java
#Table(name = "ORDER_ITEM")
public class OrderItemDO implements Serializable{
#Column(name = "PRODUCT_NAME",nullable = false)
private String name;
#OneToMany(cascade = CascadeType.ALL, mappedBy="item")
private Set<ReviewDO> reviews = new HashSet<>();
}
ReviewDO.java
#Table(name = "REVIEW")
public class ReviewDO implements Serializable {
#Column(name = "RATING")
private double rating;
#Column(name = "REVIEW_TEXT")
private String reviewText;
#ManyToOne()
#JoinColumn(name = "ITEM_ID", referencedColumnName="ID")
private OrderItemDO item;
#ManyToOne()
#JoinColumn(name = "ORDER_ID", referencedColumnName="ID")
private OrderDO order;
}
OrderRepository.java
#Repository
public interface OrderRepository extends CrudRepository<OrderDO, Long>{
#Query("select order from OrderDO order where order.orderNumber = ?1")
public Optional<OrderDO> findByOrderNumber(String orderNumber);
}

To find those reviews that are associated with orders or order-items, you can query on ReviewDO object by placing a ReviewRepository as is shown below:-
#Repository
public interface ReviewRepository extends CrudRepository<ReviewDO, Long>{
#Query(value = "SELECT r FROM ReviewDO r where r.item is not null or r.order is not null")
List<ReviewDO> findAllByOrdersOrOrderItems();
}
Please check the test case given below matching to your requirements or not
import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.raj.so.artefacts.OrderDO;
import com.raj.so.artefacts.OrderItemDO;
import com.raj.so.artefacts.OrderItemRepository;
import com.raj.so.artefacts.OrderRepository;
import com.raj.so.artefacts.ReviewDO;
import com.raj.so.artefacts.ReviewRepository;
#DataJpaTest
#RunWith(SpringRunner.class)
public class ReviewRepositoryTest {
#Autowired
private OrderRepository orderRepository;
#Autowired
private OrderItemRepository orderItemRepository;
#Autowired
private ReviewRepository reviewRepository;
#Test
public void testRepositoryFetch() {
// creating 2 orders
OrderDO orderDO1 = new OrderDO();
orderDO1.setOrderNumber("1");
orderRepository.save(orderDO1);
OrderDO orderDO2 = new OrderDO();
orderDO2.setOrderNumber("2");
orderRepository.save(orderDO2);
// creating an order item
OrderItemDO orderItemDO1 = new OrderItemDO();
orderItemDO1.setName("order item 1");
orderItemRepository.save(orderItemDO1);
// creating 2 reviews - one for order; other for item
ReviewDO reviewDO1 = new ReviewDO();
reviewDO1.setRating(5.0);
reviewDO1.setReviewText("rate five");
reviewDO1.setOrder(orderDO1);
reviewRepository.save(reviewDO1);
ReviewDO reviewDO2 = new ReviewDO();
reviewDO2.setRating(4.0);
reviewDO2.setReviewText("rate four");
reviewDO2.setItem(orderItemDO1);
reviewRepository.save(reviewDO2);
// query all reviews associated to orders or items
// returned review objects will have details about orders and items
List<ReviewDO> reviews = reviewRepository.findAllByOrdersOrOrderItems();
assertEquals(2, reviews.size());
List<String> orderNumbers = reviews.stream().map(item -> {
if (item.getOrder() != null) {
return item.getOrder().getOrderNumber();
} else {
return null;
}
})
.filter(item -> item != null)
.collect(Collectors.toList());
assertEquals("1", orderNumbers.get(0));
List<String> orderItemNames = reviews.stream().map(item -> {
if (item.getItem() != null) {
return item.getItem().getName();
} else {
return null;
}
})
.filter(item -> item != null)
.collect(Collectors.toList());
assertEquals("order item 1", orderItemNames.get(0));
}
}

Related

How to add the IDs of foreign tables to another table passing the parameters by constructor?

Hi everyone I'm working with SpringBoot and I want to send the ID's of table Producto and Cliente to Pedidos, I'm using the constructor for to pass of parametrs
I tried to create a List as String to hold the values ​​and then use it to send the data to the other method
Class Product
package com.example.demo.model;
import java.util.Set;
import javax.persistence.*;
#Entity
#Table(name = "Productos")
public class Producto {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String nombreProducto;
private String precioProducto;
/*Here i send of FK of this table to Pedidos*/
#OneToMany(mappedBy = "producto",cascade = CascadeType.ALL)
private Set<Pedido> pedidos;
public Producto(String nombreProducto, String precioProducto) {
this.nombreProducto = nombreProducto;
this.precioProducto = precioProducto;
}
//Getters and Setters
}
Class Cliente
package com.example.demo.model;
import java.util.Set;
import javax.persistence.*;
#Entity
#Table(name="Clientes")
public class Cliente {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String nombreCliente;
private String correoElectronico;
/*Here i send of FK of this table to Pedidos*/
#OneToMany(mappedBy = "cliente",cascade = CascadeType.ALL)
private Set<Pedido> pedidos;
public Cliente(String nombreCliente, String correoElectronico) {
this.nombreCliente = nombreCliente;
this.correoElectronico = correoElectronico;
}
//Getters and Setters
}
Class Pedido
package com.example.demo.model;
import javax.persistence.*;
#Entity
#Table(name = "Pedido")
public class Pedido {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String fechaPedido;
private String direccion;
/*
Here I create the atribute of FK of the tables Cliente and Producto
*/
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "cliente_id", referencedColumnName = "id")
private Cliente cliente;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "producto_id", referencedColumnName = "id")
private Producto producto;
public Pedido(String fechaPedido, String direccion, Cliente cliente, Producto producto) {
this.fechaPedido = fechaPedido;
this.direccion = direccion;
this.cliente = cliente;
this.producto = producto;
}
//Getters and Setters
}
And the last Class it's the RunnClass
package com.example.demo;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
//import java.util.stream.Stream;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import com.example.demo.model.Cliente;
import com.example.demo.model.Pedido;
import com.example.demo.model.Producto;
import com.example.demo.repository.ClienteRepository;
import com.example.demo.repository.PedidosRepository;
import com.example.demo.repository.ProductoRepositroy;
import com.github.javafaker.Faker;
#Component
public class SampleDataLoader implements CommandLineRunner {
private final ClienteRepository clienteRepository;
private final ProductoRepositroy productoRepositroy;
private final PedidosRepository pedidosRepository;
private final Faker faker; //It's a ASI of DataFaker
public SampleDataLoader(ClienteRepository clienteRepository,
ProductoRepositroy productoRepositroy,
PedidosRepository pedioPedidosRepository) {
this.clienteRepository = clienteRepository;
this.productoRepositroy = productoRepositroy;
this.pedidosRepository = pedioPedidosRepository;
this.faker = new Faker(); //It's a ASI of DataFaker
}
#Override
public void run(String... args) throws Exception {
ejecutarClases();
}
private void ejecutarClases() {
List<Cliente> clientes = IntStream.rangeClosed(1, 20)
.mapToObj(i -> new Cliente(faker.name().fullName(),
faker.internet().emailAddress()))
.collect(Collectors.toList());
clienteRepository.saveAll(clientes);
List<Producto> productos = IntStream.rangeClosed(1, 100)
.mapToObj(i -> new Producto(faker.commerce().productName(), "$"+faker.commerce().price()))
.collect(Collectors.toList());
productoRepositroy.saveAll(productos);
//I don't know how to send two ID's to this table,
//if you can see I have two values as null
//I want to send the ID's the other tables
List<Pedido> pedidos = IntStream.rangeClosed(1, 30)
.mapToObj(i -> new Pedido(faker.backToTheFuture().date(),
faker.address().streetAddress(), null, null))
.collect(Collectors.toList());
pedidosRepository.saveAll(pedidos);
}
}
I hope someone can help me please.

Get from VIEW in Spring boot

I am beginner with Spring Boot and trying to improve my skills to get new job, so I hope you help me even if the question maybe easy for you as I search a lot and gain nothing.
I need to get by id, but return data is duplicated with only one record, I will show you what I do and the result for more explanation.
In DB side:
I have VW_Prices view in DB and it's data as shown below:
In Spring Boot side:
VW_Prices class is :
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Immutable;
#Entity
#Table(name = "VW_PRICES")
public class VW_Prices implements Serializable {
private long dealId;
private Long quotationId;
private Long productPriceForEjada;
private Long productPriceForClient;
private Long productId;
private Long productQuantity;
private String productName;
#Id
#Column(name = "ID")
public long getDealId() {
return dealId;
}
public void setDealId(long dealId) {
this.dealId = dealId;
}
#Column(name = "PRODUCT_QUANTITY")
public Long getProductQuantity() {
return productQuantity;
}
public void setProductQuantity(Long productQuantity) {
this.productQuantity = productQuantity;
}
#Column(name = "PRODUCT_NAME")
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
#Column(name = "PRODUCT_PRICE_FOR_EJADA")
public Long getProductPriceForEjada() {
return productPriceForEjada;
}
public void setProductPriceForEjada(Long productPriceForEjada) {
this.productPriceForEjada = productPriceForEjada;
}
#Column(name = "PRODUCT_PRICE_FOR_CLIENT")
public Long getProductPriceForClient() {
return productPriceForClient;
}
public void setProductPriceForClient(Long productPriceForClient) {
this.productPriceForClient = productPriceForClient;
}
#Column(name = "PRODUCT_ID")
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
#Column(name = "QUOTATION_ID")
public Long getQuotationId() {
return quotationId;
}
public void setQuotationId(Long quotationId) {
this.quotationId = quotationId;
}
}
and I create VW_PricesRepository
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import springboot.deals_tracker_system.models.VW_Prices;
import springboot.deals_tracker_system.models.VW_Prices_interface;
public interface VW_PricesRepository extends JpaRepository<VW_Prices, Long> {
#Query( nativeQuery = true,value = "SELECT distinct * from VW_Prices v where v.id = :dealID " )
List<VW_Prices> findByDealId( #Param("dealID") Long id);
}
and my in my Service
public List<VW_Prices> findByDealId(Long dealId) {
System.out.println("we are in service");
List<VW_Prices> variableForDebug = VW_pricesRepository.findByDealId(dealId);
for (VW_Prices vw_Prices : variableForDebug) {
System.out.println(vw_Prices.getDealId() + " " + vw_Prices.getProductName());
}
return variableForDebug;
//return VW_pricesRepository.findByDealId(dealId);
}
When I pass dealId = 39 the result comes duplicated and not correct as in below:
how can I get correct data??
The view is made for Quotation Product Table to get product name.
i think the problem is the id annotation you must add GeneratedValue
fro the class:
#Entity
#Table(name = "VW_PRICES")
public class VW_Prices implements Serializable {
#Id
#GeneratedValue (strategy = GenerationType.IDENTITY)
private long dealId;
private Long quotationId;
private Long productPriceForEjada;
private Long productPriceForClient;
private Long productId;
private Long productQuantity;
private String productName;
//code..
}
You dont have to use JPQL for this type of queries it's already exist in jpa:
VW_PricesRepository:
public interface VW_PricesRepository extends JpaRepository<VW_Prices, Long> {
}
to get data by id use findById like that:
public VW_Prices findByDealId(Long dealId) {
System.out.println("we are in service");
VW_Prices vw_Prices = VW_pricesRepository.findById(dealId);
System.out.println(vw_Prices.getDealId() + " " +
vw_Prices.getProductName());
}
return vw_Prices;
}
All data should be deleted from VW_Prices table because ids are not unique, try to insert new data with unique id then try the above code
I detect the problem, The view has main table Quotation and I didn't select it's ID and I used ID of the secondary table as the main ID for the View
I just write it if any one Google for such problem

OneToMany bidirectional relationship JoinColumn value is null in Spring Data JPA

I have OneToMany bidirectional mapping for two entities Cart and CartProduct. Whenever we insert a Cart object with cart products, CartProduct table should fill with cart_id. Here is the problem, when I insert cart object, everything seems to be fine except, JoinColumn(card_id) which results in a null value in CartProduct table. Am I doing this right?
Cart.Java
package com.springtesting.model.cart;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.springtesting.model.AbstractAuditingEntity;
import com.springtesting.model.user.UserProfile;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#EqualsAndHashCode(callSuper = true)
#Entity
#Data
#Table(name = "cart")
public class Cart extends AbstractAuditingEntity
{
private static final long serialVersionUID = 6294902210705780249L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#OneToOne
#JoinColumn(name = "user_profile_id")
#JsonIgnoreProperties(value = {"addresses"})
private UserProfile userProfile;
#ManyToOne
#JoinColumn(name = "cart_status")
private CartStatus cartStatus;
#OneToMany(mappedBy = "cart", cascade = CascadeType.ALL,fetch = FetchType.EAGER)
//#ElementCollection(targetClass = CartProduct.class)
private List<CartProduct> cartProducts=new ArrayList<>();
}
CartProduct.Java
package com.springtesting.model.cart;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.springtesting.model.AbstractAuditingEntity;
import com.springtesting.model.product.Product;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.*;
#EqualsAndHashCode(callSuper = true)
#Entity
#Data
#Table(name = "cart_product")
public class CartProduct extends AbstractAuditingEntity
{
private static final long serialVersionUID = 6498067041321289048L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#OneToOne
#JoinColumn(name = "product_id")
private Product product;
#Column(name = "quantity")
private Integer quantity;
#ManyToOne
#JoinColumn(name = "cart_id",referencedColumnName = "id")
#JsonIgnoreProperties(value = {"userProfile","cartStatus","cartProducts"})
private Cart cart;
}
TestCase.java
#Test
public void insertCart()
{
Cart cart=new Cart();
cart.setUserProfile(userProfileRepository.findAllByUserId(1L).get());
cart.setCartStatus(cartStatusRepository.findById(1L).get());
List<CartProduct> cartProducts=new ArrayList<>();
CartProduct cartProduct=new CartProduct();
cartProduct.setProduct(productRepository.findById(1L).get());
cartProduct.setQuantity(2);
cartProducts.add(cartProduct);
cartProduct=new CartProduct();
cartProduct.setProduct(productRepository.findById(2L).get());
cartProduct.setQuantity(1);
cartProducts.add(cartProduct);
cart.setCartProducts(cartProducts);
cartRepository.saveAndFlush(cart);
}
Yes, your fix is the addition of cartProduct.setCart(cart); This is because the CartProduct is the owning entity and is the keeper of the foreignKey. The above statement sets the FK.
The way to think about this is the concept of owning entity. When you have mappedBy="cart" you are saying that the CartProduct class owns the relationship. This means that only the CartProduct class is doing the persisting. This tells JPA to create a FK in the CartProduct table. However, we notice that save is not being called on CartProduct but rather on Cart and yet cartProducts is still being saved. This is because you have the cascade = CascadeType.ALL annotation. This tells JPA to cascade certain operations when they are done to Cart, in this case the save operation.
You should have SQL statements printed and examine the differences with different configurations and test cases. This will help you understand better.
You also have FetchType.EAGER. This is generally a bad habit and usually leads to endless problems.
A good way to think about a bidirectional mapping is that the List<CartProducts> cartProducts is a query only field. In order to save a CartProduct you would call save on the cartProductRepository directly. E.g.
CartProduct cartProduct=new CartProduct();
cartProduct.setProduct(productRepository.findById(1L).get());
cartProduct.setQuantity(2);
cartProduct.setCart(cart);
cartProductRepository.save(cartProduct);
and then
cart.getCartProducts().add(cartProduct);
and remove all the cascade and eager fetch annotations. When hibernate says that you must management both sides of the relationship this is what is meant.
Doing it this way will result in one query for the save. By using a cascade annotation you will find that as you add items to the cart and call save on it the sql generated will first delete all the existing cartProducts items from the database and re-add them along with the new one every time you call save. For a cart with 10 items instead of a single save you will have a delete and 10 new saves. Definitely less desirable. If you have to reload the cart from scratch the most efficient method is to get the cart and then cart.setCartProducts(cartProductRepository.findAllByCart(cart)); which is what FetchType.EAGER is doing anyway. When you understand all this then you realize that you don't need a = new ArrayList<>(); for your cartProducts.
I think I figured out the solution. Based Hibernate docs
Whenever a bidirectional association is formed, the application
developer must make sure both sides are in-sync at all times.
So I manually added the cart object to cartProduct object, which saves cart_id in CartProduct table
CartController.java
import com.pj.springsecurity.model.cart.Cart;
import com.pj.springsecurity.model.cart.CartProduct;
import com.pj.springsecurity.repo.CartRepository;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
#RestController
#RequestMapping("/api/v1/cart")
public class CartController
{
private final CartRepository cartRepository;
public CartController(CartRepository cartRepository)
{
this.cartRepository = cartRepository;
}
#GetMapping(path = "/list")
public List<Cart> getAllCarts()
{
return cartRepository.findAll();
}
#GetMapping(path = "/find/user/{id}")
public Optional<Cart> getCartBasedOnUserId(#PathVariable Long id)
{
return cartRepository.findAllByUserProfileUserId(id);
}
#PostMapping(path = "/product/add")
public Cart addProductToCart(#RequestBody Cart cart)
{
List<CartProduct> cartProducts=cart.getCartProducts();
for(CartProduct cartProduct: cartProducts)
{
cartProduct.setCart(cart);
}
return cartRepository.saveAndFlush(cart);
}
#PutMapping(path = "/update")
public Cart updateCart(#RequestBody Cart cart)
{
return cartRepository.saveAndFlush(cart);
}
#DeleteMapping(path = "/delete")
public Cart createEmptyCart(#RequestBody Cart cart)
{
return cartRepository.saveAndFlush(cart);
}
#DeleteMapping(path = "/product/delete")
public void deleteProductFromCart(#RequestBody Cart cart)
{
List<CartProduct> cartProducts=cart.getCartProducts();
for(CartProduct cartProduct: cartProducts)
{
cartProduct.setCart(null);
}
cartRepository.delete(cart);
}
}
and Test case updated with the same
#Test
public void insertCart()
{
Cart cart=new Cart();
cart.setUserProfile(userProfileRepository.findAllByUserId(1L).get());
cart.setCartStatus(cartStatusRepository.findById(1L).get());
List<CartProduct> cartProducts=new ArrayList<>();
CartProduct cartProduct=new CartProduct();
cartProduct.setProduct(productRepository.findById(1L).get());
cartProduct.setQuantity(2);
cartProduct.setCart(cart);
cartProducts.add(cartProduct);
cartProduct=new CartProduct();
cartProduct.setProduct(productRepository.findById(2L).get());
cartProduct.setQuantity(1);
cartProduct.setCart(cart);
cartProducts.add(cartProduct);
cart.setCartProducts(cartProducts);
cartRepository.saveAndFlush(cart);
}

How to pull an alias from native query in JPA

I'm trying to pull an alias from native query in JPA, something like (SUM,COUNT), Well the method can return an integer if i pulled SUM or COUNT perfectly (ONLY if i pulled it alone) .
but how can i pull it with the rest of object? here is a sample what i am trying to do
#Entity
#Table("hotels")
public class Hotel {
#Column(name="id")
#Id
private int hotelId;
#Column(name="hotel_name")
private String hotelName;
#OneToMany
private List<Availability>list;
private int avaialbeCount; //this one should be Aliased and need to be pulled by none column
}
Repository
public interface HotelRepository extends JpaRepository<Hotel,Integer>{
#Query(value="select h.*,a.count(1) as avaialbeCount from hotels h INNER JOIN availability a on (a.hotel_id=h.hotel_id) group by a.date",nativeQuery=true)
public List<Hotel> getHotels();
}
in the above repository. im trying to get avaialbeCount with hotel columns but im unable to pull it, however i can pull it by removing the select h.* and keep select COUNT only and make the method returns Integer instead of Hotel
You can use JPQL, something like this
#Query("SELECT new test.Hotel(h.hotelName, count(h)) FROM Hotel h GROUP BY h.hotelName")
to use this new test.Hotel(h.hotelName, count(h)) construction, you need constructor like
public Hotel(String hotelName, Long avaialbeCount) {
this.hotelName = hotelName;
this.avaialbeCount = avaialbeCount;
}
Example:
Repository:
package test;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface HotelRepo extends JpaRepository<Hotel, Long> {
#Query("SELECT new test.Hotel(h.hotelName, count(h)) FROM Hotel h GROUP BY h.hotelName")
List<Hotel> getHotelsGroupByName();
}
Entity:
package test;
import javax.persistence.*;
#Entity
#Table(name = "hotels")
public class Hotel {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long hotelId;
#Column(name = "hotel_name")
private String hotelName;
#Transient
private Long avaialbeCount;
public Hotel() {
}
public Hotel(String hotelName) {
this.hotelName = hotelName;
}
public Hotel(String hotelName, Long avaialbeCount) {
this.hotelName = hotelName;
this.avaialbeCount = avaialbeCount;
}
#Override
public String toString() {
return "Hotel{" +
"hotelId=" + hotelId +
", hotelName='" + hotelName + '\'' +
", avaialbeCount=" + avaialbeCount +
'}';
}
}
#Transient annotation is used to indicate that a field is not to be persisted in the database.

SpringMVC+Hibernate : criteria.list() is returning an empty list

I am using spring MVC with Hibernate, The aim is to get the table data and store it in a list.Here the entity class being used :
package com.bng.core.entity;
// default package
// Generated Oct 25, 2015 4:38:03 PM by Hibernate Tools 3.4.0.CR1
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* servicenames generated by hbm2java
*/
#Entity
#Table(name = "servicenames")
public class ServiceNames implements java.io.Serializable {
private Integer id;
private String serviceName;
public ServiceNames() {
}
public ServiceNames(String servicename) {
this.serviceName = servicename;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "servicename", length = 25)
public String getServiceName() {
return this.serviceName;
}
public void setServiceName(String servicename) {
this.serviceName = servicename;
}
}
And the method used to get the list :
#Transactional
#Override
public List<ServiceNames> getServiceNames() {
Logger.sysLog(LogValues.APP_INFO, this.getClass().getName(), "Getting all Service names.");
Session session = sessionFactoryGlobal.openSession();
Criteria criteria = session.createCriteria(ServiceNames.class);
List<ServiceNames> serviceNamesList = criteria.list();
session.close();
return serviceNamesList;
}
When the method is called it returns an empty list. Please suggest where its going wrong ?
I think you are sure your table servicenames has data. So such problem can be when #Transactional is not working properly. Try to get list without #Transactional by open and close a transaction manually.

Resources