Here what I'm trying to do, accessing data with RestControllers from SQL DB,
code is compiling and running fine (Tomcat started on port(s): 8081 (http) with context path '') but whenever I'm trying to access the mapping from postman on http://localhost:8081/getAllStudents, I'm getting error
{"timestamp":"2018-06-09T11:03:59.136+0000","status":404,"error":"Not Found","message":"No message available","path":"/getAllStudents"}
/**Spring boot app**/
package com.akshay;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#ComponentScan
#EnableJpaRepositories
#EnableAutoConfiguration
public class StartLearnApplication extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(StartLearnApplication.class, args);
}
}
/**CONTROLLER**/
package com.akshay.spring.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.akshay.spring.dtos.StudentDTO;
import com.akshay.spring.services.StudentService;
#RestController
#RequestMapping("/api")
public class StudentController {
#Autowired
private StudentService studentService;
#GetMapping("/getAllStudents")
public List<StudentDTO> getAllStudents() {
return studentService.getAllStudents();
}
#GetMapping("/getStudentByRollNumber")
public StudentDTO getStudentBy(#RequestParam(name="rollNumber") String rollNumber) {
return studentService.getStudentBy(rollNumber);
}
#PostMapping("/saveStudent")
public StudentDTO saveStudent(#RequestBody StudentDTO studentDTO) {
return studentService.saveStudent(studentDTO);
}
#PostMapping("/deleteStudentByRollNumber")
public void deleteStudentBy(#RequestParam(name="rollNumber")String rollNumber) {
studentService.deleteStudentBy(rollNumber);
}
}
/**Service Interface**/
package com.akshay.spring.services;
import java.util.List;
import com.akshay.spring.dtos.StudentDTO;
public interface StudentService {
List<StudentDTO> getAllStudents();
StudentDTO getStudentBy(String rollNumber);
StudentDTO saveStudent(StudentDTO studentDTO);
void deleteStudentBy(String rollNumber);
}
/**Service Impl**/
package com.akshay.spring.serviceImpls;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.akshay.spring.dtos.StudentDTO;
import com.akshay.spring.models.StudentModel;
import com.akshay.spring.repositories.StudentRepository;
import com.akshay.spring.services.StudentService;
#Service
public class StudentServiceImpl implements StudentService {
#Autowired
StudentRepository studentRepository;
#Override
public List<StudentDTO> getAllStudents() {
List <StudentModel> studentsModelList = studentRepository.findAll();
List <StudentDTO> studentDTOList = null;
for(StudentModel student: studentsModelList) {
studentDTOList.add(convertModelToDTO(student));
}
return studentDTOList;
}
#Override
public StudentDTO getStudentBy(String rollNumber) {
return convertModelToDTO(studentRepository.getStudentByRollNumber(rollNumber));
}
#Override
public StudentDTO saveStudent(StudentDTO studentDTO) {
studentRepository.save(convertDTOToModel(studentDTO));
return studentDTO;
}
#Override
public void deleteStudentBy(String rollNumber) {
studentRepository.deleteStudentByRollNumber(rollNumber);
}
private StudentDTO convertModelToDTO(StudentModel student) {
StudentDTO studentDTO = new StudentDTO();
studentDTO.setAddress(student.getAddress());
studentDTO.setEmailId(student.getEmailId());
studentDTO.setFathersName(student.getFathersName());
studentDTO.setFirstName(student.getFirstName());
studentDTO.setId(student.getId());
studentDTO.setLastName(student.getLastName());
studentDTO.setMothersName(student.getMothersName());
studentDTO.setPhoneNumber(student.getPhoneNumber());
studentDTO.setRollNumber(student.getRollNumber());
studentDTO.setStandard(student.getStandard());
return studentDTO;
}
private StudentModel convertDTOToModel(StudentDTO student) {
StudentModel studentModel = new StudentModel();
studentModel.setAddress(student.getAddress());
studentModel.setEmailId(student.getEmailId());
studentModel.setFathersName(student.getFathersName());
studentModel.setFirstName(student.getFirstName());
studentModel.setId(student.getId());
studentModel.setLastName(student.getLastName());
studentModel.setMothersName(student.getMothersName());
studentModel.setPhoneNumber(student.getPhoneNumber());
studentModel.setRollNumber(student.getRollNumber());
studentModel.setStandard(student.getStandard());
return studentModel;
}
}
/**Table Model**/
package com.akshay.spring.models;
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="student_details")
public class StudentModel {
#Id
#GeneratedValue(strategy =GenerationType.AUTO)
#Column(name = "id")
Long id;
#Column(name = "roll_number")
String rollNumber;
#Column(name = "first_name")
String firstName;
#Column(name = "last_name")
String lastName;
#Column(name = "standard")
String standard;
#Column(name = "phone_number")
String phoneNumber;
#Column(name = "email_id")
String emailId;
#Column(name = "fathers_name")
String fathersName;
#Column(name = "mothers_name")
String mothersName;
#Column(name = "address")
String address;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRollNumber() {
return rollNumber;
}
public void setRollNumber(String rollNumber) {
this.rollNumber = rollNumber;
}
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 getStandard() {
return standard;
}
public void setStandard(String standard) {
this.standard = standard;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getFathersName() {
return fathersName;
}
public void setFathersName(String fathersName) {
this.fathersName = fathersName;
}
public String getMothersName() {
return mothersName;
}
public void setMothersName(String mothersName) {
this.mothersName = mothersName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
#Override
public String toString() {
return "StudentDTO [id=" + id + ", rollNumber=" + rollNumber + ", firstName=" + firstName + ", lastName="
+ lastName + ", standard=" + standard + ", phoneNumber=" + phoneNumber + ", emailId=" + emailId
+ ", fathersName=" + fathersName + ", mothersName=" + mothersName + ", address=" + address + "]";
}
}
/**DTO**/
package com.akshay.spring.dtos;
public class StudentDTO {
Long id;
String rollNumber;
String firstName;
String lastName;
String standard;
String phoneNumber;
String emailId;
String fathersName;
String mothersName;
String address;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRollNumber() {
return rollNumber;
}
public void setRollNumber(String rollNumber) {
this.rollNumber = rollNumber;
}
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 getStandard() {
return standard;
}
public void setStandard(String standard) {
this.standard = standard;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getFathersName() {
return fathersName;
}
public void setFathersName(String fathersName) {
this.fathersName = fathersName;
}
public String getMothersName() {
return mothersName;
}
public void setMothersName(String mothersName) {
this.mothersName = mothersName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
#Override
public String toString() {
return "StudentDTO [id=" + id + ", rollNumber=" + rollNumber + ", firstName=" + firstName + ", lastName="
+ lastName + ", standard=" + standard + ", phoneNumber=" + phoneNumber + ", emailId=" + emailId
+ ", fathersName=" + fathersName + ", mothersName=" + mothersName + ", address=" + address + "]";
}
}
/**JPA repository**/
package com.akshay.spring.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.akshay.spring.models.StudentModel;
public interface StudentRepository extends JpaRepository<StudentModel, Long> {
StudentModel getStudentByRollNumber(String rollNumber);
void deleteStudentByRollNumber(String rollNumber);
}
I think your request mapping needs to be : http://localhost:8081/api/getAllStudents
Related
I am trying to figure out how to find and return all Books that are associated with a specific author name.
{
"bookId": 5,
"bookName": "test2",
"publishYear": 2022,
"publisher": "test2",
"authors": [
{
"id": 5,
"name": "Heny",
"surname": "Blakc"
},
{
"id": 6,
"name": "Garyy",
"surname": "Harrys"
}
]
}
I want to return all books where Garyy is the author.
I am using Spring Boot + Postgres SQL OneToMany annotation.
Would appreciate any suggestions.
AuthorController:
package com.example.demo.controller;
import com.example.demo.entity.AuthorEntity;
import com.example.demo.repository.AuthorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
#RequestMapping("/author")
public class AuthorController {
#Autowired
AuthorRepository authorRepository;
#GetMapping("/all")
public List<AuthorEntity> author(){
return authorRepository.findAll();
}
#PostMapping("/create")
public AuthorEntity createAuthor(#RequestBody AuthorEntity author){
AuthorEntity savedAuthor = authorRepository.save(author);
return savedAuthor;
}
#GetMapping("/find/{author}")
public List<AuthorEntity> findAuthor(#PathVariable(value = "author") String name){
return authorRepository.findByName(name);
}
}
BookController:
package com.example.demo.controller;
import com.example.demo.entity.BookEntity;
import com.example.demo.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
#RequestMapping("/book")
public class BookController {
#Autowired
private BookRepository bookRepository;
#GetMapping("/all")
public List<BookEntity> getAllBooks(){
List<BookEntity> allBookList = bookRepository.findAll();
return allBookList;
}
#GetMapping("/findBook/{name}")
public List<BookEntity> getBookByName(#PathVariable(value = "name")String bookName)
{
return bookRepository.findByBookName(bookName);
}
#GetMapping("/year/{year}")
public List<BookEntity> getBookByYear(#PathVariable(value = "year")Integer year)
{
return bookRepository.findByPublishYear(year);
}
#GetMapping("/publisher/{publisher}")
public List<BookEntity> getBookByPublisher(#PathVariable(value = "publisher")String publisher)
{
return bookRepository.findByPublisher(publisher);
}
#PostMapping("/create-book")
public BookEntity createBook (#RequestBody BookEntity book){
BookEntity savedBook = bookRepository.save(book);
return savedBook;
}
}
AuthorEntity:
package com.example.demo.entity;
import javax.persistence.*;
#Entity
#Table(name = "authors")
public class AuthorEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(name = "name", nullable = false)
private String name;
#Column(name = "surname",nullable = false)
private String surname;
#ManyToOne(fetch =FetchType.LAZY)
private BookEntity books;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
#Override
public String toString() {
return "AuthorEntity{" +
"id=" + id +
", name='" + name + '\'' +
", surname='" + surname + '\'' +
", books=" + books +
'}';
}
}
BookEntity:
package com.example.demo.entity;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "books")
public class BookEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer bookId;
#Column(name = "book_name", nullable = false)
private String bookName;
#Column(name = "publish_year",nullable = false)
private Integer publishYear;
#Column(name = "publisher",nullable = false)
private String publisher;
#OneToMany(targetEntity = AuthorEntity.class, cascade = CascadeType.ALL)
private List<AuthorEntity> authors;
public List<AuthorEntity> getAuthors() {
return authors;
}
public void setAuthors(List<AuthorEntity> authors) {
this.authors = authors;
}
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public Integer getPublishYear() {
return publishYear;
}
public void setPublishYear(Integer publishYear) {
this.publishYear = publishYear;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
#Override
public String toString() {
return "BookEntity{" +
"bookId=" + bookId +
", bookName='" + bookName + '\'' +
", publishYear=" + publishYear +
", publisher='" + publisher + '\'' +
", authors=" + authors +
'}';
}
}
AuthorRepository:
package com.example.demo.repository;
import com.example.demo.entity.AuthorEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface AuthorRepository extends JpaRepository<AuthorEntity, Integer> {
List<AuthorEntity> findByName(String name);
}
BookRepository:
package com.example.demo.repository;
import com.example.demo.entity.BookEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface BookRepository extends JpaRepository<BookEntity, Integer> {
public List<BookEntity> findByBookName(String bookName);
public List<BookEntity> findByPublishYear(Integer year);
public List<BookEntity> findByPublisher(String publisher);
}
There are multiple way to do so , one approach is to use forEach and filter in java itself like
List<BookeEntity> books = getBooks();
books.forEach(e->{
List<AuthorEntity> al= e.getAuthors().stream().filter(ee->ee.getName().equals("Garyy")).collect(Collectors.toList());
e.setAuthors(al);
});
Your database design was wrong. Reality:
1 author wrote one or many books,
1 book wrote by one or many authors.
Therefore, you need an table author-book to convert relationship many-many to 2 relationships: one-many, many-one.
You can see https://www.stat.auckland.ac.nz/~paul/ItDT/HTML/node42.html section 5.6.3.2 Relationships
My application fails to start because spring can't see bean.
I'm trying to run mu application and add created user to db. I have no idea how to create missing bean. I found that there must be annotation #Repository above interface, so I placed it, but it still doesn't work.
User:
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDate;
#Entity
public class User implements Serializable, UserInterface {
private static final long serialVersionUID = 8062231146287834334L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column
private String login;
#Column
private String password;
#Column
private String email;
#Column
private Long phoneNumber;
#Column
private String firstName;
#Column
private String lastName;
#Column
private LocalDate dateOfBirth;
#Column
private String address;
#Column
private String city;
#Column
private String zipCode;
public User() {
//constructor for hibernate
}
private User(String login, String password, String email, Long phoneNumber, String firstName,
String lastName, LocalDate dateOfBirth, String address, String city, String zipCode) {
this.login = login;
this.password = password;
this.email = email;
this.phoneNumber = phoneNumber;
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
this.address = address;
this.city = city;
this.zipCode = zipCode;
}
#Override
public String getLogin() {
return login;
}
#Override
public String getPassword() {
return password;
}
#Override
public String getEmail() {
return email;
}
#Override
public Long getPhoneNumber() {
return phoneNumber;
}
#Override
public String getFirstName() {
return firstName;
}
#Override
public String getLastName() {
return lastName;
}
#Override
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
#Override
public String getAddress() {
return address;
}
#Override
public String getCity() {
return city;
}
#Override
public String getZipCode() {
return zipCode;
}
#Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
", phoneNumber=" + phoneNumber +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", dateOfBirth=" + dateOfBirth +
", address='" + address + '\'' +
", city='" + city + '\'' +
", zipCode='" + zipCode + '\'' +
'}';
}
public static class UserBuilder {
private String login;
private String password;
private String email;
private Long phoneNumber;
private String firstName;
private String lastName;
private LocalDate dateOfBirth;
private String address;
private String city;
private String zipCode;
public UserBuilder setUserLogin(String login) {
this.login = login;
return this;
}
public UserBuilder setUserPassword(String password) {
this.password = password;
return this;
}
public UserBuilder setUserEmail(String email) {
this.email = email;
return this;
}
public UserBuilder setUserPhoneNumber(Long phoneNumber) {
this.phoneNumber = phoneNumber;
return this;
}
public UserBuilder setUserFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public UserBuilder setUserLastName(String lastName) {
this.lastName = lastName;
return this;
}
public UserBuilder setUserDateOfBirth(String dateOfBirth) {
this.dateOfBirth = LocalDate.parse(dateOfBirth);
return this;
}
public UserBuilder setUserAddress(String address) {
this.address = address;
return this;
}
public UserBuilder setUserCity(String city) {
this.city = city;
return this;
}
public UserBuilder setUserZipCode(String zipCode) {
this.zipCode = zipCode;
return this;
}
public User build() {
boolean isAllFielsdAreFull = login != null && password != null && email != null
&& phoneNumber != null && firstName != null
&& lastName != null && dateOfBirth != null && address != null
&& city != null && zipCode != null;
if (isAllFielsdAreFull) {
return new User(login, password, email, phoneNumber, firstName, lastName, dateOfBirth, address, city, zipCode);
} else {
throw new RuntimeException("Some fields are null!");
}
}
}
}
UserRepo:
package wawer.kamil.library;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import wawer.kamil.library.domain.User;
#Repository
public interface UserRepo extends JpaRepository<User, Long> {
}
Controller:
package wawer.kamil.library;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Controller;
import wawer.kamil.library.domain.User;
#Controller
public class Start {
private UserRepo userRepo;
#Autowired
public Start(UserRepo userRepo) {
this.userRepo = userRepo;
}
#EventListener(ApplicationReadyEvent.class)
public void run() {
User user = new User.UserBuilder()
.setUserLogin("Mareczek")
.setUserPassword("Mareczek3#")
.setUserEmail("mareczek#gmail.com")
.setUserPhoneNumber(515791468L)
.setUserFirstName("Marek")
.setUserLastName("Kowalski")
.setUserDateOfBirth("1990-12-12")
.setUserAddress("Kowalska 12")
.setUserCity("Lublin")
.setUserZipCode("20-123")
.build();
userRepo.save(user);
}
}
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://0.0.0.0:32768/library
?serverTimezone=Europe/Warsaw
spring.datasource.username=root
spring.datasource.password=root
Main class:
package wawer.kamil.library;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class LibraryApplication {
public static void main(String[] args) {
SpringApplication.run(LibraryApplication.class, args);
}
}
Error Logs:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-06-10 11:19:30.771 ERROR 6282 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in wawer.kamil.library.Start required a bean of type 'wawer.kamil.library.UserRepo' that could not be found.
Action:
Consider defining a bean of type 'wawer.kamil.library.UserRepo' in your configuration.
Process finished with exit code 1
I would like to run my application, and add user to db.
You need to enable repositories
#SpringBootApplication
#EnableJpaRepositories // this will fix the issue
public class LibraryApplication {
public static void main(String[] args) {
SpringApplication.run(LibraryApplication.class, args);
}
I am trying to map the pojo class to my mysql database, but i always get an error when i want to get users:
java.sql.SQLSyntaxErrorException: Unknown column 'user0_.Report_id' in 'field list'
This is how the database looks like this:
database
And these are the pojo classes:
Order
package com.latinon.reportator.model;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* #author sistemas
*
*/
#Entity
#Table(name="Order")
public class Order {
private Integer id;
private Date startDate;
private Date endDate;
private BigInteger imperssions;
private String zone;
private int monetization;
private String adUnit;
private String unit;
private String adFormat;
private Double totalAmount;
private Integer platform;
private Double value;
private String valueMesure;
private Set<Device> orderDevices = new HashSet<Device>(0);
private Set<Product> orderProducts = new HashSet<Product>(0);
private Set<Report> orderReport = new HashSet<Report>(0);
private Set<User> orderUsers = new HashSet<User>(0);
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="Order_id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Temporal(TemporalType.DATE)
#Column(name="Order_start_date", nullable=false)
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
#Temporal(TemporalType.DATE)
#Column(name="Order_end_date")
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
#Column(name="Order_impressions", nullable=false)
public BigInteger getImperssions() {
return imperssions;
}
public void setImperssions(BigInteger imperssions) {
this.imperssions = imperssions;
}
#Column(name="Order_zone")
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
#Column(name="Order_monetization",nullable=false)
public int getMonetization() {
return monetization;
}
public void setMonetization(int monetization) {
this.monetization = monetization;
}
#Column(name="Order_ad_unit")
public String getAdUnit() {
return adUnit;
}
public void setAdUnit(String adUnit) {
this.adUnit = adUnit;
}
#Column(name="Order_unit",nullable=false)
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
#Column(name="Order_ad_format", nullable=false)
public String getAdFormat() {
return adFormat;
}
public void setAdFormat(String adFormat) {
this.adFormat = adFormat;
}
#Column(name="Order_total_amount", nullable=false)
public Double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(Double totalAmount) {
this.totalAmount = totalAmount;
}
#Column(name="Order_platform", nullable=false)
public Integer getPlatform() {
return platform;
}
public void setPlatform(Integer platform) {
this.platform = platform;
}
#Column(name="Order_value", nullable=false)
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
#Column(name="Order_value_mesure",nullable=false)
public String getValueMesure() {
return valueMesure;
}
public void setValueMesure(String valueMesure) {
this.valueMesure = valueMesure;
}
#ManyToMany(fetch=FetchType.LAZY)
#JoinTable(name="Order_Device", joinColumns={
#JoinColumn(name="Order_Device_Order_id")
})
public Set<Device> getOrderDevices() {
return orderDevices;
}
public void setOrderDevices(Set<Device> orderDevices) {
this.orderDevices = orderDevices;
}
#ManyToMany(fetch=FetchType.LAZY)
#JoinTable(name="Order_Product", joinColumns={
#JoinColumn(name="Order_Product_Order_id")
})
public Set<Product> getOrderProducts() {
return orderProducts;
}
public void setOrderProducts(Set<Product> orderProducts) {
this.orderProducts = orderProducts;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "orderId")
public Set<Report> getOrderReport() {
return orderReport;
}
public void setOrderReport(Set<Report> orderReport) {
this.orderReport = orderReport;
}
#ManyToMany(fetch=FetchType.LAZY, mappedBy="userOrders")
public Set<User> getOrderUsers() {
return orderUsers;
}
public void setOrderUsers(Set<User> orderUsers) {
this.orderUsers = orderUsers;
}
#Override
public String toString() {
return "Order [id=" + id + ", startDate=" + startDate + ", endDate=" + endDate + ", imperssions=" + imperssions
+ ", zone=" + zone + ", monetization=" + monetization + ", adUnit=" + adUnit + ", unit=" + unit
+ ", adFormat=" + adFormat + ", totalAmount=" + totalAmount + ", platform=" + platform + ", value="
+ value + ", valueMesure=" + valueMesure + "]";
}
}
Report pojo:
package com.latinon.reportator.model;
import java.math.BigInteger;
import java.util.Date;
import javax.persistence.*;
/**
* #author sistemas
*
*/
#Entity
#Table(name="User")
public class Report {
private Integer id;
private BigInteger impressions;
private Date date;
private Double grossRevenue;
private Double latinonRevenue;
private Double userRevenue;
private Double fillRate;
private BigInteger completion25;
private BigInteger completion50;
private BigInteger completion75;
private BigInteger completion100;
private BigInteger requests;
private String zone;
private Double cpm;
private Order orderId;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="Report_id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name="Report_impressions")
public BigInteger getImpressions() {
return impressions;
}
public void setImpressions(BigInteger impressions) {
this.impressions = impressions;
}
#Temporal(TemporalType.DATE)
#Column(name="Report_date")
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#Column(name="Report_gross_revenue")
public Double getGrossRevenue() {
return grossRevenue;
}
public void setGrossRevenue(Double grossRevenue) {
this.grossRevenue = grossRevenue;
}
#Column(name="Report_latinon_revenue")
public Double getLatinonRevenue() {
return latinonRevenue;
}
public void setLatinonRevenue(Double latinonRevenue) {
this.latinonRevenue = latinonRevenue;
}
#Column(name="Report_user_revenue")
public Double getUserRevenue() {
return userRevenue;
}
public void setUserRevenue(Double userRevenue) {
this.userRevenue = userRevenue;
}
#Column(name="Report_fill_rate")
public Double getFillRate() {
return fillRate;
}
public void setFillRate(Double fillRate) {
this.fillRate = fillRate;
}
#Column(name="Report_completion_25")
public BigInteger getCompletion25() {
return completion25;
}
public void setCompletion25(BigInteger completion25) {
this.completion25 = completion25;
}
#Column(name="Report_completion_50")
public BigInteger getCompletion50() {
return completion50;
}
public void setCompletion50(BigInteger completion50) {
this.completion50 = completion50;
}
#Column(name="Report_completion_75")
public BigInteger getCompletion75() {
return completion75;
}
public void setCompletion75(BigInteger completion75) {
this.completion75 = completion75;
}
#Column(name="Report_completion_100")
public BigInteger getCompletion100() {
return completion100;
}
public void setCompletion100(BigInteger completion100) {
this.completion100 = completion100;
}
#Column(name="Report_request")
public BigInteger getRequests() {
return requests;
}
public void setRequests(BigInteger requests) {
this.requests = requests;
}
#Column(name="Report_zone")
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
#Column(name="Report_cpm")
public Double getCpm() {
return cpm;
}
public void setCpm(Double cpm) {
this.cpm = cpm;
}
#ManyToOne
#JoinColumn(name="Order_Order_id")
public Order getOrderId() {
return orderId;
}
public void setOrderId(Order orderId) {
this.orderId = orderId;
}
#Override
public String toString() {
return "Report [id=" + id + ", impressions=" + impressions + ", date=" + date + ", grossRevenue=" + grossRevenue
+ ", latinonRevenue=" + latinonRevenue + ", userRevenue=" + userRevenue + ", fillRate=" + fillRate
+ ", completion25=" + completion25 + ", completion50=" + completion50 + ", completion75=" + completion75
+ ", completion100=" + completion100 + ", requests=" + requests + ", zone=" + zone + ", cpm=" + cpm
+ ", orderId=" + orderId + "]";
}
}
User pojo:
package com.latinon.reportator.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="User")
#Inheritance(strategy=InheritanceType.JOINED)
public class User {
private int id;
private String login;
private String password;
private String email;
private Set<Domain> userDomains = new HashSet<Domain>(0);
private Set<Order> userOrders = new HashSet<Order>(0);
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="User_id",nullable=false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="User_login", length=45)
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
#Column(name="User_password", length=45)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name="User_mail", length=45)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#ManyToMany(fetch=FetchType.LAZY)
public Set<Domain> getUserDomains() {
return userDomains;
}
public void setUserDomains(Set<Domain> userDomains) {
this.userDomains = userDomains;
}
#ManyToMany(fetch=FetchType.LAZY)
public Set<Order> getUserOrders() {
return userOrders;
}
public void setUserOrders(Set<Order> userOrders) {
this.userOrders = userOrders;
}
#Override
public String toString() {
return "User [id=" + id + ", login=" + login + ", password=" + password + ", email=" + email + "]";
}
}
You have in you Report class #Table(name="User"). is this a typo?
I have spring application everytime I run and I try to login I got the following excpetion after login
java.lang.IllegalStateException: Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)
at com.emc.fleet.domain.User_Roo_Jpa_ActiveRecord.ajc$interMethod$com_emc_fleet_domain_User_Roo_Jpa_ActiveRecord$com_emc_fleet_domain_User$entityManager(User_Roo_Jpa_ActiveRecord.aj:19)
at com.emc.fleet.domain.User.entityManager(User.java:1)
at com.emc.fleet.domain.User_Roo_Jpa_ActiveRecord.ajc$interMethodDispatch1$com_emc_fleet_domain_User_Roo_Jpa_ActiveRecord$com_emc_fleet_domain_User$entityManager(User_Roo_Jpa_ActiveRecord.aj)
at com.emc.fleet.domain.User_Roo_Finder.ajc$interMethod$com_emc_fleet_domain_User_Roo_Finder$com_emc_fleet_domain_User$findUsersByUserIdEquals(User_Roo_Finder.aj:47)
at com.emc.fleet.domain.User.findUsersByUserIdEquals(User.java:1)
I have read many STO questions and checked all answers none of them succeded
this is my user class
package com.emc.fleet.domain
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;
#RooJavaBean
#RooToString
#RooJpaActiveRecord(finders = { "findUsersByEmailLike", "findUsersByUserIdEquals", "findUsersByCostCenter", "findUsersByDepartmet" })
public class User {
#Id
#GeneratedValue
private Long id;
#NotEmpty
#NotNull
private String firstName;
#NotEmpty
#NotNull
private String lastName;
#NotNull
private Long userId;
#Email
#NotNull
private String email;
#NotNull
private String address;
#NotNull
private String district;
private String deskPhone;
#NotEmpty
#NotNull
private String mobile;
#NotEmpty
#NotNull
private String password;
#Transient
private String retypePassword;
#OneToOne
private Department departmet;
#OneToOne
#JoinColumn(name = "cost_center")
private CostCenter costCenter;
private String managerName;
private boolean enabled = true;
#Enumerated(EnumType.STRING)
private Roles role = Roles.ROLE_USER;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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 Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getDeskPhone() {
return deskPhone;
}
public void setDeskPhone(String deskPhone) {
this.deskPhone = deskPhone;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRetypePassword() {
return retypePassword;
}
public void setRetypePassword(String retypePassword) {
this.retypePassword = retypePassword;
}
public Department getDepartmet() {
return departmet;
}
public void setDepartmet(Department departmet) {
this.departmet = departmet;
}
public CostCenter getCostCenter() {
return costCenter;
}
public void setCostCenter(CostCenter costCenter) {
this.costCenter = costCenter;
}
public String getManagerName() {
return managerName;
}
public void setManagerName(String managerName) {
this.managerName = managerName;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Roles getRole() {
return role;
}
public void setRole(Roles role) {
this.role = role;
}
#Override
public String toString() {
return getEmail() + " - " + getUserId();
}
}
and this the user_Roo_Configurable file
package com.emc.fleet.domain;
import com.emc.fleet.domain.User;
import org.springframework.beans.factory.annotation.Configurable;
privileged aspect User_Roo_Configurable {
declare #type: User: #Configurable;
}
any clue ?
I get following exception when I try to display data from EmergencyContact. SurveyData and EmergencyData are related by OneToMany. I'm able to persist the data but not able to retrieve it back.
I want to give a SurveyID as input and get back emergency contacts of that survey. I verified all my setter and getter methods and they look okay. I'm unable to trace where I made mistake. Any help is appreciated.
16:53:42,029 ERROR [stderr] (http-localhost-127.0.0.1-8080-1) Caused by: org.hibernate.QueryException: could not resolve property: survey_id of: masonsurveyejb.businesslogic.EmergencyContact [SELECT emc FROM masonsurveyejb.businesslogic.EmergencyContact emc WHERE emc.survey_id = 11]
My query string looks like below. I receive survey_id variable value as an argument in this method.
"SELECT emc FROM EmergencyContact emc WHERE emc.survey_id = " + survey_id
Following are my EmergencyContact and SurveyData classes
package masonsurveyejb.businesslogic;
import java.io.Serializable;
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.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name = "EmergencyData")
public class EmergencyContact implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name = "EMERGENCY_SEQUENCE", sequenceName = "Survey_Seq", initialValue = 100, allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "EMERGENCY_SEQUENCE")
private Integer contactId;
#Column(name = "Name")
private String emName;
#Column(name = "Phone")
private String emPhone;
#Column(name = "Email")
private String emEmail;
#ManyToOne
#JoinColumn(name = "SurveyID")
private SurveyData surveyData;
public Integer getContactId() {
return contactId;
}
public void setContactId(Integer contactId) {
this.contactId = contactId;
}
public SurveyData getSurveyData() {
return surveyData;
}
public void setSurveyData(SurveyData surveyData) {
this.surveyData = surveyData;
}
public String getEmName() {
return emName;
}
public void setEmName(String emName) {
this.emName = emName;
}
public String getEmPhone() {
return emPhone;
}
public void setEmPhone(String emPhone) {
this.emPhone = emPhone;
}
public String getEmEmail() {
return emEmail;
}
public void setEmEmail(String emEmail) {
this.emEmail = emEmail;
}
}
///////////////////////////////////////////////////////////////////////////////
// #filename: Student.java
// #description: This file is the a simple class which is used as a model
// object for Student.
//
// Modification History
// Date Author Change Reason
// ==== ====== =============
// 2014-02-20 Santosh K Tadikonda Initial Creation
//
///////////////////////////////////////////////////////////////////////////////
package masonsurveyejb.businesslogic;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
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;
#Entity
public class SurveyData {
#Id
#SequenceGenerator(name = "SURVEY_SEQUENCE", sequenceName = "Survey_Seq", initialValue = 100, allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SURVEY_SEQUENCE")
#Column(name = "SurveyID")
private Integer survey_id;
private String firstname;
private String lastname;
private String address;
private String city;
private String state;
private String zipcode;
private String telephone;
private String email;
private String surveydate;
#Column(name = "Likes")
private String chklike;
#Column(name = "Know")
private String radioknow;
private String recommend;
private String raffle;
private String comments;
#OneToMany(mappedBy = "surveyData", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<EmergencyContact> emContacts;
public List<EmergencyContact> getEmContacts() {
return emContacts;
}
public void setEmContacts(List<EmergencyContact> emContacts) {
this.emContacts = emContacts;
}
public Integer getSurvey_id() {
return survey_id;
}
public void setSurvey_id(Integer survey_id) {
this.survey_id = survey_id;
}
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 getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
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 String getSurveydate() {
return surveydate;
}
public void setSurveydate(String surveydate) {
this.surveydate = surveydate;
}
public String getChklike() {
return chklike;
}
public void setChklike(String chklike) {
this.chklike = chklike;
}
public String getRadioknow() {
return radioknow;
}
public void setRadioknow(String radioknow) {
this.radioknow = radioknow;
}
public String getRecommend() {
return recommend;
}
public void setRecommend(String recommend) {
this.recommend = recommend;
}
public String getRaffle() {
return raffle;
}
public void setRaffle(String raffle) {
this.raffle = raffle;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String toString() {
String studentString;
studentString = getSurvey_id() + ";" +getFirstname() + ";" + getLastname() + ";"
+ getAddress() + ";" + getCity() + ";" + getState() + ";"
+ getZipcode() + ";" + getTelephone() + ";" + getEmail() + ";"
+ getSurveydate() + ";" + getChklike() + ";" + getRadioknow()
+ ";" + getRecommend() + ";" + getRaffle() + ";"
+ getComments();
return studentString;
}
}
Following is the method from which I make query
#Override
public ArrayList<EmergencyContact> GetEmergencyContacts(String survey_id) {
try {
if (survey_id == null || survey_id.length() == 0) {
System.out.println("Received a null or empty survey ID.");
return null;
}
System.out.println("Getting emergency contacts for " + survey_id);
String queryStr = "SELECT emc FROM EmergencyContact emc WHERE emc.survey_id = "
+ survey_id;
Query query = entityManager.createQuery(queryStr);
List resultList = query.getResultList();
if (resultList != null && resultList.size() > 0) {
ArrayList<EmergencyContact> emList = new ArrayList<EmergencyContact>();
for (Object result : resultList) {
EmergencyContact emc = new EmergencyContact();
emc = (EmergencyContact) result;
emList.add(emc);
}
return emList;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
You receiving the exception because entity 'EmergencyContact' has no property named 'survey_id'.
Your query should be:
String queryStr = "SELECT emc FROM EmergencyContact emc WHERE emc.surveyData.survey_id = :id";
Query query = entityManager.createQuery(queryStr).setParameter("id", survey_id);
List resultList = query.getResultList();
Please consider 2 things:
Use property names in JPQL query (surveyData.survey_id)
It's better to set query parameters with special method, "setParameter"