Spring Boot Hibernate one to many. Lazy many not written to database - spring-boot

I have two entities. Person (one) and Contactdetails (many).
Contactdetails are lazy loading. I have no problem with creating a new Person and get it written into the database. For my test I use the MySQL database installed locally filled up with dummy data. I run kind of integration test.
In my test code I use #Transactional annotation in order to stay inside one session where I fetch a Person, create a new Contacdetails, connect them together and then save the Person, which will cascade save the Contactdetails too. In theory...
Contactdetails is not written to the database. Interestingly, if I write to console all Contactdetails inside the #Transactional annotated test method, I see the new Contactdetails created. As soon es I leave this test method, this freshly created Contactdetails is no more visible.
My Entities are as follows:
Person:
package com.szivalaszlo.contracts.landon.data.entity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.time.LocalDate;
import java.util.Objects;
#Entity
#Table(name="person")
public class Person {
private static Logger logger = LogManager.getLogger();
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "date_of_birth")
private LocalDate dateOfBirth;
#Column(name = "first_name_mother")
private String firstNameMother;
#Column(name = "last_name_mother")
private String lastNameMother;
#OneToMany(fetch=FetchType.LAZY, mappedBy = "person", cascade = CascadeType.ALL) // refers to person attribute of Contactdetails class
private List<Contactdetails> contactdetails;
#ManyToMany(fetch=FetchType.LAZY)
#JoinTable(name = "buyer_contract",
joinColumns = #JoinColumn(name = "person_buyerid"),
inverseJoinColumns = #JoinColumn(name = "contractid"))
List<Contract> buyerContracts;
#ManyToMany(fetch=FetchType.LAZY)
#JoinTable(name = "seller_contract",
joinColumns = #JoinColumn(name = "person_sellerid"),
inverseJoinColumns = #JoinColumn(name = "contractid"))
List<Contract> sellerContracts;
public Person(){
}
public Person(String firstName, String lastName, String dateOfBirth, String firstNameMother, String lastNameMother) {
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = LocalDate.parse(dateOfBirth);
this.firstNameMother = firstNameMother;
this.lastNameMother = lastNameMother;
}
public int getId() {
return id;
}
public void setId(int 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 LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getFirstNameMother() {
return firstNameMother;
}
public void setFirstNameMother(String firstNameMother) {
this.firstNameMother = firstNameMother;
}
public String getLastNameMother() {
return lastNameMother;
}
public void setLastNameMother(String lastNameMother) {
this.lastNameMother = lastNameMother;
}
public List<Contactdetails> getContactdetails() {
return contactdetails;
}
public void addContactdetail(Contactdetails contactdetail){
if(null == contactdetails){
contactdetails = new ArrayList<Contactdetails>();
}
contactdetails.add(contactdetail);
}
public String getStringForEqualsCheck(){
return firstName+lastName+dateOfBirth.toString()+firstNameMother+lastNameMother;
}
#Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (!(obj instanceof Person))
return false;
if (obj == this)
return true;
return this.getStringForEqualsCheck().equals(((Person) obj).getStringForEqualsCheck());
}
#Override
public int hashCode() {
return Objects.hash(firstName, lastName, dateOfBirth, firstNameMother, lastNameMother);
}
#Override
public String toString() {
return "Person{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", dateOfBirth=" + dateOfBirth +
", firstNameMother='" + firstNameMother + '\'' +
", lastNameMother='" + lastNameMother + '\'' +
'}';
}
}
Contactdetails:
package com.szivalaszlo.contracts.landon.data.entity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.persistence.*;
import java.util.Objects;
#Entity
#Table(name="contactdetails")
public class Contactdetails {
private static Logger logger = LogManager.getLogger();
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "address")
private String address;
#Column(name = "email")
private String email;
#Column(name = "phone")
private String phone;
#ManyToOne
#JoinColumn(name = "personid", nullable = false)
private Person person;
public Contactdetails(){
}
public Contactdetails(String address, String email, String phone) {
this.address = address;
this.email = email;
this.phone = phone;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
logger.debug("Person is set for contactdetail: " + this.toString() + " person: " + this.person.toString());
}
public String getStringForEqualsCheck(){
return address+email+phone;
}
#Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (!(obj instanceof Contactdetails))
return false;
if (obj == this)
return true;
return this.getStringForEqualsCheck().equals(((Contactdetails) obj).getStringForEqualsCheck());
}
#Override
public int hashCode() {
return Objects.hash(address, email, phone);
}
#Override
public String toString() {
return "Contactdetails{" +
"id=" + id +
", address='" + address + '\'' +
", email='" + email + '\'' +
", phone='" + phone + '\'' +
", person=" + person +
'}';
}
}
Service class:
package com.szivalaszlo.contracts.landon.business.domain;
import com.szivalaszlo.contracts.landon.data.entity.Contactdetails;
import com.szivalaszlo.contracts.landon.data.entity.Person;
import com.szivalaszlo.contracts.landon.data.repository.ContactdetailsRepository;
import com.szivalaszlo.contracts.landon.data.repository.PersonRepository;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.List;
#Service
public class PersonService {
private static Logger logger = LogManager.getLogger();
private PersonRepository personRepository;
private ContactdetailsRepository contactdetailsRepository;
#Autowired
public PersonService(PersonRepository personRepository, ContactdetailsRepository contactdetailsRepository){
this.personRepository = personRepository;
this.contactdetailsRepository = contactdetailsRepository;
}
public int createPerson(String firstName, String lastName, String dateOfBirth, String firstNameMother, String lastNameMother){
Person person = new Person(firstName, lastName, dateOfBirth, firstNameMother, lastNameMother);
if(personAlreadyExistsInDb(person)){
logger.debug("Same person already found in Db. Person: " + person.toString());
return -1;
}else{
personRepository.save(person);
return person.getId();
}
}
private boolean personAlreadyExistsInDb(Person person){
HashSet<Person> allPersonFromDb = personRepository.findAll();
if (allPersonFromDb.contains(person)){
return true;
}else{
return false;
}
}
public void createContactdetailsForPerson(Person person, String address, String email, String phone){
Contactdetails contactdetails = new Contactdetails(address, email, phone);
if(contactdetailsAlreadyExistForPerson(contactdetails, person)){
logger.debug("Same contactdetail for person already found " + person.toString() + " " + contactdetails.toString());
} else{
contactdetails.setPerson(person);
person.addContactdetail(contactdetails);
contactdetailsRepository.save(contactdetails);
personRepository.save(person);
}
}
private boolean contactdetailsAlreadyExistForPerson(Contactdetails contactdetails, Person person){
List<Contactdetails> allContactdetailsForPersonFromDb = person.getContactdetails();
if(null == allContactdetailsForPersonFromDb || allContactdetailsForPersonFromDb.size() == 0){
return false;
}
if(!allContactdetailsForPersonFromDb.contains(contactdetails)){
return false;
}
return true;
}
}
Test class:
package com.szivalaszlo.contracts;
import com.szivalaszlo.contracts.landon.business.domain.PersonService;
import com.szivalaszlo.contracts.landon.data.entity.Contactdetails;
import com.szivalaszlo.contracts.landon.data.entity.Person;
import com.szivalaszlo.contracts.landon.data.repository.ContactdetailsRepository;
import com.szivalaszlo.contracts.landon.data.repository.PersonRepository;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Random;
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
public class PersonServiceTest_ {
private static Logger logger = LogManager.getLogger();
#Autowired
private PersonRepository personRepository;
#Autowired
private ContactdetailsRepository contactdetailsRepository;
Random rand = new Random();
int randomNumber = rand.nextInt(899)+100;
private String address = "test address street 1 in City "+randomNumber;
private String email = "testemail#exmaple.com " +randomNumber;
private String phone = "+41 12 345 78 90 " +randomNumber;
#Test
#Transactional(propagation = Propagation.REQUIRED)
public void it_should_save_contactdetail_to_person(){
PersonService testPersonService = new PersonService(personRepository, contactdetailsRepository);
Person testPerson = personRepository.findById(179); //I have an id# 179 Person in the database fully detailed.
testPersonService.createContactdetailsForPerson(testPerson, address, email, phone);
List<Contactdetails> allStoredContactdetailsinDB = contactdetailsRepository.findAll();
allStoredContactdetailsinDB.forEach(item->System.out.println(item));
}
}
The test runs with no error. I see the following output in the console:
Bradlystad, ND 98886-5789', email='maverick85#example.com', phone='464-812-3618', person=Person{id=98, firstName='Eldridge', lastName='Reichel', dateOfBirth=1981-08-07, firstNameMother='Brianne', lastNameMother='Ryan'}}
Contactdetails{id=99, address='569 Langosh Turnpike Suite 235
East Archibald, FL 43208-3081', email='spouros#example.org', phone='08976297815', person=Person{id=99, firstName='Myrtie', lastName='Graham', dateOfBirth=1982-01-19, firstNameMother='Libby', lastNameMother='Veum'}}
Contactdetails{id=100, address='010 Pfeffer Islands
Kiehnside, FL 25044-1157', email='paucek.grover#example.com', phone='1-157-850-0688x390', person=Person{id=100, firstName='Katheryn', lastName='Hoppe', dateOfBirth=2009-06-22, firstNameMother='Virginie', lastNameMother='Donnelly'}}
Contactdetails{id=106, address='test address street 1 in City 623', email='testemail#exmaple.com 623', phone='+41 12 345 78 90 623', person=Person{id=179, firstName='TestJhonFirst808', lastName='TestSmithLast808', dateOfBirth=1990-11-11, firstNameMother='TestJackieMotherFirst808', lastNameMother='TestSmithMotherLast808'}}
The interesting part is the last line which shows, that the Contactdetails is created in the db with id#106.
When I query the database after the test is run, I don't see the new line in the table.

By default, test transactions will be automatically rolled back after
completion of the test; however, transactional commit and rollback
behavior can be configured declaratively via the #Commit and #Rollback
annotations
Add the following annotation to your test:
#Rollback(false)

Related

Spring Boot Rest API Issues

I'm trying to implement a Spring Boot Rest API using Spring Data Jdbc with H2 Database.
This is a microservice, and I'm trying to send a POST request to the microservice from an angular app. I know my POST is working correctly from Angular. Inside of microservice, I am trying to save the POST request to a local H2 database.
This should be relatively straight forward based on documentation I've read online, but I am getting error messages. Any help would be greatly appreciated. Here are the files I have setup inside my spring boot microservice (titled 'order'):
OrderController.java:
package com.clothingfly.order;
import java.util.ListIterator;
import org.springframework.web.client.RestTemplate;
import com.clothingfly.order.Model.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.clothingfly.order.Model.Order;
#RestController
#CrossOrigin(origins = "http://localhost:4200")
public class OrderController {
#Autowired
TempOrderRepository orderRepository;
#PostMapping("/order")
public Order postOrder(#RequestBody Order order) {
Order _order = orderRepository.save(new Order(order.getId(), order.getAddress(), order.getPayment(), order.getItems()));
return _order;
}
}
TempOrderRepository.java:
package com.clothingfly.order;
import org.springframework.data.jpa.repository.JpaRepository;
import com.clothingfly.order.Model.Order;
public interface TempOrderRepository extends JpaRepository<Order, Long>{
}
OrderApplication.java:
package com.clothingfly.order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
And I have a model named Order.java:
package com.clothingfly.order.Model;
import java.util.List;
import javax.persistence.*;
import org.springframework.data.annotation.Id;
#Entity
#Table(name = "orders")
public class Order {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "Address")
private Address address;
#Column(name = "Payment")
private PaymentInfo payment;
#Column(name = "Items")
private List<Item> items;
#Column(name = "Error")
private String error;
public Order() {
}
public Order(long id, Address address, PaymentInfo payment, List<Item> items){
this.id = id;
this.address = address;
this.payment = payment;
this.items = items;
this.error = "";
}
public long getId() {
return id;
}
public Address getAddress() {
return address;
}
public PaymentInfo getPayment() {
return payment;
}
public List<Item> getItems() {
return items;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
}
The Order model takes in three other models:
Item.java:
package com.clothingfly.order.Model;
import javax.persistence.*;
#Entity
#Table(name = "items")
public class Item {
#Id
#GeneratedValue
#Column(name = "id")
private long id;
#Column(name = "name")
private String name;
#Column(name = "price")
private float price;
#Column(name = "imageUrl")
private String imageUrl;
#Column(name = "quantity")
private long quantity;
#Column(name = "inventory")
private long inventory;
public long getId() {
return id;
}
public String getName() {
return name;
}
public float getPrice() {
return price;
}
public long getQuantity() {
return quantity;
}
public long getInventory() {
return inventory;
}
public String getImageUrl(){
return imageUrl;
}
public void setInventory(long inventory) {
this.inventory = inventory;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(float price) {
this.price = price;
}
public void setQuantity(long quantity) {
this.quantity = quantity;
}
public Item(long id, String name, float price, long quantity, long inventory, String imageUrl) {
this.id = id;
this.name = name;
this.price = price;
this.quantity = quantity;
this.inventory = inventory;
this.imageUrl = imageUrl;
}
public Item() {
}
}
Address.java:
package com.clothingfly.order.Model;
import javax.persistence.*;
#Entity
#Table(name = "addresses")
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "firstName")
private String firstName;
#Column(name = "lastName")
private String lastName;
#Column(name = "address")
private String address;
#Column(name = "country")
private String country;
#Column(name = "apartmentNo")
private String apartmentNo;
#Column(name = "state")
private String state;
#Column(name = "city")
private String city;
#Column(name = "zipcode")
private String zipcode;
public Address() {
}
public Address(String firstName, String lastName, String address, String country, String apartmentNo, String state,
String city, String zipcode) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.country = country;
this.apartmentNo = apartmentNo;
this.state = state;
this.city = city;
this.zipcode = zipcode;
}
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 getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getApartmentNo() {
return apartmentNo;
}
public void setApartmentNo(String apartmentNo) {
this.apartmentNo = apartmentNo;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
}
PaymentInfo.java:
package com.clothingfly.order.Model;
import javax.persistence.*;
#Entity
#Table(name = "payments")
public class PaymentInfo {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "cardHolder")
private String cardHolder;
#Column(name = "cardNumber")
private String cardNumber;
#Column(name = "expirationDate")
private String expirationDate;
#Column(name = "cvv")
private String cvv;
public PaymentInfo(String cardHolder, String cardNumber, String expirationDate, String cvv) {
this.cardHolder = cardHolder;
this.cardNumber = cardNumber;
this.expirationDate = expirationDate;
this.cvv = cvv;
}
public String getCardHolder() {
return cardHolder;
}
public void setCardHolder(String cardHolder) {
this.cardHolder = cardHolder;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public String getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(String expirationDate) {
this.expirationDate = expirationDate;
}
public String getCvv() {
return cvv;
}
public void setCvv(String cvv) {
this.cvv = cvv;
}
}
I'm getting the following error when trying to run microservice:
Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: com.clothingfly.order.Model.Address, at table: orders, for columns: [org.hibernate.mapping.Column(address)]
How would I go about fixing this?
I want to be able to display all of my models inside a table.
I tried changing Address model so that it only returns a string of the city, but that seemed to cause more issues than anything.
Note, one to one will always cause you an issue, always better to implement many to one and one to many. and add it to both entities you are mapping. It will do the same job with no errors.
First, create packages, and don't place everything in one package.
create
package com.clothingfly.repo or com.clothingfly.order.repo
package com.clothingfly.controller or com.clothingfly.order.controller
Secondly, add the annotation #Repository to your repository interface
package com.clothingfly.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import com.clothingfly.order.Model.Order;
#Repository
public interface TempOrderRepository extends JpaRepository<Order, Long>{
}
Thirdly, add the annotation #EnableJpaRepositories(basePackages = "com.clothingfly.repo") to your main application class.
package com.clothingfly.order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
#EnableJpaRepositories(basePackages = "com.clothingfly.repo")
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
Lastly, this will not work correctly. Not sure what you are doing here.
#Column(name = "Address")
private Address address;
Try this:
add this in your address entity
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name="order_id", nullable = false)// add this column
// order_id in your Address database not the entity
#OnDelete(action = OnDeleteAction.CASCADE)
#JsonIgnore
private Order order;
Then, add this to your Order class.
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="order")
#OnDelete(action = OnDeleteAction.CASCADE)
#JsonIgnore
List<Address> address = new ArrayList<Address>(); // I use list cause sometimes it throws an error
// try to simply use this, if it throws expection then use the list
//private Address address;
Your Order constructor should be like:
public Order(long id, List<Address> address ...etc
Or simply
public Order(long id, Address address ...etc
Do this for all your mapped entities and don't forget to add setters and getters for all fields.
you have to tell hibernate that the Address object is coming from another table and how to join those tables, since your orders table most likely does not have a column which contains the hole address but the the address id/ primary key of the address as foreign key.
this is possible, depending if you have 1:1, 1:n, n:1 or n:m relations with the corresponding #OneToOne, #OneToMany, #ManyToOne and #ManyToMany annotations.
for your example it could be something like
#OneToOne
#JoinColumn(name = "address_id", referencedColumnName = "id")
private Address address;

JPA #OneToMany mapping inserting null values

I had a hard time with hibernate OneToMany mapping. I have googled to find the solution from morning nothing helped. Following are my code snippets.
package com.student.app.model;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonProperty;
#Entity
#Table(name = "student")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "student_id")
private long id;
#Column(name = "student_name")
private String name;
#Column(name = "student_class")
#JsonProperty("class")
private String clazz;
#Column(name = "total_marks")
private int totalMarks;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "student")
private List<Subject> subjects;
public Student() {
}
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 getClazz() {
return clazz;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
public int getTotalMarks() {
return totalMarks;
}
public void setTotalMarks(int totalMarks) {
this.totalMarks = totalMarks;
}
public List<Subject> getSubjects() {
return subjects;
}
public void setSubjects(List<Subject> subjects) {
this.subjects = subjects;
}
#Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", clazz=" + clazz + ", totalMarks=" + totalMarks
+ ", subjects=" + subjects + "]";
}
}
Subject.java
package com.student.app.model;
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.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "subject")
public class Subject {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "subject_id")
private long id;
#Column(name = "subject_name")
private String name;
#Column(name = "marks")
private String marks;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "student_id")
private Student student;
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 getMarks() {
return marks;
}
public void setMarks(String marks) {
this.marks = marks;
}
#Override
public String toString() {
return "Subject [id=" + id + ", name=" + name + ", marks=" + marks + "]";
}
}
StudentRepository.java
package com.student.app.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.student.app.model.Student;
#Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
Student findStudentByName(String name);
}
POST Mapping
#PostMapping("/students")
public ResponseEntity<?> addStudent(#RequestBody Student student) {
try {
System.out.println("Student Object is : " + student);
Student studentData = studentRepository.save(student);
if (null == studentData) {
return ResponseEntity.noContent().build();
}
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{name}")
.buildAndExpand(studentData.getName()).toUri();
return new ResponseEntity<>(location, HttpStatus.CREATED);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Post Request JSON
{
"name": "Vinod Kumar",
"class": "8th class",
"subjects": [
{
"name": "Telugu",
"marks": 85
},
{
"name": "English",
"marks": 80
},
{
"name": "Maths",
"marks": 90
}
],
"totalMarks": 580
}
Student Table data
STUDENT_ID STUDENT_CLASS STUDENT_NAME TOTAL_MARKS
1 8th class Vinod Kumar 580
Subject Table data
SUBJECT_ID MARKS SUBJECT_NAME STUDENT_ID
2 85 Telugu null
3 80 English null
4 90 Maths null
Here the issue is the STUDENT_ID column storing null values.
When you save a Student, Hibernate smart enough to insert a Student record to the database, get that record id and save all subjects of the Student with Subject.STUDENT_ID = generated student id, when the student and the subject connected to each other from both sides.
But by some reasons Hibernate doesn't connect a Subject with a Student as Java objects from the Subject side. It doesn't do for you
subject.setStudent(student)
This is the reason why Subject.STUDENT_ID = null in the database.
Before saving a student you have to assign the student to a subject for each subject, doing it in the loop
emptyStreamIfNull(student.getSubjects()).forEach(subject -> setStudent(student));
Some recommendations
Your database schema is not convenient. Student and Subject are tabular data.
So you need an additional object StudentSubjectMark.
Also use Long id for ids (not long id).
You have to log error here
catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}

Targeting unmapped class error in Spring boot app

I work on basic exemplary app that is about #OneToMany & ManyToOne annotation. I define mapping between two classes, apparently there is no error but on running app it gives me an error : Use of #OneToMany or #ManyToMany targeting an unmapped class: com.orchard.orchard.model.AppUser.userRole[ com.orchard.orchard.model.UserRole]
I'm failed to understand where does problem lies as mapping also describe in AppUser. I'd be grateful for the help.
Classes are as follows:
AppUser.java
package com.orchard.orchard.model;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
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.JoinColumn;
import javax.persistence.OneToMany;
#Entity
public class AppUser {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(updatable = false, nullable = false)
private Integer id;
private String name;
#Column(unique = true)
private String username;
private String password;
private String email;
#Column(columnDefinition = "text")
private String bio;
private Date createdDate;
#OneToMany(mappedBy = "appUser", cascade = CascadeType.ALL, fetch =
FetchType.EAGER)
private Set<UserRole> userRole = new HashSet<>();
public AppUser() {
}
public AppUser(Integer id, String name, String username, String
password, String email, String bio,
Date createdDate, Set<UserRole> userRoles) {
this.id = id;
this.name = name;
this.username = username;
this.password = password;
this.email = email;
this.bio = bio;
this.createdDate = createdDate;
this.userRole = userRoles;
}
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 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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Set<UserRole> getUserRoles() {
return userRole;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRole = userRoles;
}
}
UserRole.java
package com.orchard.orchard.model;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class UserRole {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long userRoleId;
#ManyToOne
#JoinColumn(name = "user_id")
#JsonIgnore
private AppUser appUser;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "role_id")
private Role role;
public UserRole() {
}
public UserRole(long userRoleId, AppUser appUser, Role role) {
this.userRoleId = userRoleId;
this.appUser = appUser;
this.role = role;
}
public long getUserRoleId() {
return userRoleId;
}
public void setUserRoleId(long userRoleId) {
this.userRoleId = userRoleId;
}
public AppUser getAppUser() {
return appUser;
}
public void setAppUser(AppUser appUser) {
this.appUser = appUser;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
You forgot to add #Entity annotation to your UserRole class
#Entity
public class UserRole {
}

Spring doesn't save List in oneToMany relationship

I've this Address Entity
package com.appdeveloperblog.app.ws.io.entity;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity(name = "addresses")
public class AddressEntity implements Serializable {
private static final long serialVersionUID = 3652691377296902875L;
#Id
#GeneratedValue
private long id;
#Column(length = 30, nullable = false)
private String addressId;
#Column(length = 15, nullable = false)
private String city;
#Column(length = 15, nullable = false)
private String country;
#Column(length = 100, nullable = false)
private String streetName;
#Column(length = 7, nullable = false)
private String postalCode;
#Column(length = 10, nullable = false)
private String type;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "users_id")
private UserEntity userDetails;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getAddressId() {
return addressId;
}
public void setAddressId(String addressId) {
this.addressId = addressId;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public UserEntity getUserDetails() {
return userDetails;
}
public void setUserDetails(UserEntity userDetails) {
this.userDetails = userDetails;
}
}
and this a Users Entity
package com.appdeveloperblog.app.ws.io.entity;
import java.io.Serializable;
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.Id;
import javax.persistence.OneToMany;
#Entity(name = "users")
public class UserEntity implements Serializable {
private static final long serialVersionUID = -3772691377276902875L;
#Id
#GeneratedValue
private long id;
#Column(nullable = false)
private String userId;
#Column(nullable = false, length = 50)
private String firstName;
#Column(nullable = false, length = 50)
private String lastName;
#Column(nullable = false, length = 120, unique = true)
private String email;
#Column(nullable = false)
private String encryptedPassword;
private String emailVerificationToken;
#Column(nullable = false)
private Boolean emailVerificationStatus = false;
#OneToMany(mappedBy = "userDetails", cascade = CascadeType.ALL)
private List<AddressEntity> addresses;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEncryptedPassword() {
return encryptedPassword;
}
public void setEncryptedPassword(String encryptedPassword) {
this.encryptedPassword = encryptedPassword;
}
public String getEmailVerificationToken() {
return emailVerificationToken;
}
public void setEmailVerificationToken(String emailVerificationToken) {
this.emailVerificationToken = emailVerificationToken;
}
public Boolean getEmailVerificationStatus() {
return emailVerificationStatus;
}
public void setEmailVerificationStatus(Boolean emailVerificationStatus) {
this.emailVerificationStatus = emailVerificationStatus;
}
}
and this function which I use it in service layer to save the data into the Mysql Database
#Override
public UserDto createUser(UserDto user) {
if (userRepository.findByEmail(user.getEmail()) != null)
throw new RuntimeException("Record already exists");
for(int i = 0 ; i < user.getAddresses().size() ; i++)
{
AddressDTO address = user.getAddresses().get(i);
address.setUserDetails(user);
address.setAddressId(utils.generateAddressId(30));
user.getAddresses().set(i, address);
}
ModelMapper modelMapper = new ModelMapper();
UserEntity userEntity = modelMapper.map(user, UserEntity.class);
String publicUserId = utils.generateUserId(30);
userEntity.setUserId(publicUserId);
userEntity.setEncryptedPassword(bCryptPasswordEncoder.encode(user.getPassword()));
UserEntity storedUserDetails = userRepository.save(userEntity);
// BeanUtils.copyProperties(storedUserDetails, returnValue);
UserDto returnValue = modelMapper.map(storedUserDetails, UserDto.class);
return returnValue;
}
after I post the data to the API using Postman POST request it save only the data into the users table and all the data in addresses table have been igonred
POST request Example:
{
"firstName" : "Sergey",
"lastName" : "Kargopolov",
"email" : "tno#test.com",
"password" : "123",
"addresses":[
{
"city":"Vancouver",
"country":"Canada",
"streetName":"123 Street name",
"postalCode": "ABCBA",
"type":"billing"
}
]
}
Below classes are the stripped down version of what you are trying to achieve. Please compare with your classes and it should work fine only difference is I have remove additional fields to test it easily. Check code in UserController map method.
UserEntity.java
#Entity
#Table(name = "users")
public class UserEntity implements Serializable {
private static final long serialVersionUID = 4865903039190150223L;
#Id
#GeneratedValue
private long id;
#Column(length = 50, nullable = false)
private String firstName;
#Column(length = 50, nullable = false)
private String lastName;
#OneToMany(mappedBy = "userDetails", cascade = CascadeType.ALL)
private List<AddressEntity> addresses;
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 List<AddressEntity> getAddresses() {
return addresses;
}
#Override
public String toString() {
return "UserEntity [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", addresses="
+ addresses + "]";
}
public void setAddresses(List<AddressEntity> addresses) {
this.addresses = addresses;
}
}
AddressEntity.java
#Entity(name = "addresses")
public class AddressEntity implements Serializable {
private static final long serialVersionUID = 3652691377296902875L;
#Id
#GeneratedValue
private long id;
#Column(length = 15, nullable = false)
private String city;
#Column(length = 15, nullable = false)
private String country;
#JsonIgnore
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "users_id")
private UserEntity userDetails;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public UserEntity getUserDetails() {
return userDetails;
}
public void setUserDetails(UserEntity userDetails) {
this.userDetails = userDetails;
}
#Override
public String toString() {
return "AddressEntity [id=" + id + ", city=" + city + ", country=" + country + "]";
}
}
UserDto.java
public class UserDto implements Serializable {
private static final long serialVersionUID = 6835192601898364280L;
private long id;
private String firstName;
private String lastName;
private List<AddressDTO> addresses;
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 List<AddressDTO> getAddresses() {
return addresses;
}
public void setAddresses(List<AddressDTO> addresses) {
this.addresses = addresses;
}
}
AddressDTO.java
public class AddressDTO {
private long id;
private String city;
private String country;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
UserController.java
#RestController
public class UserController {
#Autowired
UserRepository repository;
#PostMapping("map")
#ResponseBody
public UserEntity map(#RequestBody UserDto userDto) {
ModelMapper modelMapper = new ModelMapper();
UserEntity userEntity = modelMapper.map(userDto, UserEntity.class);
for (AddressEntity address : userEntity.getAddresses()) {
address.setUserDetails(userEntity);
}
repository.save(userEntity);
return userEntity;
}
}
Sample Request:
{
"firstName" : "Sergey",
"lastName" : "Kargopolov",
"addresses":[
{
"city":"Vancouver",
"country":"Canada"
}
]
}
Output:
{
"id": 7,
"firstName": "Sergey",
"lastName": "Kargopolov",
"addresses": [
{
"id": 8,
"city": "Vancouver",
"country": "Canada"
}
]
}

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'demo-db.common_bean' doesn't exist

I am trying to create Spring boot application with JPARepository.My aim is to create the application generic.
In my application i have 4 common functionalities for all the entities as follows :
getAll
getAllNewAfterLastSyncDate
getAllModifiedAfterLastSyncDate
getAllDeletedAfterLastSyncDate
To achive this and avoid redundency of code i created one generic base repository which extends JPARepository as follows :
BaseRepository.java
package dev.ashish.syncdemo.utlities;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.NoRepositoryBean;
#NoRepositoryBean
public interface BaseRepository<T> extends JpaRepository<T, Long>{
**#Query("select t from #{#entityName} t where t.deleteFlag = 'F' ")**
public List<T> getAll();
/*public List<T> getAllNewAfterLastSyncDate();
public List<T> getAllModifiedAfterLastSyncDate();
public List<T> getAllDeletedAfterLastSyncDate();
*/
}
I have created common bean which will be extended by all entities in my aplication as it has 5 common attributes or fields used for all entities.
CommonBean.java
package dev.ashish.syncdemo.beans;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class CommonBean {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="id")
private Long id;
#Column(name = "code")
private String code;
#Column(name = "created_by")
private Long createdBy;
#Column(name = "created_oy")
private Timestamp createdOn;
#Column(name = "modified_by")
private Long modifiedBy;
#Column(name = "modified_on")
private Timestamp modifiedOn;
#Column(name = "delete_flag")
private String deleteFlag;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Long getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Long createdBy) {
this.createdBy = createdBy;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}
public Long getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(Long modifiedBy) {
this.modifiedBy = modifiedBy;
}
public Timestamp getModifiedOn() {
return modifiedOn;
}
public void setModifiedOn(Timestamp modifiedOn) {
this.modifiedOn = modifiedOn;
}
public String getDeleteFlag() {
return deleteFlag;
}
public void setDeleteFlag(String deleteFlag) {
this.deleteFlag = deleteFlag;
}
}
Now Consider i want to use this for customer entity
CustomerEntity.java
package dev.ashish.syncdemo.beans;
import javax.persistence.Column;
public class CustomerEntity extends CommonBean{
#Column(name="first_name")
private String firstName;
#Column(name="middle_name")
private String middleName;
#Column(name="last_name")
private String lastName;
#Column(name="address1")
private String address1;
#Column(name="address2")
private String address2;
#Column(name="landline_no")
private String landlineNo;
#Column(name="mobile_no")
private String mobileNo;
#Column(name="email_id")
private String emailId;
#Column(name="city")
private String city;
#Column(name="state")
private String state;
#Column(name="country")
private String country;
#Column(name="pin_code")
private String pinCode;
#Column(name="fax_number")
private String faxNumber;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getLandlineNo() {
return landlineNo;
}
public void setLandlineNo(String landlineNo) {
this.landlineNo = landlineNo;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
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 getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPinCode() {
return pinCode;
}
public void setPinCode(String pinCode) {
this.pinCode = pinCode;
}
public String getFaxNumber() {
return faxNumber;
}
public void setFaxNumber(String faxNumber) {
this.faxNumber = faxNumber;
}
#Override
public String toString() {
return "CustomerEntity [firstName=" + firstName + ", middleName=" + middleName + ", lastName=" + lastName
+ ", address1=" + address1 + ", address2=" + address2 + ", landlineNo=" + landlineNo + ", mobileNo="
+ mobileNo + ", emailId=" + emailId + ", city=" + city + ", state=" + state + ", country=" + country
+ ", pinCode=" + pinCode + ", faxNumber=" + faxNumber + ", getId()=" + getId() + ", getCode()="
+ getCode() + ", getCreatedBy()=" + getCreatedBy() + ", getCreatedOn()=" + getCreatedOn()
+ ", getModifiedBy()=" + getModifiedBy() + ", getModifiedOn()=" + getModifiedOn() + ", getDeleteFlag()="
+ getDeleteFlag() + "]";
}
}
I created CustomerService which extends BaseRepositoy as follows:
CustomerService.java
package dev.ashish.syncdemo.service;
import org.springframework.stereotype.Service;
import dev.ashish.syncdemo.beans.CustomerEntity;
import dev.ashish.syncdemo.utlities.BaseRepository;
#Service("customerService")
public interface CustomerService extends BaseRepository<CustomerEntity>{
}
FrontController.java
package dev.ashish.syncdemo.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import dev.ashish.syncdemo.service.CustomerService;
import dev.ashish.syncdemo.utlities.Constants;
#RestController
#RequestMapping("/frontgate")
public class FrontController {
#Autowired
private CustomerService customerService;
#RequestMapping(value = "/getres", method = RequestMethod.POST)
public String getRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
String reqStr = request.getReader().readLine();
System.out.println("Request is : " + reqStr);
Map<String, Object> reqMap = new Gson().fromJson(reqStr, new TypeToken<HashMap<String, Object>>() {
}.getType());
System.out.println("Req Map " + reqMap);
return parseRequest(reqMap);
}
public String parseRequest(Map<String, Object> reqMap)
{
String entity = (String)reqMap.get(Constants.ENTITY);
String action = (String)reqMap.get(Constants.ACTION);
String pageSize = (String)reqMap.get(Constants.PAGE_SIZE);
String pageNumber = (String)reqMap.get(Constants.PAGE_NUMBER);
String lastSyncDate = (String)reqMap.get(Constants.LAST_SYNC_DATE);
return customerService.getAll().toString();
}
}
SyncDemoApplication.java
package dev.ashish;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SyncDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SyncDemoApplication.class, args);
}
}
Application flow is as follows:
Request will come to FrontController then it will be forwarded to customerservice which is extending base repository of type JPArepository.
As there are all common functionalities i dont want to create repository for all entities separately and write query for each of them. As you can see i am using SPEL #{#entityName} passing entity name at runtime to query in #Query annotation.
When i try to run application it gives me following exception :
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'demo-db.common_bean' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.7.0_67]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.7.0_67]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.7.0_67]
at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[na:1.7.0_67]
at com.mysql.jdbc.Util.handleNewInstance(Util.java:389) ~[mysql-connector-java-5.1.35.jar:5.1.35]
Query being fired is as follows :
Hibernate: select customeren0_.id as id2_0_, customeren0_.code as code3_0_, customeren0_.created_by as created_4_0_, customeren0_.created_oy as created_5_0_, customeren0_.delete_flag as delete_f6_0_, customeren0_.modified_by as modified7_0_, customeren0_.modified_on as modified8_0_, customeren0_.address1 as address9_0_, customeren0_.address2 as address10_0_, customeren0_.city as city11_0_, customeren0_.country as country12_0_, customeren0_.email_id as email_i13_0_, customeren0_.fax_number as fax_num14_0_, customeren0_.first_name as first_n15_0_, customeren0_.landline_no as landlin16_0_, customeren0_.last_name as last_na17_0_, customeren0_.middle_name as middle_18_0_, customeren0_.mobile_no as mobile_19_0_, customeren0_.pin_code as pin_cod20_0_, customeren0_.state as state21_0_
from **common_bean** customeren0_ where customeren0_.dtype='CustomerEntity' and customeren0_.delete_flag='F'
Instead of common_bean in from clause it should be customer as i am doing operation for entity customer.
Please let me know what i am doing wrong.

Resources