I am having a hard time trying to figure out how to add a one to many relationship in my database. The Book entity needs to hold many Counts. When I tried it, I got an error that says:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.counter, PID: 11949
java.lang.RuntimeException: cannot find implementation for com.example.counter.db.AppDatabase. AppDatabase_Impl does not exist
at androidx.room.Room.getGeneratedImplementation(Room.java:97)
at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:1358)
at com.example.counter.db.AppDatabase.getInstance(AppDatabase.java:18)
Here is what my AppDatabase Looks like:
package com.example.counter.db;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
#Database(entities = {Count.class, Book.class}, version = 2, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
private static AppDatabase instance;
public static AppDatabase getInstance(Context context){
if(instance != null){
return instance;
}else{
instance = Room.databaseBuilder(context, AppDatabase.class, "AppDatabase_database")
.build();
return instance;
}
}
public abstract CountDAO countDAO();
public abstract BookDAO bookDAO();
}
Count Entity:
package com.example.counter.db;
import androidx.room.Embedded;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.PrimaryKey;
import java.text.SimpleDateFormat;
import java.util.Date;
import static androidx.room.ForeignKey.CASCADE;
#Entity
public class Count {
#PrimaryKey(autoGenerate = true)
private long count_id;
private long book_id;
private String title;
private Date date;
private int total;
public Count( long book_id, String title, Date date, int total) {
this.book_id = book_id;
this.title = title;
this.date = date;
this.total = total;
}
public long getCount_id() {
return count_id;
}
public void setCount_id(long id) {
this.count_id = id;
}
public long getBook_id() {
return book_id;
}
public void setBook_id(long book_id) {
this.book_id = book_id;
}
public String getCountTitle() {
return title;
}
public void setCountTitle(String title) {
this.title = title;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
#Override
public String toString() {
return "Count{" +
"id=" + count_id +
", book_id=" + book_id +
", title='" + title + '\'' +
", date=" + date +
", total=" + total +
'}';
}
}
Book Entity:
package com.example.counter.db;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import java.util.Date;
#Entity
public class Book {
#PrimaryKey(autoGenerate = true)
private long book_id;
private String title;
private Date date;
public Book(String title, Date date) {
this.title = title;
this.date = date;
}
public long getBook_id() {
return book_id;
}
public void setBook_id(long id) {
this.book_id = id;
}
public String getBookTitle() {
return title;
}
public void setBookTitle(String title) {
this.title = title;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#Override
public String toString() {
return "Book{" +
"id=" + book_id +
", title=" + title +
", date=" + date +
'}';
}
}
BookWithCounts Entity
package com.example.counter.db;
import androidx.room.Embedded;
import androidx.room.Relation;
import java.util.List;
public class BookWithCounts {
#Embedded
public Book book;
#Relation(
parentColumn = "book_id",
entityColumn = "book_id"
)
public List<Count> counts;
public BookWithCounts(Book book, List<Count> counts){
this.book = book;
this.counts = counts;
}
}
CountDAO
package com.example.counter.db;
import androidx.room.Embedded;
import androidx.room.Relation;
import java.util.List;
public class BookWithCounts {
#Embedded
public Book book;
#Relation(
parentColumn = "book_id",
entityColumn = "book_id"
)
public List<Count> counts;
public BookWithCounts(Book book, List<Count> counts){
this.book = book;
this.counts = counts;
}
}
BookDAO
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Transaction;
import androidx.room.Update;
import java.util.List;
#Dao
public interface BookDAO {
#Query("select * from Book")
LiveData<List<Book>> getAllBooks();
#Query("select * from Book where book_id=:id")
List<Book> getBookByID(long id);
#Query("select title from Book")
LiveData<List<String>> getAllBookTitles();
#Insert
long insertBook(Book book);
#Insert
long insertCount(Count count);
#Update
void updateBook(Book book);
#Delete
void deleteBook(Book book);
}
BooksWithCountsDAO
package com.example.counter.db;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.Transaction;
import java.util.List;
#Dao
public interface BookWithCountsDAO {
#Transaction
#Insert
long insertBook(Book book);
#Insert
void insertCounts(List<Count> counts);
}
I also have View Models for both Books and Counts that I use to fill a recycler view. However, I get the error when I try and view the recycler view.
[Update] I figured out the issue. It was a combination of things. First I didn't have the annotation processor dependency. These are the dependencies you need.
def room_version = "2.3.0"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
I also had issues with using a type Date with no date converter. I didn't want to mess with the date converter. So I simply just changed the type to a string. After I was able to get it working.
Related
So, I'm making an order project, I'm able to create products(id, created_at, deleted, price_in_euros, product_name), and with those products create orders. When I create an order, the products I chose to it become a cartItem(id, amount, productName, product_id, product_name, quantity, order_id). To make this clear, everytime I make an order I create a shoppingCartItem for each product I choose to order. This will saturate my db since if I want to make 2 orders with 30 products each, I'm making 60 different cartItems.
I need to find a way to use a cartItem for different orders if the amount is the same, because 4 cartItems, for example, can be the same product, but with different amounts.
My CloudProduct.java
package com.proj.my.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import java.sql.Date;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.Table;
import jakarta.validation.constraints.Pattern;
#Entity
#Table(name="cloud_product_info")
#SQLDelete(sql = "UPDATE cloud_product_info SET deleted = true WHERE product_id=?")
#Where(clause = "deleted=false")
//#FilterDef(name="", parameters = #ParamDef(name="isDeleted", type = "boolean"))
//#Filter(name="deletedBookFilter", condition = "deleted = :isDeleted")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"createdAt", "updatedAt"},
allowGetters = true)
public class CloudProduct {
public static Integer id;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer productId;
#Column(unique=true)
private String productName;
private Float priceInEuros;
#CreationTimestamp
#Column(updatable = false, name = "created_at")
private Date createdAt;
private Boolean deleted = Boolean.FALSE;
#JsonIgnore
public Boolean getdeleted() {
return deleted;
}
#JsonIgnore
public void setdeleted(Boolean deleted) {
this.deleted = deleted;
}
public CloudProduct(Integer productId, String productName, Float priceInEuros) {
this.productId = productId;
this.productName = productName;
this.priceInEuros = priceInEuros;
}
public CloudProduct() {
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Float getpriceInEuros() {
return priceInEuros;
}
public void setProductPrice(Float priceInEuros) {
this.priceInEuros = priceInEuros;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
#Override
public String toString() {
return "Product{" +
"id=" + productId +
", name='" + productName + '\'' +
", price=" + priceInEuros +
'}';
}
}
My Order.java
package com.proj.my.model;
import java.time.LocalDate;
import java.util.List;
import org.hibernate.annotations.CreationTimestamp;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OneToOne;
import jakarta.persistence.Table;
import lombok.ToString;
#ToString
#Entity
#Table(name = "myorder")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"createdAt"},
allowGetters = true)
public class Order {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#OneToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "userId")
private User user;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, targetEntity = ShoppingCart.class)
#JoinColumn(name = "order_id")
private List<ShoppingCart> cartItems;
#CreationTimestamp
#Column(updatable = false, name = "createdAt")
private LocalDate createdAt;
public LocalDate getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDate createdAt) {
this.createdAt = createdAt;
}
public Order() {
}
public Order(User user, LocalDate createdAt, List<ShoppingCart> cartItems) {
this.user = user;
this.cartItems = cartItems;
this.createdAt = createdAt;
}
public Order(int Id, LocalDate createdAt, List<ShoppingCart> cartItems) {
this.cartItems = cartItems;
this.createdAt = createdAt;
this.id = Id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setCustomer(User user) {
this.user = user;
}
public List<ShoppingCart> getCartItems() {
return cartItems;
}
public void setCartItems(List<ShoppingCart> cartItems) {
this.cartItems = cartItems;
}
}
My shoppingCart.java
package com.proj.my.model;
import org.hibernate.annotations.NotFound;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
/*#Data
#AllArgsConstructor
#RequiredArgsConstructor
#NoArgsConstructor
*/
#Entity
public class ShoppingCart {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private Integer productId;
private String productName;
private int quantity;
private float amount;
public ShoppingCart() {
}
public ShoppingCart(Integer productId, String productName, int quantity, float amount) {
this.productId = productId;
this.productName = productName;
this.quantity = quantity;
this.amount = amount;
}
public ShoppingCart(Integer productId, int quantity) {
this.productId = productId;
this.quantity = quantity;
}
public ShoppingCart(String productName, int quantity) {
this.productName = productName;
this.quantity = quantity;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
#Override
public String toString() {
return "ShoppingCart{" +
"id=" + id +
", productId=" + productId +
", productName='" + productName + '\'' +
", quantity=" + quantity +
", amount=" + amount +
'}';
}
}
My orderService.java
package com.proj.my.service;
import com.proj.my.model.Order;
import com.proj.my.model.CloudProduct;
import com.proj.my.model.ShoppingCart;
import com.proj.my.repository.OrderRepository;
import com.proj.my.repository.CloudProductRepository;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
#Service
public class OrderService {
private OrderRepository orderRepository;
private CloudProductRepository cloudProductRepository;
public OrderService(OrderRepository orderRepository, CloudProductRepository cloudProductRepository) {
this.orderRepository = orderRepository;
this.cloudProductRepository = cloudProductRepository;
}
public Order getOrderDetail(int orderId) {
Optional<Order> order = this.orderRepository.findById(orderId);
return order.isPresent() ? order.get() : null;
}
public List<Order> getAllOrderDetail(LocalDate dataaa) {
return orderRepository.findAllByCreatedAt(dataaa);
}
public float getCartAmount(List<ShoppingCart> shoppingCartList) {
float totalCartAmount = 0f;
float singleCartAmount = 0f;
for (ShoppingCart cart : shoppingCartList) {
String cloudProductName = cart.getProductName();
Optional<CloudProduct> product = cloudProductRepository.findByProductName(cloudProductName);
if (product.isPresent()) {
CloudProduct cloudproduct = product.get();
singleCartAmount = cart.getQuantity() * cloudproduct.getpriceInEuros();
totalCartAmount = totalCartAmount + singleCartAmount;
cart.setProductId(cloudproduct.getProductId());
cart.setAmount(singleCartAmount);
cloudProductRepository.save(cloudproduct);
}
}
return totalCartAmount;
}
public Order saveOrder(Order order) {
return orderRepository.save(order);
}
}
My orderController.java
package com.proj.my.controller;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.proj.my.dto.OrderDTO;
import com.proj.my.dto.ResponseOrderDTO;
import com.proj.my.model.CloudProduct;
import com.proj.my.model.Order;
import com.proj.my.model.ShoppingCart;
import com.proj.my.model.User;
import com.proj.my.repository.CloudProductRepository;
import com.proj.my.service.CloudProductService;
import com.proj.my.service.OrderService;
import com.proj.my.service.UserService;
#RestController
#RequestMapping("/api")
public class OrderController {
private OrderService orderService;
private CloudProductService cloudProductService;
private UserService userService;
#Autowired
private CloudProductRepository cloudProductRepository;
public OrderController(OrderService orderService, CloudProductService cloudProductService, UserService userService) {
this.orderService = orderService;
this.cloudProductService = cloudProductService;
this.userService = userService;
}
#GetMapping(value = "/getOrder/{orderId}")
public ResponseEntity<Order> getOrderDetails(#PathVariable int orderId) {
Order order = orderService.getOrderDetail(orderId);
return ResponseEntity.ok(order);
}
#GetMapping(value = "/getOrders/{dataaa}")
public List<Order> getAllOrderDetails(#PathVariable LocalDate dataaa) {
return orderService.getAllOrderDetail(dataaa);
}
#PostMapping("/placeOrder")
public ResponseEntity<?> placeOrder(#RequestBody OrderDTO orderDTO) {
ResponseOrderDTO responseOrderDTO = new ResponseOrderDTO();
List<ShoppingCart> shoppingCartList = orderDTO.getCartItems();
ShoppingCart shoppingCart;
for (ShoppingCart cart : shoppingCartList) {
String cloudProductName = cart.getProductName();
Optional<CloudProduct> product = cloudProductRepository.findByProductName(cloudProductName);
if (product.isPresent()){
float amount = orderService.getCartAmount(orderDTO.getCartItems());
if(amount > 0){
User user = new User(orderDTO.getuserEmail());
Integer userIdFromDb = userService.isUserPresent(user);
if (userIdFromDb != null) {
user.setUserId(userIdFromDb);
}else{
user = userService.createUser(user);
}
LocalDate createdAt = LocalDate.now();
Order order = new Order(user, createdAt, orderDTO.getCartItems());
order = orderService.saveOrder(order);
responseOrderDTO.setAmount(amount);
responseOrderDTO.setDate(com.proj.my.util.DateUtil.getCurrentDateTime());
responseOrderDTO.setOrderId(order.getId());
return ResponseEntity.ok(responseOrderDTO);
}
else{
return new ResponseEntity<>("Can't create an order without products.", HttpStatus.OK);
}
}
else{
return new ResponseEntity<>("No Product with such name found.", HttpStatus.OK);
}
}
return null;
}}
Let me know if you need the rest of the services and, or controllers of the other 2 entities.
How can I do this ?
I'm trying to retrieve a list of just the orders created from one day ago till today, and I can't manage to find any help about it, tried everything I found already.
Basically I need a getAllOrders(), but with filtered by that time period, one day....
How do I filter it ? I Found tons of tutorials on how to sort them descending or ascending, nothing else.
My order.java:
package com.proj.my.model;
import java.time.LocalDate;
import java.util.List;
import org.hibernate.annotations.CreationTimestamp;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OneToOne;
import jakarta.persistence.Table;
import lombok.ToString;
#ToString
#Entity
#Table(name = "myorder")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"createdAt"},
allowGetters = true)
public class Order {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#OneToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "userId")
private User user;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, targetEntity = ShoppingCart.class)
#JoinColumn(name = "order_id")
private List<ShoppingCart> cartItems;
#CreationTimestamp
#Column(updatable = false, name = "createdAt")
private LocalDate createdAt;
public LocalDate getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDate createdAt) {
this.createdAt = createdAt;
}
public Order() {
}
public Order(User user, LocalDate createdAt, List<ShoppingCart> cartItems) {
this.user = user;
this.cartItems = cartItems;
this.createdAt = createdAt;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setCustomer(User user) {
this.user = user;
}
public List<ShoppingCart> getCartItems() {
return cartItems;
}
public void setCartItems(List<ShoppingCart> cartItems) {
this.cartItems = cartItems;
}
}
My orderservice.java
package com.proj.my.service;
import com.proj.my.model.Order;
import com.proj.my.model.CloudProduct;
import com.proj.my.model.ShoppingCart;
import com.proj.my.repository.OrderRepository;
import com.proj.my.repository.CloudProductRepository;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
#Service
public class OrderService {
private OrderRepository orderRepository;
private CloudProductRepository cloudProductRepository;
public OrderService(OrderRepository orderRepository, CloudProductRepository cloudProductRepository) {
this.orderRepository = orderRepository;
this.cloudProductRepository = cloudProductRepository;
}
public Order getOrderDetail(int orderId) {
Optional<Order> order = this.orderRepository.findById(orderId);
return order.isPresent() ? order.get() : null;
}
/* #Query(value = "from order t where Date BETWEEN :yesterday AND :now")
public List<Order> getAllBetweenDates(#Param("yesterday")Date yesterday,#Param("now")Date localdate.now){
private LocalDate yesterday = now.minus(1, ChronoUnit.DAYS);
return orderRepository.findAll();
} */
public List<Order> getAllOrderDetail() {
return orderRepository.findAll();
}
public float getCartAmount(List<ShoppingCart> shoppingCartList) {
float totalCartAmount = 0f;
float singleCartAmount = 0f;
for (ShoppingCart cart : shoppingCartList) {
String cloudProductName = cart.getProductName();
Optional<CloudProduct> product = cloudProductRepository.findByProductName(cloudProductName);
if (product.isPresent()) {
CloudProduct cloudproduct = product.get();
singleCartAmount = cart.getQuantity() * cloudproduct.getpriceInEuros();
totalCartAmount = totalCartAmount + singleCartAmount;
cart.setProductId(cloudproduct.getProductId());
cart.setAmount(singleCartAmount);
cloudProductRepository.save(cloudproduct);
}
}
return totalCartAmount;
}
public Order saveOrder(Order order) {
return orderRepository.save(order);
}
}
My orderDTO.java
package com.proj.my.dto;
import com.proj.my.model.ShoppingCart;
import java.util.List;
public class OrderDTO {
private List<ShoppingCart> cartItems;
private String userEmail;
private String userName;
public OrderDTO() {
}
public OrderDTO(List<ShoppingCart> cartItems, String userEmail, String userName) {
this.cartItems = cartItems;
this.userEmail = userEmail;
this.userName = userName;
}
public List<ShoppingCart> getCartItems() {
return cartItems;
}
public void setCartItems(List<ShoppingCart> cartItems) {
this.cartItems = cartItems;
}
public String getuserEmail() {
return userEmail;
}
public void setuserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getuserName() {
return userName;
}
public void setuserName(String userName) {
this.userName = userName;
}
#Override
public String toString() {
return "OrderDTO{" +
", cartItems=" + cartItems +
", userEmail='" + userEmail + '\'' +
", userName='" + userName + '\'' +
'}';
}
}
My shoppingcart.java
package com.proj.my.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
/*#Data
#AllArgsConstructor
#RequiredArgsConstructor
#NoArgsConstructor
*/
#Entity
public class ShoppingCart {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private Integer productId;
private String productName;
private int quantity;
private float amount;
public ShoppingCart() {
}
public ShoppingCart(Integer productId, String productName, int quantity, float amount) {
this.productId = productId;
this.productName = productName;
this.quantity = quantity;
this.amount = amount;
}
public ShoppingCart(Integer productId, int quantity) {
this.productId = productId;
this.quantity = quantity;
}
public ShoppingCart(String productName, int quantity) {
this.productName = productName;
this.quantity = quantity;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
#Override
public String toString() {
return "ShoppingCart{" +
"id=" + id +
", productId=" + productId +
", productName='" + productName + '\'' +
", quantity=" + quantity +
", amount=" + amount +
'}';
}
}
And finally my orderController.java
package com.proj.my.controller;
import java.time.LocalDate;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.proj.my.dto.OrderDTO;
import com.proj.my.dto.ResponseOrderDTO;
import com.proj.my.model.Order;
import com.proj.my.model.User;
import com.proj.my.service.CloudProductService;
import com.proj.my.service.OrderService;
import com.proj.my.service.UserService;
#RestController
#RequestMapping("/api")
public class OrderController {
private OrderService orderService;
private CloudProductService cloudProductService;
private UserService userService;
public OrderController(OrderService orderService, CloudProductService cloudProductService, UserService userService) {
this.orderService = orderService;
this.cloudProductService = cloudProductService;
this.userService = userService;
}
#GetMapping(value = "/getOrder/{orderId}")
public ResponseEntity<Order> getOrderDetails(#PathVariable int orderId) {
Order order = orderService.getOrderDetail(orderId);
return ResponseEntity.ok(order);
}
#GetMapping(value = "/getOrder")
public List<Order> getAllOrderDetails() {
return orderService.getAllOrderDetail();
}
#PostMapping("/placeOrder")
public ResponseEntity<ResponseOrderDTO> placeOrder(#RequestBody OrderDTO orderDTO) {
ResponseOrderDTO responseOrderDTO = new ResponseOrderDTO();
float amount = orderService.getCartAmount(orderDTO.getCartItems());
User user = new User(orderDTO.getuserName(), orderDTO.getuserEmail());
Integer userIdFromDb = userService.isUserPresent(user);
if (userIdFromDb != null) {
user.setUserId(userIdFromDb);
}else{
user = userService.createUser(user);
}
LocalDate createdAt = LocalDate.now();
Order order = new Order(user, createdAt, orderDTO.getCartItems());
order = orderService.saveOrder(order);
responseOrderDTO.setAmount(amount);
responseOrderDTO.setDate(com.proj.my.util.DateUtil.getCurrentDateTime());
responseOrderDTO.setOrderId(order.getId());
return ResponseEntity.ok(responseOrderDTO);
}}
You can add method in OrderRepository interface
public List<Order> findByCreatedAtBetween(LocalDate d1, LocalDate d2)
and call it
orderRepository.findByCreatedAtBetween(today.minusDays(1),today);
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.details
Working on location based rest api and so far everything is working fine except for one controller with bring this error
2022-03-16 16:28:37.842 WARN 7720 --- [nio-8080-exec-5] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.Producttracking.dto.MetadataDto]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Conflicting setter definitions for property "x": org.postgis.Point#setX(double) vs org.postgis.Point#setX(int)
2022-03-16 16:28:37.847 WARN 7720 --- [nio-8080-exec-5] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.Producttracking.dto.MetadataDto]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Conflicting setter definitions for property "x": org.postgis.Point#setX(double) vs org.postgis.Point#setX(int)
here is the metadata entitty
package com.example.Producttracking.entity;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.n52.jackson.datatype.jts.GeometryDeserializer;
import org.n52.jackson.datatype.jts.GeometrySerializer;
import org.postgis.Point;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalTime;
#Entity
#Table
public class Metadata implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
private Long meta_id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "emp_id", referencedColumnName = "emp_id")
private Employee employee;
private LocalDate date;
private LocalTime time;
#JsonSerialize(using = GeometrySerializer.class)
#JsonDeserialize(contentUsing = GeometryDeserializer.class)
private Point location;
public Metadata() {
}
public Metadata(Long meta_id, Employee employee, LocalDate date, LocalTime time, Point location) {
this.meta_id = meta_id;
this.employee = employee;
this.date = date;
this.time = time;
this.location = location;
}
public Metadata(Employee employee, LocalDate date, LocalTime time, Point location) {
this.employee = employee;
this.date = date;
this.time = time;
this.location = location;
}
public Long getMeta_id() {
return meta_id;
}
public void setMeta_id(Long meta_id) {
this.meta_id = meta_id;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public LocalTime getTime() {
return time;
}
public void setTime(LocalTime time) {
this.time = time;
}
public Point getLocation() {
return location;
}
public void setLocation(Point location) {
this.location = location;
}
#Override
public String toString() {
return "Metadata{" +
"meta_id=" + meta_id +
", employee=" + employee +
", date=" + date +
", time=" + time +
", location=" + location +
'}';
}
}
here is the the dto
package com.example.Producttracking.dto;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
import org.n52.jackson.datatype.jts.GeometryDeserializer;
import org.n52.jackson.datatype.jts.GeometrySerializer;
import org.postgis.Point;
import java.time.LocalDate;
import java.time.LocalTime;
#Data
public class MetadataDto {
private Long emp_id;
private LocalDate date;
private LocalTime time;
#JsonSerialize(using = GeometrySerializer.class)
#JsonDeserialize(contentUsing = GeometryDeserializer.class)
private Point location;
}
here is the controller
package com.example.Producttracking.controller;
import com.example.Producttracking.dto.MetadataDto;
import com.example.Producttracking.entity.Metadata;
import com.example.Producttracking.services.MetadataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
#RequestMapping(path = "api/v1/metadata")
public class MetadataController {
private final MetadataService metadataService;
#Autowired
public MetadataController(MetadataService metadataService) {
this.metadataService = metadataService;
}
#GetMapping
public List<Metadata> getMetadata(){
return metadataService.getMetadata();
}
#PostMapping
public void registerMetadata (#RequestBody MetadataDto metadataDto){
metadataService.registerMetadata(metadataDto);
}
}
and here is the service
package com.example.Producttracking.services;
import com.example.Producttracking.dto.MetadataDto;
import com.example.Producttracking.entity.Metadata;
import com.example.Producttracking.repository.MetadataRepository;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
#Service
public class MetadataService {
private final MetadataRepository metadataRepository;
private final ModelMapper modelMapper;
#Autowired
public MetadataService(MetadataRepository metadataRepository, ModelMapper modelMapper) {
this.metadataRepository = metadataRepository;
this.modelMapper = modelMapper;
}
public List<Metadata> getMetadata() {
return metadataRepository.findAll();
}
public void registerMetadata(MetadataDto metadataDto) {
Metadata metadata = modelMapper.map(metadataDto,Metadata.class);
Optional<Metadata> metadataOptional = metadataRepository.findById(metadata.getMeta_id());
if (metadataOptional.isPresent()){
throw new IllegalStateException("metadata exist");
}
metadataRepository.save(metadata);
}
}
I'm just learning Spring Boot and doing a small project I got stuck with. I have a many to many relationship between Students and Courses, there is a table in the middle called enrollment for this relationship which takes the student_id and course_id as the primary key. I am creating an API for the above-mentioned. I have next
Class Student
Class Enrollment
Class Course
Class StudentRepository
Class StudentJPAResource
Class Student
package com.myapis.rest.webservices.restfulwebservicesedgar01.student;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import com.myapis.rest.webservices.restfulwebservicesedgar01.enrollment.Enrollment;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
#Entity
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "STUD_SEQ")
#SequenceGenerator(sequenceName = "student_id_seq", allocationSize = 1, name = "STUD_SEQ")
private Integer studentId;
#Size(min=2, message="Name should have at least two chars")
private String firstName;
private String lastName;
#OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
#JsonIgnore
private List<Enrollment> enrollments = new ArrayList<>();
#Past
private Date birthDate;
public Student() {}
public Student(Integer studentId, String firstName, String lastName, Date birthDate) {
super();
this.studentId = studentId;
this.firstName = firstName;
this.birthDate = birthDate;
}
public Integer getId() {
return studentId;
}
public void setId(Integer id) {
this.studentId = studentId;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setfirstName(String firstName) {
this.firstName = firstName;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public List<Enrollment> getEnrollments() {
return enrollments;
}
#Override
public String toString() {
return "Student [studentId=" + studentId + ", firstName=" + firstName + ", lastName=" + lastName + ", payments="
+ payments + ", birthDate=" + birthDate + "]";
}
}
Class Enrollment
package com.myapis.rest.webservices.restfulwebservicesedgar01.enrollment;
import java.util.Date;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MapsId;
import javax.persistence.Table;
import com.myapis.rest.webservices.restfulwebservicesedgar01.course.Course;
import com.myapis.rest.webservices.restfulwebservicesedgar01.student.Student;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity(name="Enrollment")
#Table(name="enrollments")
public class Enrollment {
#EmbeddedId
private EnrollmentId id;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("studentId")
#JoinColumn(name="student_id")
#JsonIgnore
private Student student;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("courseId")
#JoinColumn(name="course_id")
#JsonIgnore
private Course course;
#Column(name="enrollment_id")
private Integer enrollmentId;
#Column(name="date_enrollment")
private Date enrollmentDate;
public Enrollment() {}
public Enrollment(Student student, Course course, Integer enrollmentId, Date enrollmentDate) {
super();
this.id = new EnrollmentId(student.getId(), course.getId());
this.student = student;
this.course = course;
this.enrollmentId = enrollmentId;
this.enrollmentDate = enrollmentDate;
}
public EnrollmentId getId() {
return id;
}
public void setId(EnrollmentId id) {
this.id = id;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public Integer getEnrollmentId() {
return enrollmentId;
}
public void setEnrollmentId(Integer enrollmentId) {
this.enrollmentId = enrollmentId;
}
public Date getEnrollmentDate() {
return enrollmentDate;
}
public void setEnrollmentDate(Date enrollmentDate) {
this.enrollmentDate = enrollmentDate;
}
#Override
public String toString() {
return "Enrollment [id=" + id + ", student=" + student + ", course=" + course + ", enrollmentId=" + enrollmentId
+ ", enrollmentDate=" + enrollmentDate + "]";
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
Enrollment that = (Enrollment) o;
return Objects.equals(student, that.student) &&
Objects.equals(course, that.course);
}
#Override
public int hashCode() {
return Objects.hash(student, course);
}
}
Class Course
package com.myapis.rest.webservices.restfulwebservicesedgar01.course;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import com.myapis.rest.webservices.restfulwebservicesedgar01.enrollment.Enrollment;
import com.myapis.rest.webservices.restfulwebservicesedgar01.student.Student;
#Entity
public class Course {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "COURSE_SEQ")
#SequenceGenerator(sequenceName = "course_id_seq", allocationSize = 1, name = "COURSE_SEQ")
private Integer courseId;
private String courseName;
private String description;
#OneToMany(mappedBy = "course", cascade = CascadeType.ALL)
private List<Enrollment> enrollments = new ArrayList<>();
public Course() {}
public Course(Integer courseId, String courseName, String description) {
super();
this.courseId = courseId;
this.courseName = courseName;
this.description = description;
}
public Integer getId() {
return courseId;
}
public Integer getCourseId() {
return courseId;
}
public void setCourseId(Integer courseId) {
this.courseId = courseId;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Course [courseId=" + courseId + ", courseName=" + courseName + ", description=" + description + "]";
}
}
Class Enrollment
package com.myapis.rest.webservices.restfulwebservicesedgar01.enrollment;
import java.util.Date;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MapsId;
import javax.persistence.Table;
import com.myapis.rest.webservices.restfulwebservicesedgar01.course.Course;
import com.myapis.rest.webservices.restfulwebservicesedgar01.student.Student;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity(name="Enrollment")
#Table(name="enrollments")
public class Enrollment {
#EmbeddedId
private EnrollmentId id;
#ManyToOne(fetch = FetchType.EAGER)
#MapsId("studentId")
#JoinColumn(name="student_id")
#JsonIgnore
private Student student;
#ManyToOne(fetch = FetchType.EAGER)
#MapsId("courseId")
#JoinColumn(name="course_id")
#JsonIgnore
private Course course;
#Column(name="enrollment_id")
private Integer enrollmentId;
#Column(name="date_enrollment")
private Date enrollmentDate;
public Enrollment() {}
public Enrollment(Student student, Course course, Integer enrollmentId, Date enrollmentDate) {
super();
this.id = new EnrollmentId(student.getId(), course.getId());
this.student = student;
this.course = course;
this.enrollmentId = enrollmentId;
this.enrollmentDate = enrollmentDate;
}
public EnrollmentId getId() {
return id;
}
public void setId(EnrollmentId id) {
this.id = id;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public Integer getEnrollmentId() {
return enrollmentId;
}
public void setEnrollmentId(Integer enrollmentId) {
this.enrollmentId = enrollmentId;
}
public Date getEnrollmentDate() {
return enrollmentDate;
}
public void setEnrollmentDate(Date enrollmentDate) {
this.enrollmentDate = enrollmentDate;
}
#Override
public String toString() {
return "Enrollment [id=" + id + ", student=" + student + ", course=" + course + ", enrollmentId=" + enrollmentId
+ ", enrollmentDate=" + enrollmentDate + "]";
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
Enrollment that = (Enrollment) o;
return Objects.equals(student, that.student) &&
Objects.equals(course, that.course);
}
#Override
public int hashCode() {
return Objects.hash(student, course);
}
}
Class StudentRepository
package com.edgarapis.rest.webservices.restfulwebservicesedgar01.student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface StudentRepository extends JpaRepository<Student, Integer>{
}
Class StudentJPAResource
package com.myapis.rest.webservices.restfulwebservicesedgar01.student;
import java.net.URI;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.myapis.rest.webservices.restfulwebservicesedgar01.payment.Payment;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.MapperFeature;
import com.myapis.rest.webservices.restfulwebservicesedgar01.enrollment.Enrollment;
#RestController
public class StudentJPAResource {
#Autowired
private StudentRepository studentRepository;
//retrieve all students
#GetMapping("/jpa/students")
public List<Student> retrieveAllStudents() {
return studentRepository.findAll();
}
//retrieve one user by id from studentRepository
#GetMapping("/jpa/students/{id}")
public EntityModel<Optional<Student>> retriveStudent(#PathVariable int id) {
Optional<Student> student = studentRepository.findById(id);
if(!student.isPresent()) {
throw new StudentNotFoundException("id - " + id);
}
//"all-students", SERVER_PATH + "/students"
//RetrieveAllStudents
EntityModel<Optional<Student>> resource = EntityModel.of(student);
//From the library WebMvcLinkBuilder
WebMvcLinkBuilder linkTo = WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(this.getClass()).retrieveAllStudents());
resource.add(linkTo.withRel("all-students"));
return resource;
}
//deleting one user by id
#DeleteMapping("/jpa/students/{id}")
public void deleteStudent(#PathVariable int id) {
studentRepository.deleteById(id);
}
//Save one user to the persistence layer
#PostMapping("/jpa/students")
public ResponseEntity<Object> createStudent(#Valid #RequestBody Student student) {
Student savedStudent = studentRepository.save(student);
// /user/{id} -- Response back indicating the user creation was good
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedStudent.getId()).toUri();
return ResponseEntity.created(location).build();
}
//All courses that one specific student is enrolled
#GetMapping("/jpa/students/{id}/enrollments")
public List<Enrollment> retrieveOneStudentCourses(#PathVariable int id) {
Optional<Student> studentOptional = studentRepository.findById(id);
if(!studentOptional.isPresent()) {
throw new StudentNotFoundException("id - " + id);
}
return studentOptional.get().getEnrollments();
}
//All Students with their courses
#GetMapping("/jpa/students/enrollments")
public List<Student> retrieveAllStudentsCourses() {
// How to implement???
}
}
In the class StudentJPAResource, method retrieveOneStudentCourses, I created this method to retrieve the courses of a specific student. I want to create a method to retrieve all the students and the courses that they are enrolled retrieveAllStudentsCourses().
NOTE
Currently, in the class student, I have the notation #JsonIgnore for Enrollment because when I use retrieveAllStudents() the students come up with their enrollments so, this notation prevents this, otherwise, the students will come up with the enrollments (that is actually what I want to do, but using a different method).
Thank you for your help, beforehand.
I have two table Parent table is Credit in that table only one row of data is there and another one is child table Debit that contains multiple row of data. how to fetch data from two table which has to match id of parent class and child class and no duplicate is shown from parent class.
I have try with (from Credit,debit) but that can display with duplicate and not properly data is shown based on id.
package com.rojmat.entity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.core.annotation.Order;
#Entity
#Table(name="credit")
public class Credit extends BaseEntity{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long cid;
#Column #Order
private long openingbalance;
#Column
private Date date;
#Column #Order
private long debittotal;
#Column #Order
private long drawertotal;
#Column #Order
private long debittotalplusdrawertotal;
#Column #Order
private long todaybusiness;
#OneToMany(cascade={CascadeType.ALL})
#JoinTable(name="credit_debit",
joinColumns=#JoinColumn(name="c_id"),
inverseJoinColumns=#JoinColumn(name="d_id"))
/*#JoinColumn(name="cid", referencedColumnName="cid")*/
private List<Debit> debits = new ArrayList<Debit>(Arrays.asList());
public Credit() {
}
public Credit(long cid, long openingbalance, Date date, long debittotal, long drawertotal,
long debittotalplusdrawertotal, long todaybusiness, List<Debit> debits) {
super();
this.cid = cid;
this.openingbalance = openingbalance;
this.date = date;
this.debittotal = debittotal;
this.drawertotal = drawertotal;
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
this.todaybusiness = todaybusiness;
this.debits = debits;
}
public long getCid() {
return cid;
}
public void setCid(long cid) {
this.cid = cid;
}
public long getOpeningbalance() {
return openingbalance;
}
public void setOpeningbalance(long openingbalance) {
this.openingbalance = openingbalance;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public long getDebittotal() {
return debittotal;
}
public void setDebittotal(long debittotal) {
this.debittotal = debittotal;
}
public long getDrawertotal() {
return drawertotal;
}
public void setDrawertotal(long drawertotal) {
this.drawertotal = drawertotal;
}
public long getDebittotalplusdrawertotal() {
return debittotalplusdrawertotal;
}
public void setDebittotalplusdrawertotal(long debittotalplusdrawertotal) {
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
}
public long getTodaybusiness() {
return todaybusiness;
}
public void setTodaybusiness(long todaybusiness) {
this.todaybusiness = todaybusiness;
}
public List<Debit> getDebit() {
return debits;
}
public void setDebit(List<Debit> debit) {
this.debits = debits;
}
/*#Override
public String toString() {
return "Credit [cid=" + cid + ", openingbalance =" + openingbalance + ", date=" + date + ", debittotal= " + debittotal + ", debittotalplusdrawertotal=" + debittotalplusdrawertotal + ", todaybusiness=" + todaybusiness + "]";
}*/
}
package com.rojmat.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="debit")
public class Debit {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long did;
#Column
private String amount;
#Column
private String description;
public Debit() {
}
public Debit(String amount, String description) {
super();
this.amount = amount;
this.description = description;
}
public long getDid() {
return did;
}
public void setDid(long did) {
this.did = did;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Debit [did=" + did + ", amount =" + amount + ", description=" + description + "]";
}
}
1.CreditDaoImpl.java
package com.rojmat.daoImpl;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.rojmat.dao.CreditDao;
import com.rojmat.entity.Credit;
#Repository
public class CreditDaoImpl implements CreditDao{
#Autowired
private SessionFactory sessionFactory;
#Override
public void addCreditDebit(Credit credit) {
try {
sessionFactory.getCurrentSession().saveOrUpdate(credit);
} catch(Exception e) {
e.printStackTrace();
}
}
#Override
public void deleteCreditDebit(int cid) {
/*Credit credit = (Credit)sessionFactory.getCurrentSession().createQuery("from Credit as c LEFT JOIN FETCH c.Debit where c.cid="+cid).uniqueResult();
List<Debit> debits = credit.getDebit();
sessionFactory.getCurrentSession().delete(credit);
debits.forEach((debit) -> {
sessionFactory.getCurrentSession().delete(debit);
});*/
}
#SuppressWarnings("unchecked")
#Override
public List<Credit> getAllCreditDebit() {
List<Credit> credit = sessionFactory.getCurrentSession().createQuery("from Credit,Debit").list();
return credit;
}
}
try this example: you put "distinct" before the property you do not want to be duplicated
//SQL query
select distinct credit.idCredit as idCredit from Credit credit Left Join Debit debit on credit.idCredit= debit.idCredit
//HQL query
#Entity(name = "Credit")
#Table(name = "Credit")
public class Credit{
//if you put #Id --> HQL Query "select credit from Credit credit"
#Column(name = "idCredit")
private Long idCredit;
#Column(name = "label")
private String label;
#OneToMany
#JoinColumns({#JoinColumn(name = "idCredit" ,referencedColumnName = "idCredit")})
List<Debit> debits;
...
}
public class Debit{
....
#Column(name = "idCredit")
private Long idCredit;
...
}
Query query = getSession().createQuery("select distinct credit.idCredit as idCredit, credit.label as label, credit.debits as debits from Credit credit ");
query.setResultTransformer(Transformers.aliasToBean(Credit.class));
return query.list();
package com.rojmat.entity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.core.annotation.Order;
#Entity
#Table(name="credit")
public class Credit extends BaseEntity{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long cid;
#Column #Order
private long openingbalance;
#Column
private Date date;
#Column #Order
private long debittotal;
#Column #Order
private long drawertotal;
#Column #Order
private long debittotalplusdrawertotal;
#Column #Order
private long todaybusiness;
#OneToMany(cascade={CascadeType.ALL})
#JoinTable(name="credit_debit",
joinColumns=#JoinColumn(name="c_id"),
inverseJoinColumns=#JoinColumn(name="d_id"))
/*#JoinColumn(name="cid", referencedColumnName="cid")*/
private List<Debit> debits = new ArrayList<Debit>(Arrays.asList());
public Credit() {
}
public Credit(long cid, long openingbalance, Date date, long debittotal, long drawertotal,
long debittotalplusdrawertotal, long todaybusiness, List<Debit> debits) {
super();
this.cid = cid;
this.openingbalance = openingbalance;
this.date = date;
this.debittotal = debittotal;
this.drawertotal = drawertotal;
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
this.todaybusiness = todaybusiness;
this.debits = debits;
}
public long getCid() {
return cid;
}
public void setCid(long cid) {
this.cid = cid;
}
public long getOpeningbalance() {
return openingbalance;
}
public void setOpeningbalance(long openingbalance) {
this.openingbalance = openingbalance;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public long getDebittotal() {
return debittotal;
}
public void setDebittotal(long debittotal) {
this.debittotal = debittotal;
}
public long getDrawertotal() {
return drawertotal;
}
public void setDrawertotal(long drawertotal) {
this.drawertotal = drawertotal;
}
public long getDebittotalplusdrawertotal() {
return debittotalplusdrawertotal;
}
public void setDebittotalplusdrawertotal(long debittotalplusdrawertotal) {
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
}
public long getTodaybusiness() {
return todaybusiness;
}
public void setTodaybusiness(long todaybusiness) {
this.todaybusiness = todaybusiness;
}
public List<Debit> getDebit() {
return debits;
}
public void setDebit(List<Debit> debit) {
this.debits = debits;
}
/*#Override
public String toString() {
return "Credit [cid=" + cid + ", openingbalance =" + openingbalance + ", date=" + date + ", debittotal= " + debittotal + ", debittotalplusdrawertotal=" + debittotalplusdrawertotal + ", todaybusiness=" + todaybusiness + "]";
}*/
}
package com.rojmat.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="debit")
public class Debit {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long did;
#Column
private String amount;
#Column
private String description;
public Debit() {
}
public Debit(String amount, String description) {
super();
this.amount = amount;
this.description = description;
}
public long getDid() {
return did;
}
public void setDid(long did) {
this.did = did;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/*#Override
public String toString() {
return "Debit [did=" + did + ", amount =" + amount + ", description=" + description + "]";
}*/
}