I am trying to create an application to save data into the Oracle database using CrudRepository. Here is my repositiry:
public interface CustomerRepository extends CrudRepository<Customer, Long> {
List<Customer> findByEmail(String email);
List<Customer> findByDate(Date date);
// custom query example and return a stream
#Query("select c from Customer c where c.email = :email")
Stream<Customer> findByEmailReturnStream(#Param("email") String email);
}
My application.property looks like:
spring.datasource.url=jdbc:oracle:thin:#vgdevst-scan.hhs.local:1521/EONDEV.hhslocal
spring.datasource.username=EON_USER
spring.datasource.password=EON_USERD
spring.datasource.driver-class-oracle.jdbc.driver.OracleDriver
While my customer entity class is :
#Entity
public class Customer {
//http://www.oracle.com/technetwork/middleware/ias/id-generation-083058.html
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CUST_SEQ")
#SequenceGenerator(sequenceName = "customer_seq", initialValue = 1, allocationSize = 1, name = "CUST_SEQ")
Long id;
String name;
String email;
//#Temporal(TemporalType.DATE)
#Column(name = "CREATED_DATE")
Date date;
public Customer(String name, String email, Date date) {
this.name = name;
this.email = email;
this.date = date;
}
public Customer(Long id, String name, String email, Date date) {
super();
this.id = id;
this.name = name;
this.email = email;
this.date = date;
}
public Customer() {
}
#Override
public String toString() {
return "Customer{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", date=" + date +
'}';
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
I am trying to save a new cutomer to database using:
#SpringBootApplication
public class Application implements CommandLineRunner {
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
#Autowired
DataSource dataSource;
#Autowired
CustomerRepository customerRepository;
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
#Transactional(readOnly = true)
#Override
public void run(String... args) throws Exception {
System.out.println("DATASOURCE = " + dataSource);
customerRepository.save(new Customer(new Long(4),"Amit","a.r#state.ma.us",new Date()));
System.out.println("\n1.findAll()...");
for (Customer customer : customerRepository.findAll()) {
System.out.println(customer);
}
}
}
I do not see the new customer added either in sops or in database. What am i missing here?
Your problem seems to be that you are executing the save statement in a readOnly transaction. The solution could be as simple as removing that property.
Reading the readOnly flag documentation, it states that:
A boolean flag that can be set to true if the transaction is effectively read-only, allowing for corresponding optimizations at runtime.
Use only #Transactional:
#Transactional
#Override
public void run(String... args) throws Exception {
// the rest of your code ...
}
The code was working just fine.
Its just that in my application code, i had changed the application.property file as per my old code and instead of "spring.datasource.url" i had put "appname.datasource.url", which is why code never interacted with DB.
Related
I'm new to this tool and I'm having trouble with this specific issue. I looked for an example But could not find something similar, better, I found a possible solution, but in my case It doesn't work.
I have this narrow project that resembles our famous CRUD, and I'm trying to reference the primary key from one table to another.
Client Entity:
#Entity
#Table(name = "client")
public class Client {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "cpf", length = 14)
private String cpf;
#Column(name = "name", length = 100)
private String name;
#Column(name = "birth_date")
private LocalDate birthDate;
#Column(name = "address", length = 255)
private String address;
#Column(name = "telephone", length = 14)
private String telephone;
#Column(name = "email", length = 200)
private String email;
#Column(name = "date_register", insertable = true, updatable = false)
private LocalDate dateRegister;
public Client() {
super();
}
public Client(Long id, String cpf, String name, LocalDate birthDate, String address, String telephone, String email, LocalDate dateRegister) {
super();
this.id = id;
this.cpf = cpf;
this.name = name;
this.birthDate = birthDate;
this.address = address;
this.telephone = telephone;
this.email = email;
this.dateRegister = dateRegister;
}
public Client(String cpf, String name, LocalDate birthDate, String address, String telephone, String email, LocalDate dateRegister) {
super();
this.cpf = cpf;
this.name = name;
this.birthDate = birthDate;
this.address = address;
this.telephone = telephone;
this.email = email;
this.dateRegister = dateRegister;
}
#PrePersist
public void prePersist() {
setDateRegister(LocalDate.now());
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public LocalDate getDateRegister() {
return dateRegister;
}
public void setDateRegister(LocalDate dateRegister) {
this.dateRegister = dateRegister;
}
#Override
public String toString() {
return "Client [id=" + id + ", cpf=" + cpf + ", name=" + name + ", birthDate=" + birthDate + ", address="
+ address + ", telephone=" + telephone + ", email=" + email + ", dateRegister=" + dateRegister + "]";
}
}
Sale Entity:
#Entity
#Table(name = "sale")
public class Sale {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne
#JoinColumn(name = "client_id")
private Client client;
#OneToMany(mappedBy = "sale")
private List<SaleItem> items;
#Column(name = "payment_type", length = 10)
#Enumerated(EnumType.STRING)
private PaymentType paymentType;
#Column(name = "amount")
private BigDecimal amount;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public List<SaleItem> getItems() {
return items;
}
public void setItems(List<SaleItem> items) {
this.items = items;
}
public PaymentType getPaymentType() {
return paymentType;
}
public void setPaymentType(PaymentType paymentType) {
this.paymentType = paymentType;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
#Override
public String toString() {
return "Sale [id=" + id + ", client=" + client + ", items=" + items + ", paymentType=" + paymentType
+ ", amount=" + amount + "]";
}
}
The objective is to link the client to a sale through its primary key. These two codes refer to the sales repository and its controller:
SaleRepository:
public interface SaleRepository extends JpaRepository<Sale, Long> {
}
SaleController:
#RestController
#RequestMapping("/api/sales")
#CrossOrigin("*")
public class SaleController {
#Autowired
private SaleRepository repository;
#Autowired
private SaleItemRepository saleItemrepository;
#PostMapping
#Transactional
public void save(#RequestBody Sale sale) {
repository.save(sale);
sale.getItems().stream().forEach(saleItem -> saleItem.setSale(sale));
saleItemrepository.saveAll(sale.getItems());
}
}
And the problem is exactly how this reference is being made. In the current private Client client; way , the client object is being passed in full instead of its id, that's why it throws this following error when I try to register the sale.
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.time.LocalDate` from String "31/05/1968": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text '31/05/1968' could not be parsed at index 0; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDate` from String "31/05/1968": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text '31/05/1968' could not be parsed at index 0<EOL> at [Source: (PushbackInputStream); line: 1, column: 87] (through reference chain: MyNameIsRafaelSampaio.github.com.bruxo_vendas_ltda_api.model.Sale["client"]->MyNameIsRafaelSampaio.github.com.bruxo_vendas_ltda_api.model.Client["birthDate"])]
As was to be expected, since the column birthDate present in the client entity is not being treated correctly in the sale entity. I did research on a possible solution but none made much sense to me, I believe for being a newbie, one of the solutions that I found more understandable was the use of the #MapsId tag. I tried to make changes to adapt, but I was not successful, if you can help I will be grateful.
I am simply trying to create a Spring boot Hibernate CRUD REST API through this code:
EmployeController.java
#RestController
#RequestMapping("/api")
public class EmployeController {
#Autowired
private EmployeService employeService;
#GetMapping("/employe")
public List<Employe> get(){
return employeService.get();
}
}
Employe.java
#Entity
#Table(name="employe")
public class Employe {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private int id;
#Column
private String name;
#Column
private String gender;
#Column
private String department;
#Column
private Date dob;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
#Override
public String toString() {
return "Employe [id=" + id + ", name=" + name + ", gender=" + gender + ", department=" + department + ", dob="
+ dob + "]";
}
}
EmployeService.java
public interface EmployeService {
List<Employe> get();
Employe get(int id);
void save(Employe employe);
void delete(int id);
}
EmployeServiceImplement.java
#Service
public class EmployeServiceImplement implements EmployeService {
#Autowired
private EmployeDAO employeDAO;
#Transactional
#Override
public List<Employe> get() {
return employeDAO.get();
}
}
EmployeDAO.java
public interface EmployeDAO {
List<Employe> get();
Employe get(int id);
void save(Employe employe);
void delete(int id);
}
EmployeDAOImplement.java
#Repository
public class EmployeDAOImplement implements EmployeDAO {
#Autowired
private EntityManager entityManager;
#Override
public List<Employe> get() {
Session currentSession = entityManager.unwrap(Session.class);
Query<Employe> query = currentSession.createQuery("from Employe", Employe.class);
List<Employe>list = query.getResultList();
return list;
}
}
I have write all the configuration related to MySQl database into the application.properties and when i run this project as Spring Boot App and go to the Postman and tried like this
and i a unable to understan why it always throws 404 error every time , can anyone tell me what i am missing in this code.
Try with this GET request, it may help you:
http://localhost:8080/api
I checked your code.
where is #RestController for your Controller file and where is #RequestMapping For your method in Controller class?
maybe you should write something like this according to your need.
tell me if you need more help.
#RestController
#RequestMapping("/api")
public class EmployeController {
#RequestMapping(value = "/employ")
public void employ() {
}
}
Instead of this -
#Override
public List get()
Use this -
#RequestMapping(value = "/Employe", method = RequestMethod.GET)
public List get()
I have a RESTcontroller that has a delete mapping like so:
#DeleteMapping("/deleterequest/{custId}")
//#Transactional
public ResponseEntity<?> delete(#PathVariable long custId) {
log.info("entering deleterequest");
LeaveQuery deleteLeaveQuery = leaveQueryRepository.findOne(custId);
log.info("condition" + deleteLeaveQuery.getStatus().equals("Onbehandeld"));
// if (!deleteLeaveQuery.getStatus().equals("Onbehandeld"))
// return ResponseEntity.badRequest().build();
//deleteLeaveQuery.setAccount(null);
//leaveQueryRepository.save(deleteLeaveQuery);
log.info("is deleteLeaveQuery null? " + (deleteLeaveQuery == null));
//leaveQueryRepository.delete(deleteLeaveQuery);
//leaveQueryRepository.delete(deleteLeaveQuery.getId());
leaveQueryRepository.deleteById(deleteLeaveQuery.getId());
accountService.sendLeaveRequestCanceledNotification(deleteLeaveQuery);
return ResponseEntity.ok().build();
}
When I use the regular (built-in) delete function of my leaveQueryRepository, I get no error, not during log INFO mode nor with log DEBUG mode on. However the object doesn't get deleted either. Its still in the database after the delete method was called. When I make a custom spring repository method called deleteById I get the following error:
org.springframework.dao.InvalidDataAccessApiUsageException: No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call; nested exception is javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call
at
I have no idea what is causing this error. The jparepository looks like this:
#Repository
public interface LeaveQueryRepository extends JpaRepository<LeaveQuery, Long> {
//#Modifying
public void deleteById(long id);
}
The LeaveRequest object looks like this:
#Entity
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id",
scope = LeaveQuery.class)
public class LeaveQuery implements Serializable {
#Id
#GeneratedValue
private Long id;
private Date startDate;
private Date endDate;
private String status = "Onbehandeld";
private String reason ="";
private int totalHours;
private String processedBy;
#ManyToOne(fetch = FetchType.EAGER) //, cascade = CascadeType.PERSIST
#JoinColumn(name = "FK_account", nullable = true)
private Account account;
public String getProcessedBy() {
return processedBy;
}
public void setProcessedBy(String processedBy) {
this.processedBy = processedBy;
}
public int getTotalHours() {
return totalHours;
}
public void setTotalHours(int totalHours) {
this.totalHours = totalHours;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
return "LeaveQuery{" +
"id=" + id +
", startDate=" + startDate +
", endDate=" + endDate +
", denialReason='" + reason + '\'' +
'}';
}
}
It has a relation with an Account object which looks like this:
#Entity
//#JsonIgnoreProperties
//#JsonIdentityInfo(
// generator = ObjectIdGenerators.PropertyGenerator.class,
// property = "id",
// scope = Account.class)
public class Account implements Serializable {
#Id
#GeneratedValue
private Long id;
private String username;
private String password;
private String name;
private boolean admin;
private boolean enabled;
private int remainingStatutoryLeaveHours = 240;
private int remainingNonStatutoryLeaveHours = 60;
#JsonIgnore
#OneToMany(fetch = FetchType.EAGER, mappedBy = "account", cascade = CascadeType.ALL)
List<LeaveQuery> leaveQueryList;
//
#OneToMany(fetch = FetchType.LAZY, mappedBy = "account", cascade = CascadeType.ALL)
List<LaborPeriod> laborperiods = new ArrayList<>();
#OneToOne
private Person person;
#Enumerated
UserRole userRole = UserRole.USER;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public UserRole getUserRole() {
return userRole;
}
public void setUserRole(UserRole userRole) {
this.userRole = userRole;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isAdmin() {
return admin;
}
public void setAdmin(boolean admin) {
this.admin = admin;
}
public List<LaborPeriod> getLaborperiods() {
return laborperiods;
}
public void setLaborperiods(List<LaborPeriod> laborperiods) {
this.laborperiods = laborperiods;
}
public List<LeaveQuery> getLeaveQueryList() {
return leaveQueryList;
}
public void setLeaveQueryList(List<LeaveQuery> leaveQueryList) {
this.leaveQueryList = leaveQueryList;
}
public int getRemainingStatutoryLeaveHours() {
return remainingStatutoryLeaveHours;
}
public void setRemainingStatutoryLeaveHours(int remainingStatutoryLeaveHours) {
this.remainingStatutoryLeaveHours = remainingStatutoryLeaveHours;
}
public int getRemainingNonStatutoryLeaveHours() {
return remainingNonStatutoryLeaveHours;
}
public void setRemainingNonStatutoryLeaveHours(int remainingNonStatutoryLeaveHours) {
this.remainingNonStatutoryLeaveHours = remainingNonStatutoryLeaveHours;
}
#Override
public String toString() {
return "Account{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", name='" + name + '\'' +
", admin=" + admin +
", enabled=" + enabled +
", remainingStatutoryLeaveHours=" + remainingStatutoryLeaveHours +
", remainingNonStatutoryLeaveHours=" + remainingNonStatutoryLeaveHours +
", userRole=" + userRole +
'}';
}
}
Does anyone know what could be causing this error?
Any help would be appreciated.
All controller methods should be none transactional.
You should add one more layer between Controller and Repository (Service layer) and put #Transactional on Service class or put this annotation on your method in this Service class.
It should be Controller -> Service -> Repository
To let #Transactional work you should init TransactionalManager.
You can add something like this in your Persistence Configuration
#Bean
public JpaTransactionManager transactionManager() throws IOException {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
Use orphanRemoval = true.
Try to update your Account class like so
#JsonIgnore
#OneToMany(fetch = FetchType.EAGER, mappedBy = "account", cascade = CascadeType.ALL, orphanRemoval = true)
List<LeaveQuery> leaveQueryList;
Also check out this question.
I have three entity classes, I have written the query which includes join of two tables.
Table: ExpensesCategories
#Entity
#Table(name = "ExpensesCategories")
public class ExpensesCategories {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "category_id", unique = true)
private int categoryId;
#NotNull
private String categoryName;
#NotNull
private String categoryCodeInBankStats;
public int getCategoryId() {
return categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getCategoryCodeInBankStats() {
return categoryCodeInBankStats;
}
public void setCategoryCodeInBankStats(String categoryCodeInBankStats) {
this.categoryCodeInBankStats = categoryCodeInBankStats;
}
}
Table: Transactions
#Entity
#Table(name = "TransactionHistory")
public class TransactionHistory {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Temporal(TemporalType.DATE)
private Date dateOfTransaction;
private String transactionType;
private String refNo;
private Date valueDate;
private double withdrawalAmount;
private double depositAmount;
private double closingBalance;
#ManyToOne
#JoinColumn(name="userDetailsId", referencedColumnName="user_id")
private UserDetails userDetails;
#ManyToOne
#JoinColumn(name="expenseCategoriesId", referencedColumnName="category_id")
private ExpensesCategories expenseCategories;
public TransactionHistory(int userId, Date dateOfTransaction, String transactionType, String refNo, Date valueDate,
double withdrawalAmount, double depositAmount, double closingBalance) {
this.dateOfTransaction = dateOfTransaction;
this.transactionType = transactionType;
this.refNo = refNo;
this.valueDate = valueDate;
this.withdrawalAmount = withdrawalAmount;
this.depositAmount = depositAmount;
this.closingBalance = closingBalance;
}
public TransactionHistory() {
}
public Date getDateOfTransaction() {
return dateOfTransaction;
}
public void setDateOfTransaction(Date date) {
this.dateOfTransaction = date;
}
public String getTransactionType() {
return transactionType;
}
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
public String getRefNo() {
return refNo;
}
public void setRefNo(String refNo) {
this.refNo = refNo;
}
public Date getValueDate() {
return valueDate;
}
public void setValueDate(Date valueDate) {
this.valueDate = valueDate;
}
public double getWithdrawalAmount() {
return withdrawalAmount;
}
public void setWithdrawalAmount(double withdrawalAmount) {
this.withdrawalAmount = withdrawalAmount;
}
public double getDepositAmount() {
return depositAmount;
}
public void setDepositAmount(double depositAmount) {
this.depositAmount = depositAmount;
}
public double getClosingBalance() {
return closingBalance;
}
public void setClosingBalance(double closingBalance) {
this.closingBalance = closingBalance;
}
public UserDetails getUserDetails() {
return userDetails;
}
public void setUserDetails(UserDetails userDetails) {
this.userDetails = userDetails;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public ExpensesCategories getExpenseCategories() {
return expenseCategories;
}
public void setExpenseCategories(ExpensesCategories expenseCategories) {
this.expenseCategories = expenseCategories;
}
}
Table: User Details
#Entity
#Table(name = "Employee")
public class UserDetails {
#Id
#Column(name = "user_id", unique = true)
private int id;
#NotNull
private String firstname;
#NotNull
private String lastname;
#Column(unique = true)
#NotNull
private String emailaddress;
#NotNull
private String role;
public UserDetails(String firstname, String lastname, String emailaddress, String role) {
this.firstname = firstname;
this.lastname = lastname;
this.emailaddress = emailaddress;
this.role = role;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public UserDetails() {
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmailaddress() {
return emailaddress;
}
public void setEmailaddress(String emailaddress) {
this.emailaddress = emailaddress;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
#Override
public String toString() {
return "Employee [id=" + id + ", firstname=" + firstname + ", lastname=" + lastname + ", emailaddress="
+ emailaddress + ", role=" + role + "]";
}
I have written query like this in transaction entity.
#Query( nativeQuery=true, value="SELECT a.expense_categories_id, a.Total_withdrawal_Amount, b.category_code_in_bank_stats, b.category_name FROM (SELECT expense_categories_id , SUM(withdrawal_amount) AS Total_withdrawal_Amount FROM transaction_history GROUP BY expense_categories_id) a join expenses_categories b on a.expense_categories_id = b.category_id
")
List<Object[]> getCategorizedExpenses();
My Json Response is like:
[
[
1,
21,
"UPI",
"UPI Payments"
],
[
2,
3733.59,
"POS",
"Shopping"
]
]
But i want json response with column names as well:
[
[
expense_categories_id: 1,
Total_withdrawal_Amount: 21,
category_code_in_bank_stats: "UPI",
category_name: "UPI Payments"
],
[
expense_categories_id: 2,
Total_withdrawal_Amount: 3733.59,
category_code_in_bank_stats: "POS",
category_name: "Shopping"
]
]
Please help me out..
You would need to map the results directly to a POJO class and ad some json config:
1) Define the pojo
public ResultClass implements Serializable{
#JsonProperty("expense_categories_id")
private Integer expenseCategoriesId;
...
public ResultClass(Integer expenseCategoriesId ... // rest params){
this.expenseCategoriesId = expenseCategoriesId;
...
}
}
2) Define the mapping:
#SqlResultSetMapping(
name="myMapping",
classes={
#ConstructorResult(
targetClass=ResultClass.class,
columns={
#ColumnResult(name="expenseCategoriesId"),
#ColumnResult(name="totalWithdrawalAmount")
// further mappings ...
}
)
}
)
3) Define a native query
#NamedNativeQuery(name="TransactionHistory.myQuery"
, query="SELECT new mypackage.ResultClass(a.expense_categories_id as expeneCategoriesId ... ) from ...")
4) Define this method in the CrudRepository without the #Query annotation:
public List<ResultClass> myQuery();
Teh #SqlResultSetMapping and #NamedNativeQuery would need to be defined on one of your mapped entities.
Your native query will give you an object[][] as an result. So, it actually a mxn rows.
So,
I think you should create a class names Response
public class Response{
private Long expense_categories_id;
private Double Total_withdrawal_Amount;
private String category_code_in_bank_stats;
private String category_name;
//getters and setters for all attributes
}
List<Response> fillCategorizedExpenses(){
List<Response> response_List = new ArrayList<>();
Response response = null;
Object[][] // fill each object with by accessing their index from
//this array.
for() //iterate the object array. {
response = new Response();
response.setExpense_categories_id(value); // set all attributes.
....
....
....
response_List.add(response);
}
return response_List; //this will print as you need in your project.
}
Thank You :) Hope this might help you out.
I have a working hibernate setup using annotations
#Entity
#Table(name="Users")
public class User implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="USER_ID")
private int id = 0;
#Column(name="EMAIL")
private String email = "";
#Temporal(TemporalType.TIMESTAMP)
#Column(name="CREATED")
private Date created = null;
public User(){
Calendar cal = Calendar.getInstance();
this.created = cal.getTime();
}
public User(int id, String email, Date created) {
this.id = id;
this.email = email;
this.created = created;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
#Override
public String toString() {
return "centaurus.hib.User{" +
"id=" + id +
", email='" + email + '\'' +
", created=" + created +
'}';
}
}
to make this work i have to have a entry(amongst others) in my hibernate.cfg.xml file
<mapping class="centaurus.hib.User"/>
Otherwise hibernate throws error saying it has no mapping file.
alternatively when i create my persistent sessionfactory I can specify what classes are to be mapped.
The issue is, on other projects i have worked on I only needed to add a class and annotate it correctly for hibernate to use it. this is what i would like to do but don't know how. I don't want to have a list of classes in my hibernate config in addition to the annotated classes.
If you use Spring for your Session Factory, you can specify the 'packagesToScan' property.
<property name="packagesToScan" value="com.xyz.model" />
You can also use the Hibernate Configuration class if you're wiring up Hibernate manually and call Configuration#addAnnotatedClass(Class<?>).