Is it possible to fetch Data from 3 tables in hibernate where the controller is of a different model.
codeAModel.Java
#Entity
#Table(name="demo")
//#NamedQuery(name="Demo.findAll", query="SELECT m FROM Demo m")
public class AModel implements Serializable {
#Column(name="demo_loc")
private String location;
#Column(name="name")
private String name;
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
BModel.Java
#Entity
#Table(name="location")
//#NamedQuery(name="City.findAll", query="SELECT c FROM City c")
public class BModel implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="locationNoid")
private int locationNoId;
#Column(name="Code")
private int Code;
public int getLocationNoId() {
return locationNoId;
}
public void setLocationNoId(int locationNoId) {
this.locationNoId = locationNoId;
}
public int getCode() {
return Code;
}
public void setCode(int code) {
Code = code;
}
}
CModel.java
#Entity
#Table(name="offers")
public class CModel implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int OfferShopid;
#Column(name="offerCount")
private int offerCount;
#Column(name="foodCount")
private int foodCount;
public int getOfferShopid() {
return OfferShopid;
}
public void setOfferShopid(int offerShopid) {
OfferShopid = offerShopid;
}
public int getOfferCount() {
return offerCount;
}
public void setOfferCount(int offerCount) {
this.offerCount = offerCount;
}
public int getFoodCount() {
return foodCount;
}
public void setFoodCount(int foodCount) {
this.foodCount = foodCount;
}
}
DemoDTO.java
public class LocationDTO {
private int demoId;
private String name;
private int Code;
private int foodCount;
public int getDemoId() {
return demoId;
}
public void setDemoId(int demoId) {
this.demoId = demoId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCode() {
return Code;
}
public void setCode(int code) {
Code = code;
}
public int getFoodCount() {
return foodCount;
}
public void setFoodCount(int foodCount) {
this.foodCount = foodCount;
}
}
DemoController.java
#RestController
#RequestMapping("/api/abcService")
#Api(description = "REST API to list details")
public class DemoController {
#Autowired
private DemoService DemoService;
#RequestMapping(value = "/list/v1/{user_id}/uid/{locationNoId}/location",
method = RequestMethod.GET)
#ResponseBody
#ApiOperation(value = "Get all Lists", notes = "Get all Address related
information")
public ResponseEntity<?> getAll(#PathVariable("user_id") int userId,
#PathVariable("locationNoId") int locationNoId)
{
try {
ModelMapper modelMapper = new ModelMapper();
Type listType = new TypeToken<List<DemoDTO>>() {
}.getType();
List<DemoDTO> listAll=DemoService.ListAll(userId,locationNoId);
return new ResponseEntity<>(listAll, HttpStatus.OK);
}catch (Exception ex){
String errorMessage;
errorMessage = ex.getMessage();
return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
}
}
}
DemoDAOImpl
#Component
#Repository
#Transactional
public class DemoDAOImpl implements DemoDAO {
#PersistenceContext
private EntityManager entityManager;
#Autowired
private AService aService;
AModel aModel;
#Override
public #ResponseBody List<DemoDTO> ListAll(int User_id, int locationNoId) {
// TODO Auto-generated method stub
List<DemoDTO> listDemo=new ArrayList<>();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<AModel> query =
criteriaBuilder.createQuery(AModel.class); Root<AModel> root =
query.from(AModel.class); query.select(root); CriteriaQuery<AModel>
select = query.select(root); TypedQuery<AModel> typedQuery =
entityManager.createQuery(select); List<AModel> AllLists =
typedQuery.getResultList();
for(AModel listofAll :AllLists ) {
System.out.println(listofAll.getid());
System.out.println(listofAll.getname());
System.out.println(listofAll.getlocation());
System.out.println(listofAll.getid());
System.out.println(listofAll.getRating());
listMalls.(AllLists);
return listMalls;
}
Base DemoController you have already a DemoService that you can reuse between other controlers. So if you have
#RestController
#RequestMapping("/api/abcServiceA")
public class DemoControllerA {
#Autowired
private DemoServiceA demoServiceA;
#RestController
#RequestMapping("/api/abcServiceB")
public class DemoControllerB {
#Autowired
private DemoServiceB demoServiceB;
You can create controler:
#RestController
#RequestMapping("/api/abcServiceB")
public class DemoControllerD {
#Autowired
private DemoServiceA demoServiceA;
#Autowired
private DemoServiceB demoServiceB;
Use this two services in one method:
#RequestMapping(value = "/list/v1/{user_id}/uid/{locationNoId}/location",method = RequestMethod.GET)
#ResponseBody
#ApiOperation(value = "Get all Lists", notes = "Get all Address related information")
public ResponseEntity<?>getAll(#PathVariable("user_id")int userId,
#PathVariable("locationNoId")int locationNoId) {
try {
ModelMapper modelMapper = new ModelMapper();
Type listType = new TypeToken<List<DemoDTO>>() {}.getType();
List<DemoDTO> listAllFromA = aemoServiceA.ListAll(userId, locationNoId);
List<DemoDTO> listAllFromB = aemoServiceB.ListAll(userId, locationNoId);
// do something with listAllFromA and listAllFromB
return new ResponseEntity<>(listAll, HttpStatus.OK);
} catch (Exception ex) {
String errorMessage;
errorMessage = ex.getMessage();
return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
}
}
Related
I have a problem with my API #query reponse in SpringBoot.
First I will show u my code:
#RestController
#RequestMapping("/api/osoba")
public class APIController {
#Autowired
private KsiazkaRepo ksiazkaRepo;
#JsonView(OnlyName.class)
#RequestMapping(method = RequestMethod.POST, value = "/getAll")
public Ksiazka find(#RequestParam("id") int id){
String autor = ksiazkaRepo.findInfoById(id);
Ksiazka ksiazka = new Ksiazka();
ksiazka.setAutor(autor);
return ksiazka;
}
**#Repository
public interface KsiazkaRepo extends JpaRepository<Ksiazka, Integer> {
#Query(value = "SELECT ksiazka.tytul, ksiazka.autor FROM IEci8d0gZc.ksiazka WHERE ksiazka.id_ksiazka = :id", nativeQuery = true)
String findInfoById(#Param("id") int id);
}**
#Entity
#Validated
public class Ksiazka {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idKsiazka;
private int idKategoria;
private String isbn;
#JsonView(OnlyName.class)
private String tytul;
#JsonView(OnlyName.class)
private String autor;
private int stron;
private String wydawnictwo;
private int rokWydania;
private String opis;
public Ksiazka(){ }
public Ksiazka(int idKsiazka, int idKategoria, String isbn, String tytul, String autor, int stron, String wydawnictwo, int rokWydania, String opis) {
this.idKsiazka = idKsiazka;
this.idKategoria = idKategoria;
this.isbn = isbn;
this.tytul = tytul;
this.autor = autor;
this.stron = stron;
this.wydawnictwo = wydawnictwo;
this.rokWydania = rokWydania;
this.opis = opis;
}
public int getIdKsiazka() {
return idKsiazka;
}
public void setIdKsiazka(int idKsiazka) {
this.idKsiazka = idKsiazka;
}
public int getIdKategoria() {
return idKategoria;
}
public void setIdKategoria(int idKategoria) {
this.idKategoria = idKategoria;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getTytul() {
return tytul;
}
public void setTytul(String tytul) {
this.tytul = tytul;
}
public String getAutor() {
return autor;
}
public void setAutor(String autor) {
this.autor = autor;
}
public int getStron() {
return stron;
}
public void setStron(int stron) {
this.stron = stron;
}
public String getWydawnictwo() {
return wydawnictwo;
}
public void setWydawnictwo(String wydawnictwo) {
this.wydawnictwo = wydawnictwo;
}
public int getRokWydania() {
return rokWydania;
}
public void setRokWydania(int rokWydania) {
this.rokWydania = rokWydania;
}
public String getOpis() {
return opis;
}
public void setOpis(String opis) {
this.opis = opis;
}
And my interface OnlyName is empty.
When I'm using it like that like it is right not I can get simple response
Like:
{
"tytul": null,
"autor": "Mistrz czystego kodu. Kodeks postępowania profesjonalnych programistów,Robert C. Martin"
}
I understand that my response from #query is in String and that's why I'm getting only one result, but How should I change to get all String or something like that? Maybe String[]?
I can also create 2 different custom asking #query and get from them
1. imie,
2. nazwisko,
but this should not be the case.
Many thanks for help,
Ciao
UPDATE
Follow the steps here
In here, I am trying to tell you how to do this simply
Change the query , It should return list
#Query(value = "SELECT ksiazka.tytul, ksiazka.autor FROM IEci8d0gZc.ksiazka WHERE ksiazka.id_ksiazka = :id", nativeQuery = true)
List<String> findInfoById(#Param("id") int id); // here you can return result as list
Change the return type in "public Ksiazka find" as list
#RestController
#RequestMapping("/api/osoba")
public class APIController {
#Autowired
private KsiazkaRepo ksiazkaRepo;
#JsonView(OnlyName.class)
#RequestMapping(method = RequestMethod.POST, value = "/getAll")
public List<Ksiazka> find(#RequestParam("id") int id){
}
Inside body try to do get result as list ,
#RestController
#RequestMapping("/api/osoba")
public class APIController {
#Autowired
private KsiazkaRepo ksiazkaRepo;
#JsonView(OnlyName.class)
#RequestMapping(method = RequestMethod.POST, value = "/getAll")
public List<Ksiazka> find(#RequestParam("id") int id){
List<String> autor = ksiazkaRepo.findInfoById(id); // get result as as list
List<Ksiazka> ksiazkaList = new ArrayList<>(); // create list from Ksiazka
for (String autors : autor) { // returned result you can loop
Ksiazka ksiazka = new Ksiazka(); // create Object to Ksiazka
ksiazka.setAutor(autors);
ksiazkaList.add(ksiazka); //add created object to List
}
return ksiazkaList; // return your list
}
I created spring boot project where I am making rest application. I have used My SQL database and I am using spring data. There is one method which adds orders based on customer id. So I am not able to figure out it will work based on spring data query or custom query and how it will be?
I have attached required codes only,
Customer.java
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "customers")
#NamedQuery(name = "Customer.findAll", query = "SELECT c FROM Customer c")
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "cust_ID_PK")
#GeneratedValue(strategy = GenerationType.AUTO)
private int custIDPK;
#Column(name = "billing_city")
private String billingCity;
#Column(name = "billing_country")
private String billingCountry;
#Column(name = "billing_state")
private String billingState;
#Column(name = "billing_street")
private String billingStreet;
#Column(name = "billing_zip")
private String billingZip;
private String company;
#Column(name = "display_name")
private String displayName;
private String email;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "middle_name")
private String middleName;
#Column(name = "other_details")
private String otherDetails;
#Column(name = "print_on_check_as")
private String printOnCheckAs;
#Column(name = "shipping_city")
private String shippingCity;
#Column(name = "shipping_country")
private String shippingCountry;
#Column(name = "shipping_state")
private String shippingState;
#Column(name = "shipping_street")
private String shippingStreet;
#Column(name = "shipping_zip")
private String shippingZip;
private String suffix;
private String title;
// bi-directional many-to-one association to Order
#OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
private List<Order> orders;
public Customer() {
}
public int getCustIDPK() {
return this.custIDPK;
}
public void setCustIDPK(int cust_ID_PK) {
this.custIDPK = cust_ID_PK;
}
public String getBillingCity() {
return this.billingCity;
}
public void setBillingCity(String billingCity) {
this.billingCity = billingCity;
}
public String getBillingCountry() {
return this.billingCountry;
}
public void setBillingCountry(String billingCountry) {
this.billingCountry = billingCountry;
}
public String getBillingState() {
return this.billingState;
}
public void setBillingState(String billingState) {
this.billingState = billingState;
}
public String getBillingStreet() {
return this.billingStreet;
}
public void setBillingStreet(String billingStreet) {
this.billingStreet = billingStreet;
}
public String getBillingZip() {
return this.billingZip;
}
public void setBillingZip(String billingZip) {
this.billingZip = billingZip;
}
public String getCompany() {
return this.company;
}
public void setCompany(String company) {
this.company = company;
}
public String getDisplayName() {
return this.displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMiddleName() {
return this.middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getOtherDetails() {
return this.otherDetails;
}
public void setOtherDetails(String otherDetails) {
this.otherDetails = otherDetails;
}
public String getPrintOnCheckAs() {
return this.printOnCheckAs;
}
public void setPrintOnCheckAs(String printOnCheckAs) {
this.printOnCheckAs = printOnCheckAs;
}
public String getShippingCity() {
return this.shippingCity;
}
public void setShippingCity(String shippingCity) {
this.shippingCity = shippingCity;
}
public String getShippingCountry() {
return this.shippingCountry;
}
public void setShippingCountry(String shippingCountry) {
this.shippingCountry = shippingCountry;
}
public String getShippingState() {
return this.shippingState;
}
public void setShippingState(String shippingState) {
this.shippingState = shippingState;
}
public String getShippingStreet() {
return this.shippingStreet;
}
public void setShippingStreet(String shippingStreet) {
this.shippingStreet = shippingStreet;
}
public String getShippingZip() {
return this.shippingZip;
}
public void setShippingZip(String shippingZip) {
this.shippingZip = shippingZip;
}
public String getSuffix() {
return this.suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Order> getOrders() {
return this.orders;
}
public void setOrders(List<Order> orders) {
this.orders = orders;
}
public Order addOrder(Order order) {
getOrders().add(order);
order.setCustomer(this);
return order;
}
public Order removeOrder(Order order) {
getOrders().remove(order);
order.setCustomer(null);
return order;
}
}
Order.java
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
#Entity
#Table(name = "orders")
#NamedQuery(name = "Order.findAll", query = "SELECT o FROM Order o")
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "order_ID_PK")
#GeneratedValue(strategy = GenerationType.AUTO)
private int order_ID_PK;
#Column(name = "custom_message")
private String customMessage;
#Temporal(TemporalType.DATE)
#Column(name = "delivery_due_date")
private Date deliveryDueDate;
#Temporal(TemporalType.DATE)
#Column(name = "invoice_creation_date")
private Date invoiceCreationDate;
#Temporal(TemporalType.DATE)
#Column(name = "payment_due_date")
private Date paymentDueDate;
// bi-directional many-to-one association to Customer
#ManyToOne
#JoinColumn(name = "cust_ID_FK")
private Customer customer;
// bi-directional many-to-many association to Product
#ManyToMany(mappedBy = "orders")
private List<Product> products;
public Order() {
}
public int getOrder_ID_PK() {
return this.order_ID_PK;
}
public void setOrder_ID_PK(int order_ID_PK) {
this.order_ID_PK = order_ID_PK;
}
public String getCustomMessage() {
return this.customMessage;
}
public void setCustomMessage(String customMessage) {
this.customMessage = customMessage;
}
public Date getDeliveryDueDate() {
return this.deliveryDueDate;
}
public void setDeliveryDueDate(Date deliveryDueDate) {
this.deliveryDueDate = deliveryDueDate;
}
public Date getInvoiceCreationDate() {
return this.invoiceCreationDate;
}
public void setInvoiceCreationDate(Date invoiceCreationDate) {
this.invoiceCreationDate = invoiceCreationDate;
}
public Date getPaymentDueDate() {
return this.paymentDueDate;
}
public void setPaymentDueDate(Date paymentDueDate) {
this.paymentDueDate = paymentDueDate;
}
public Customer getCustomer() {
return this.customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public List<Product> getProducts() {
return this.products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
OrderOperation.java
package com.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.model.Order;
public interface OrderOperation extends JpaRepository<Order, Long> {
#Query("SELECT c.orders FROM Customer c where c.custIDPK = :id")
public List<Order> findOrderbyID(#Param("id") int id);
}
CustomerController.java
#RestController
#RequestMapping("/customer")
public class CustomerController {
#Autowired
ICutomerService customerDAO;
#SuppressWarnings({ "unchecked", "rawtypes" })
#RequestMapping(value = { "/", "" }, method = RequestMethod.GET, produces = { "application/json" })
public ResponseEntity<?> getAllCustomer() {
return new ResponseEntity(customerDAO.getAllCustomer(), HttpStatus.ACCEPTED);
}
#RequestMapping(value = "/{CustomerById}", method = RequestMethod.GET, produces = { "application/json" })
public Customer getCustomerbyId(#PathVariable("CustomerById") String cid) {
return customerDAO.findCustomerById(Integer.parseInt(cid));
}
#SuppressWarnings({ "unchecked", "rawtypes" })
#RequestMapping(value = "{CustomerById}/order", method = RequestMethod.GET, produces = { "application/json" })
public ResponseEntity<?> getAllOrder(#PathVariable("CustomerById") String cid) {
return new ResponseEntity(customerDAO.getOrdersbyId(Integer.parseInt(cid)), HttpStatus.ACCEPTED);
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#RequestMapping(value = "order/{CustomerById}/product", method = RequestMethod.GET, produces = {
"application/json" })
public ResponseEntity<?> getAllProduct(#PathVariable("CustomerById") String cid) {
return new ResponseEntity(customerDAO.getProductsById(Integer.parseInt(cid)), HttpStatus.ACCEPTED);
}
#SuppressWarnings("rawtypes")
#RequestMapping(value = "/add", method = RequestMethod.POST)
public ResponseEntity<?> addCustomer(#RequestBody Customer c) {
boolean flag = customerDAO.addCustomer(c);
if (flag)
return new ResponseEntity(HttpStatus.CREATED);
else
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
#SuppressWarnings("rawtypes")
#RequestMapping(value = "/{CustomerById}/orders", method = RequestMethod.POST)
public ResponseEntity<?> addOrders(#PathVariable("CustomerById") String cid, #RequestBody Order c) {
// c.getCustomer().setCustIDPK(Integer.parseInt(cid));
boolean flag = customerDAO.addOrder(c);
if (flag) {
return new ResponseEntity(HttpStatus.CREATED);
} else {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
}
How should I design this addOrders method?
If you are using Spring Data then you will need to create a CrudRepository for each table you which to access. The CrudRepository allows you to easily manipulate data in your table using standard ORM practices. Here is a link with more details.
For more detailed info on how to use Spring Data check out this wonderful guide. This guide has become indispensable when working with Spring Data.
There are many options to this but i have used below approach so hope it helps you. The #Query annotation allows to execute native queries by setting the nativeQuery flag to true.
#Query(value = "select o.* from customer c inner join order o on c.customer_id = o.customer_id where o. = ?1", nativeQuery = true)
Please write sql according to your requirement.
I have created a spring boot project with mongodb , when i insert data into collection it get inserted but when i try to fetch from findOne by id the inserted value based on id it always returns null, I have given my model class and inserting method below,please tell me whats wrong
Account.java
#Document(collection = "account")
public class Account {
#Id
private long _id;
#Field("account_name")
private String accountName;
#Field("connector_type")
private String connectorType;
#Field("xsiURI1")
private String xsiURI1;
#Field("xsiURI2")
private String xsiURI2;
#Field("oci1")
private String OCI1;
#Field("oci2")
private String OCI2;
#Field("telcomadmin_username")
private String telcomadminUsername;
#Field("telcomadmin_password")
private String telcomadminPassword;
#Field("password_expdays")
private String passwordExpdays;
#Field("account_email_address")
private String accountEmailAddress;
#DateTimeFormat(iso = ISO.DATE_TIME)
#Field("inserted_date")
private Date insertedDate;
#DateTimeFormat(iso = ISO.DATE_TIME)
#Field("updated_date")
private Date updatedDate;
#Field("isActive")
private Boolean isActive;
public long get_id() {
return _id;
}
public void set_id(long _id) {
this._id = _id;
}
public String getXsiURI1() {
return xsiURI1;
}
public void setXsiURI1(String xsiURI1) {
this.xsiURI1 = xsiURI1;
}
public String getXsiURI2() {
return xsiURI2;
}
public void setXsiURI2(String xsiURI2) {
this.xsiURI2 = xsiURI2;
}
public String getOCI1() {
return OCI1;
}
public void setOCI1(String oCI1) {
OCI1 = oCI1;
}
public String getOCI2() {
return OCI2;
}
public void setOCI2(String oCI2) {
OCI2 = oCI2;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getConnectorType() {
return connectorType;
}
public void setConnectorType(String connectorType) {
this.connectorType = connectorType;
}
public String getTelcomadminUsername() {
return telcomadminUsername;
}
public void setTelcomadminUsername(String telcomadminUsername) {
this.telcomadminUsername = telcomadminUsername;
}
public String getTelcomadminPassword() {
return telcomadminPassword;
}
public void setTelcomadminPassword(String telcomadminPassword) {
this.telcomadminPassword = telcomadminPassword;
}
public String getPasswordExpdays() {
return passwordExpdays;
}
public void setPasswordExpdays(String passwordExpdays) {
this.passwordExpdays = passwordExpdays;
}
public String getAccountEmailAddress() {
return accountEmailAddress;
}
public void setAccountEmailAddress(String accountEmailAddress) {
this.accountEmailAddress = accountEmailAddress;
}
public Date getInsertedDate() {
return insertedDate;
}
public void setInsertedDate(Date insertedDate) {
this.insertedDate = insertedDate;
}
public Date getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(Date updatedDate) {
this.updatedDate = updatedDate;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
}
AccountsController.java
#RestController
#RequestMapping("/accounts")
#CrossOrigin("*")
public class AccountsController {
#Autowired
AccountsRepository accountsRepository;
#Autowired
SequenceRepository sequenceRepository;
private static final String ACCOUNT_SEQ_KEY = "accountsequence";
#PostMapping("/create")
public Account createAccount(#Valid #RequestBody Account account) {
account.set_id(sequenceRepository.getNextSequenceId(ACCOUNT_SEQ_KEY));
account.setIsActive(true);
return accountsRepository.save(account);
}
#GetMapping(value = "/findByID/{id}")
public ResponseEntity<Account> getAccountById(#PathVariable("id") String id) {
Account account = accountsRepository.findOne(id);
if (account == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} else {
return new ResponseEntity<>(account, HttpStatus.OK);
}
}
}
AccountsRepository
public interface AccountsRepository {
List<Account> findAll(Sort sortByCreatedAtDesc);
Account save(Account account);
Account findOne(String id);
void delete(String id);
}
AccountsRepositoryIMPL
#Repository
public class AccountsRepositoryImpl implements AccountsRepository {
DBOperations dbOperations = new DBOperations();
#Override
public List<Account> findAll(Sort sortByCreatedAtDesc) {
Query q = new Query().with(new Sort(Sort.Direction.ASC, "inserted_date"));
List<Account> accountList = dbOperations.getMongoOpertion().findAllAndRemove(q, Account.class);
return accountList;
}
#Override
public Account save(Account account) {
try {
dbOperations.getMongoOpertion().save(account);
} catch (Exception e) {
e.printStackTrace();
}
return account;
}
#Override
public Account fin**strong text**dOne(String id) {
Account account = dbOperations.getMongoOpertion().findOne(Query.query(Criteria.where("_id").is(id)),
Account.class, "account");
return account;
}
#Override
public void delete(String id) {
Query query = new Query();
query.addCriteria(Criteria.where("id").is(id));
Account account = dbOperations.getMongoOpertion().findOne(query, Account.class);
dbOperations.getMongoOpertion().remove(account);
}
}
DBOperations.java
public class DBOperations {
ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml");
public MongoOperations getMongoOpertion() {
MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");
return mongoOperation;
}
}
Look at your code.
You have declared _id as Long type.
#Id
private long _id;
But in your below methods you are passing String id to match the criteria.
So it is not working.
#Override
public Account findOne(String id) {
Account account = dbOperations.getMongoOpertion().findOne(Query.query(Criteria.where("_id").is(id)),
Account.class, "account");
return account;
}
#Override
public void delete(String id) {
Query query = new Query();
query.addCriteria(Criteria.where("id").is(id));
Account account = dbOperations.getMongoOpertion().findOne(query, Account.class);
dbOperations.getMongoOpertion().remove(account);
}
Whenever I call save() method the same ID is shared between three different entities and I don't know why ?
#Entity
public class Department {
#Id
#GeneratedValue
private Long departmentId;
private String name;
public Department(Long departmentId) {
this.departmentId = departmentId;
}
public Department() {
}
public Department(String name) {
this.name = name;
}
public Long getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Long departmentId) {
this.departmentId = departmentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
#Entity
public class Location {
#Id
#GeneratedValue
private Long locationId;
private String name;
public Location(Long locationId) {
this.locationId = locationId;
}
public Location() {
}
public Location(String name) {
this.name = name;
}
public Long getLocationId() {
return locationId;
}
public void setLocationId(Long locationId) {
this.locationId = locationId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And this is my Controller:
#RestController
public class SettingsController {
#Autowired
private LocationRepository locationRepository;
#Autowired
private DepartmentRepository departmentRepository;
#Autowired
private RoleRepository roleRepository;
#RequestMapping(value = "/api/locations", method = RequestMethod.POST)
public ResponseEntity addLocation(#RequestBody DataForm dataForm) {
if (dataForm == null) {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
locationRepository.save(new Location(dataForm.getName()));
return new ResponseEntity(HttpStatus.CREATED);
}
#RequestMapping(value = "/api/roles", method = RequestMethod.POST)
public ResponseEntity addRole(#RequestBody DataForm dataForm) {
if (dataForm == null) {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
roleRepository.save(new Role(dataForm.getName()));
return new ResponseEntity(HttpStatus.CREATED);
}
#RequestMapping(value = "/api/departments", method = RequestMethod.POST)
public ResponseEntity addDepartment(#RequestBody DataForm dataForm) {
if (dataForm == null) {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
departmentRepository.save(new Department(dataForm.getName()));
return new ResponseEntity(HttpStatus.CREATED);
}
}
This should happen only if the id would be static, but It's not. If I create two new Location() objects, when I will create a new Department() the Id of the department will be 3. Why ?
Since you didn't specify the strategy for #GeneratedValue, I guess that Hibernate uses the same sequence for all your entities.
You can set something like
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="department_seq_gen")
#SequenceGenerator(name="department_seq_gen", sequenceName="DEPARTMENT_SEQ")
on Department entity, and something similar on Location entity (just use location_seq_gen and LOCATION_SEQ).
i'm using SpringBoot, with Spring JPA Hibernate, i'm trying to use the ManyToMany Annotation but it isn't working.
The join table is created, but never populated.
#Entity
#Table(name = "commande")
public class Commande {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer commandeID;
private String etat;
private String date_de_validation;
#ManyToOne(cascade = CascadeType.ALL)
private Client clientID;
#ManyToOne(cascade = CascadeType.ALL)
private Livreur livreurID;
#ManyToOne(cascade = CascadeType.ALL)
private Livraison livraisonID;
#ManyToMany
#JoinTable(name = "Join_Produit_To_Commande", joinColumns = { #JoinColumn(name = "commandeID") }, inverseJoinColumns = { #JoinColumn(name = "produitID") })
private Set<Produit> produits = new HashSet<Produit>();;
public Commande() {
}
public Commande(String etat, String date_de_validation, Client clientID,
Livreur livreurID, Livraison livraisonID) {
setEtat(etat);
setDate_de_validation(date_de_validation);
setClient(clientID);
setLivreur(livreurID);
setLivraison(livraisonID);
}
public Integer getCommandeID() {
return this.commandeID;
}
public void setCommandeID(Integer commandeID) {
this.commandeID = commandeID;
}
public String getEtat() {
return this.etat;
}
public void setEtat(String etat) {
this.etat = etat;
}
public String getDate_de_validation() {
return this.date_de_validation;
}
public void setDate_de_validation(String date_de_validation) {
this.date_de_validation = date_de_validation;
}
public Client getClient() {
return this.clientID;
}
public void setClient(Client clientID) {
this.clientID = clientID;
}
public Livreur getLivreur() {
return this.livreurID;
}
public void setLivreur(Livreur livreurID) {
this.livreurID = livreurID;
}
public Livraison getLivraison() {
return this.livraisonID;
}
public void setLivraison(Livraison livraisonID) {
this.livraisonID = livraisonID;
}
public Client getClientID() {
return clientID;
}
public void setClientID(Client clientID) {
this.clientID = clientID;
}
public Livreur getLivreurID() {
return livreurID;
}
public void setLivreurID(Livreur livreurID) {
this.livreurID = livreurID;
}
public Livraison getLivraisonID() {
return livraisonID;
}
public void setLivraisonID(Livraison livraisonID) {
this.livraisonID = livraisonID;
}
public Collection<Produit> getProduits() {
return produits;
}
public void setProduits(Set<Produit> produits) {
this.produits = produits;
}
public String toString() {
return "commandeID=" + commandeID + " etat=" + etat
+ " date_de_validation=" + date_de_validation + " clientID="
+ clientID + " livreurID=" + livreurID + " livraisonID="
+ livraisonID;
}
}
This is my second class
#Entity
#Table(name = "produit")
public class Produit {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer produitID;
private String libelle;
private double poid;
private String type;
#ManyToMany(mappedBy = "produits")
private Set<Commande> commandes = new HashSet<Commande>();;
public Produit() {
}
public Produit(String libelle, double poid, String type) {
setLibelle(libelle);
setPoid(poid);
setType(type);
}
public String getLibelle() {
return this.libelle;
}
public void setLibelle(String Libelle) {
this.libelle = Libelle;
}
public double getPoid() {
return this.poid;
}
public void setPoid(double poid) {
this.poid = poid;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public Set<Commande> getCommandes() {
return commandes;
}
public void setCommandes(Set<Commande> commandes) {
this.commandes = commandes;
}
public String toString() {
return "Libelle=" + libelle + " poid=" + poid + " type=" + type
+ " produitID=" + produitID + " Commandes : " + commandes;
}
}
And here my Unit testing
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = PfeApplication.class)
#WebAppConfiguration
#Transactional
#TransactionConfiguration(defaultRollback = true)
public class PfeApplicationTests {
#Autowired
private EntrepriseService service;
#Autowired
private PhoneService pService;
#Autowired
private LivreurService lService;
#Autowired
private CarService cService;
#Autowired
private ProduitService prService;
#Autowired
private ClientService clService;
#Autowired
private CommandeService cmdService;
#Autowired
private PositionLivreurService posService;
#Autowired
private LivraisonService livService;
#Test
public void contextLoads() {
}
#Test
#Transactional
public void manyToManyTest(){
Produit produit1 = new Produit("Lavabo", 50, "Cassable");
Livreur livreur1 = new Livreur("Adadi", "Soufiane", "03/03/1992", "0876543456");
Client client1 = new Client("Ouali", "Ouali#gmail.com", "0743453462", "Fes", "NoLogo");
Livraison livraison1 = new Livraison("24/04/2015", "25/04/2015", false, false, livreur1);
Commande commande1 = new Commande("Validé", "25/04/2015", client1, livreur1, livraison1);
produit1.getCommandes().add(commande1);
commande1.getProduits().add(produit1);
cmdService.addCommande(commande1);
prService.addProduit(produit1);
}
}
This problem similar to an earlier posting of mine. See My original posting. I solved it myself - it is basically a bug in the implementation, but if you just change Set<> into List<>, it could maybe work. Your case is different, you are using a spring implementation, but who knows ...
Resolved !
I had to add them both on the same Session on a transaction and then commit.