I'm trying to return data from database but this error has occurred I don't know the error is 404 this is my code :
http://localhost:8085/exercices
my Exercice class
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.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "exercice")
public class exercices implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long idExercice;
private String nomExercice;
private String LinkExercice;
#ManyToOne
private patient patient;
public exercices(Long idExercice, String nomExercice, String linkExercice) {
this.idExercice = idExercice;
this.nomExercice = nomExercice;
this.LinkExercice = linkExercice;
this.patient = new patient();
}
public exercices(String nomExercice, String linkExercice) {
this.nomExercice = nomExercice;
LinkExercice = linkExercice;
}
public Long getIdExercice() {
return idExercice;
}
public void setIdExercice(Long idExercice) {
this.idExercice = idExercice;
}
public String getNomExercice() {
return nomExercice;
}
public void setNomExercice(String nomExercice) {
this.nomExercice = nomExercice;
}
public String getLinkExercice() {
return LinkExercice;
}
public void setLinkExercice(String linkExercice) {
LinkExercice = linkExercice;
}
#Override
public String toString() {
return "exercices [LinkExercice=" + LinkExercice + ", idExercice=" + idExercice + ", nomExercice=" + nomExercice
+ "]";
}
}
ExerciceController
import java.util.List;
import org.apache.catalina.connector.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import healthP.Health.Progress.model.exercices;
import healthP.Health.Progress.service.ExerciceService;
#RestController
#RequestMapping()
public class ExerciceController {
#Autowired
private final ExerciceService exserv;
public ExerciceController(ExerciceService exserv) {
this.exserv = exserv;
}
#GetMapping("/exercices")
public ResponseEntity<List<exercices>> getAllExercices() {
List<exercices> ex = this.exserv.findAllExercices();
return new ResponseEntity<>(ex, HttpStatus.OK);
}
}
ExerciceService
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import healthP.Health.Progress.model.exercices;
import healthP.Health.Progress.repo.ExercicesRepo;
#Service
public class ExerciceService {
private final ExercicesRepo ExRepo;
#Autowired
public ExerciceService(ExercicesRepo ExRepo) {
this.ExRepo = ExRepo;
}
public List<exercices> findAllExercices() {
return this.ExRepo.findAll();
}
}
interface
import org.springframework.data.jpa.repository.JpaRepository;
import healthP.Health.Progress.model.exercices;
public interface ExercicesRepo extends JpaRepository<exercices, Long> {
}
and this is patient class because I want also check if the relation between two classes are correcte and spacially in the constructeur of exercice class.
package healthP.Health.Progress.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
//import org.hibernate.annotations.Table;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
#Entity
#Table(name = "patient")
// #Table(name = patient.TABLE_NAME)
public class patient implements Serializable {
// public static final String TABLE_NAME="PATIENT";
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int score;
#Column(nullable = false, updatable = false)
private Long id;
private String name;
private String email;
private String password;
#Column(nullable = false, updatable = false)
private String codePatient;
public patient() {
}
public patient(String codep, String name, String email, String password) {
this.codePatient = codep;
this.name = name;
this.email = email;
this.password = password;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCodePatient() {
return this.codePatient;
}
public void setCodePatient(String codePatient) {
this.codePatient = codePatient;
}
public void setScore(int score) {
this.score = score;
}
public int getScore() {
return this.score;
}
#Override
public String toString() {
return "{" + " id='" + getId() + "'" + ", name='" + getName() + "'" + ", email='" + getEmail() + "'"
+ ", password='" + getPassword() + "'" + "}";
}
}```
add api-path to requestmapping of ExerciceController , so it becomes
#RequestMapping("/api")
public class ExerciceController {
EDIT:
You need to add default constructor to excercises entity
public exercices(){}
now you can access it as http://localhost:8085/api/exercices
PS: unrelated to question, use singular class name for entity excercise instead of excercises
You can make little changes in your code and follow any of below approach:
1- Remove #RequestMapping()
You can access endpoint : http://localhost:8085/exercices
2- If you want to manage the api versioning then use #RequestMapping("/api/v1")
You can use endpoint: http://localhost:8085/api/v1/exercices
Related
I'm just learning Spring Boot and doing a small project I got stuck with. I have a many to many relationship between Students and Courses, there is a table in the middle called enrollment for this relationship which takes the student_id and course_id as the primary key. I am creating an API for the above-mentioned. I have next
Class Student
Class Enrollment
Class Course
Class StudentRepository
Class StudentJPAResource
Class Student
package com.myapis.rest.webservices.restfulwebservicesedgar01.student;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import com.myapis.rest.webservices.restfulwebservicesedgar01.enrollment.Enrollment;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
#Entity
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "STUD_SEQ")
#SequenceGenerator(sequenceName = "student_id_seq", allocationSize = 1, name = "STUD_SEQ")
private Integer studentId;
#Size(min=2, message="Name should have at least two chars")
private String firstName;
private String lastName;
#OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
#JsonIgnore
private List<Enrollment> enrollments = new ArrayList<>();
#Past
private Date birthDate;
public Student() {}
public Student(Integer studentId, String firstName, String lastName, Date birthDate) {
super();
this.studentId = studentId;
this.firstName = firstName;
this.birthDate = birthDate;
}
public Integer getId() {
return studentId;
}
public void setId(Integer id) {
this.studentId = studentId;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setfirstName(String firstName) {
this.firstName = firstName;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public List<Enrollment> getEnrollments() {
return enrollments;
}
#Override
public String toString() {
return "Student [studentId=" + studentId + ", firstName=" + firstName + ", lastName=" + lastName + ", payments="
+ payments + ", birthDate=" + birthDate + "]";
}
}
Class Enrollment
package com.myapis.rest.webservices.restfulwebservicesedgar01.enrollment;
import java.util.Date;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MapsId;
import javax.persistence.Table;
import com.myapis.rest.webservices.restfulwebservicesedgar01.course.Course;
import com.myapis.rest.webservices.restfulwebservicesedgar01.student.Student;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity(name="Enrollment")
#Table(name="enrollments")
public class Enrollment {
#EmbeddedId
private EnrollmentId id;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("studentId")
#JoinColumn(name="student_id")
#JsonIgnore
private Student student;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("courseId")
#JoinColumn(name="course_id")
#JsonIgnore
private Course course;
#Column(name="enrollment_id")
private Integer enrollmentId;
#Column(name="date_enrollment")
private Date enrollmentDate;
public Enrollment() {}
public Enrollment(Student student, Course course, Integer enrollmentId, Date enrollmentDate) {
super();
this.id = new EnrollmentId(student.getId(), course.getId());
this.student = student;
this.course = course;
this.enrollmentId = enrollmentId;
this.enrollmentDate = enrollmentDate;
}
public EnrollmentId getId() {
return id;
}
public void setId(EnrollmentId id) {
this.id = id;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public Integer getEnrollmentId() {
return enrollmentId;
}
public void setEnrollmentId(Integer enrollmentId) {
this.enrollmentId = enrollmentId;
}
public Date getEnrollmentDate() {
return enrollmentDate;
}
public void setEnrollmentDate(Date enrollmentDate) {
this.enrollmentDate = enrollmentDate;
}
#Override
public String toString() {
return "Enrollment [id=" + id + ", student=" + student + ", course=" + course + ", enrollmentId=" + enrollmentId
+ ", enrollmentDate=" + enrollmentDate + "]";
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
Enrollment that = (Enrollment) o;
return Objects.equals(student, that.student) &&
Objects.equals(course, that.course);
}
#Override
public int hashCode() {
return Objects.hash(student, course);
}
}
Class Course
package com.myapis.rest.webservices.restfulwebservicesedgar01.course;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import com.myapis.rest.webservices.restfulwebservicesedgar01.enrollment.Enrollment;
import com.myapis.rest.webservices.restfulwebservicesedgar01.student.Student;
#Entity
public class Course {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "COURSE_SEQ")
#SequenceGenerator(sequenceName = "course_id_seq", allocationSize = 1, name = "COURSE_SEQ")
private Integer courseId;
private String courseName;
private String description;
#OneToMany(mappedBy = "course", cascade = CascadeType.ALL)
private List<Enrollment> enrollments = new ArrayList<>();
public Course() {}
public Course(Integer courseId, String courseName, String description) {
super();
this.courseId = courseId;
this.courseName = courseName;
this.description = description;
}
public Integer getId() {
return courseId;
}
public Integer getCourseId() {
return courseId;
}
public void setCourseId(Integer courseId) {
this.courseId = courseId;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Course [courseId=" + courseId + ", courseName=" + courseName + ", description=" + description + "]";
}
}
Class Enrollment
package com.myapis.rest.webservices.restfulwebservicesedgar01.enrollment;
import java.util.Date;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MapsId;
import javax.persistence.Table;
import com.myapis.rest.webservices.restfulwebservicesedgar01.course.Course;
import com.myapis.rest.webservices.restfulwebservicesedgar01.student.Student;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity(name="Enrollment")
#Table(name="enrollments")
public class Enrollment {
#EmbeddedId
private EnrollmentId id;
#ManyToOne(fetch = FetchType.EAGER)
#MapsId("studentId")
#JoinColumn(name="student_id")
#JsonIgnore
private Student student;
#ManyToOne(fetch = FetchType.EAGER)
#MapsId("courseId")
#JoinColumn(name="course_id")
#JsonIgnore
private Course course;
#Column(name="enrollment_id")
private Integer enrollmentId;
#Column(name="date_enrollment")
private Date enrollmentDate;
public Enrollment() {}
public Enrollment(Student student, Course course, Integer enrollmentId, Date enrollmentDate) {
super();
this.id = new EnrollmentId(student.getId(), course.getId());
this.student = student;
this.course = course;
this.enrollmentId = enrollmentId;
this.enrollmentDate = enrollmentDate;
}
public EnrollmentId getId() {
return id;
}
public void setId(EnrollmentId id) {
this.id = id;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public Integer getEnrollmentId() {
return enrollmentId;
}
public void setEnrollmentId(Integer enrollmentId) {
this.enrollmentId = enrollmentId;
}
public Date getEnrollmentDate() {
return enrollmentDate;
}
public void setEnrollmentDate(Date enrollmentDate) {
this.enrollmentDate = enrollmentDate;
}
#Override
public String toString() {
return "Enrollment [id=" + id + ", student=" + student + ", course=" + course + ", enrollmentId=" + enrollmentId
+ ", enrollmentDate=" + enrollmentDate + "]";
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
Enrollment that = (Enrollment) o;
return Objects.equals(student, that.student) &&
Objects.equals(course, that.course);
}
#Override
public int hashCode() {
return Objects.hash(student, course);
}
}
Class StudentRepository
package com.edgarapis.rest.webservices.restfulwebservicesedgar01.student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface StudentRepository extends JpaRepository<Student, Integer>{
}
Class StudentJPAResource
package com.myapis.rest.webservices.restfulwebservicesedgar01.student;
import java.net.URI;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.myapis.rest.webservices.restfulwebservicesedgar01.payment.Payment;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.MapperFeature;
import com.myapis.rest.webservices.restfulwebservicesedgar01.enrollment.Enrollment;
#RestController
public class StudentJPAResource {
#Autowired
private StudentRepository studentRepository;
//retrieve all students
#GetMapping("/jpa/students")
public List<Student> retrieveAllStudents() {
return studentRepository.findAll();
}
//retrieve one user by id from studentRepository
#GetMapping("/jpa/students/{id}")
public EntityModel<Optional<Student>> retriveStudent(#PathVariable int id) {
Optional<Student> student = studentRepository.findById(id);
if(!student.isPresent()) {
throw new StudentNotFoundException("id - " + id);
}
//"all-students", SERVER_PATH + "/students"
//RetrieveAllStudents
EntityModel<Optional<Student>> resource = EntityModel.of(student);
//From the library WebMvcLinkBuilder
WebMvcLinkBuilder linkTo = WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(this.getClass()).retrieveAllStudents());
resource.add(linkTo.withRel("all-students"));
return resource;
}
//deleting one user by id
#DeleteMapping("/jpa/students/{id}")
public void deleteStudent(#PathVariable int id) {
studentRepository.deleteById(id);
}
//Save one user to the persistence layer
#PostMapping("/jpa/students")
public ResponseEntity<Object> createStudent(#Valid #RequestBody Student student) {
Student savedStudent = studentRepository.save(student);
// /user/{id} -- Response back indicating the user creation was good
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedStudent.getId()).toUri();
return ResponseEntity.created(location).build();
}
//All courses that one specific student is enrolled
#GetMapping("/jpa/students/{id}/enrollments")
public List<Enrollment> retrieveOneStudentCourses(#PathVariable int id) {
Optional<Student> studentOptional = studentRepository.findById(id);
if(!studentOptional.isPresent()) {
throw new StudentNotFoundException("id - " + id);
}
return studentOptional.get().getEnrollments();
}
//All Students with their courses
#GetMapping("/jpa/students/enrollments")
public List<Student> retrieveAllStudentsCourses() {
// How to implement???
}
}
In the class StudentJPAResource, method retrieveOneStudentCourses, I created this method to retrieve the courses of a specific student. I want to create a method to retrieve all the students and the courses that they are enrolled retrieveAllStudentsCourses().
NOTE
Currently, in the class student, I have the notation #JsonIgnore for Enrollment because when I use retrieveAllStudents() the students come up with their enrollments so, this notation prevents this, otherwise, the students will come up with the enrollments (that is actually what I want to do, but using a different method).
Thank you for your help, beforehand.
I use Quarkus + Hibernate to sync data to the DB and I've noticed during testing that sometimes my entity isn't updated. I've created a minimal example adjusting the original example https://github.com/quarkusio/quarkus-quickstarts/tree/main/hibernate-orm-quickstart
Here are my adjustments:
import.sql
DROP TABLE IF EXISTS fruit CASCADE;
CREATE TABLE fruit (
fruitsSequence INT PRIMARY KEY,
name TEXT NOT NULL,
test INT
);
Fruit.java
package org.acme.hibernate.orm;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.google.common.base.Objects;
#Entity
#Table(name = "known_fruits")
public class Fruit {
#Id
#SequenceGenerator(name = "fruitsSequence", sequenceName = "known_fruits_id_seq", allocationSize = 1, initialValue = 10)
#GeneratedValue(generator = "fruitsSequence")
private Integer id;
#Transient
private String name = "";
#Column(name = "test")
private Integer test = -1;
public Fruit() {
}
public Fruit(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "name")
#Access(AccessType.PROPERTY)
public String getChangedName() {
return "a" + name;
}
public String getName() {
return name;
}
public void setTest(Integer test) {
this.test = test;
}
public Integer getTest() {
return test;
}
#Column(name = "name")
#Access(AccessType.PROPERTY)
protected void setChangedName(String name) {
this.name = name.substring(1);
}
public void setName(String name) {
this.name = name;
}
#Override
public int hashCode() {
return Objects.hashCode(name, test);
}
#Override
public boolean equals(Object o) {
if (o instanceof Fruit) {
Fruit other = (Fruit) o;
return name.equals(other.name) && test.equals(other.test);
}
return false;
}
}
Replaced the test withDBTest.java
package org.acme.hibernate.orm;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.UserTransaction;
import org.junit.jupiter.api.Test;
import io.quarkus.test.junit.QuarkusTest;
#QuarkusTest
public class DBTest {
#Inject
EntityManager m_em;
#Inject
UserTransaction m_transaction;
#Test
void testUpdate() throws Exception {
Fruit fruit = given().when().body("{\"name\" : \"Pear\"}").contentType("application/json").post("/fruits")
.then().statusCode(201).extract().as(Fruit.class);
m_transaction.begin();
Fruit db = m_em.find(Fruit.class, fruit.getId());
db.setName("Apple");
db.setTest(13);
m_transaction.commit();
db = m_em.find(Fruit.class, fruit.getId());
assertEquals(13, db.getTest(), "Unexpected test");
assertEquals("Apple", db.getName(), "Unexpected name");
}
#Test
void testUpdateLongName() throws Exception {
Fruit fruit = given().when().body(
"{\"name\" : \"PeeeeeeeeeeeeeeeeeeeeeeeaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaDBaaaaaaaaaaaaaar\"}")
.contentType("application/json").post("/fruits").then().statusCode(201).extract().as(Fruit.class);
m_transaction.begin();
Fruit db = m_em.find(Fruit.class, fruit.getId());
db.setName(fruit.getName() + "Apple");
db.setTest(13);
m_transaction.commit();
db = m_em.find(Fruit.class, fruit.getId());
assertEquals(13, db.getTest(), "Unexpected test");
assertEquals(fruit.getName() + "Apple", db.getName(), "Unexpected name");
}
#Test
void testUpdateNameOnly() throws Exception {
Fruit fruit = given().when().body("{\"name\" : \"Pear\"}").contentType("application/json").post("/fruits")
.then().statusCode(201).extract().as(Fruit.class);
m_transaction.begin();
Fruit db = m_em.find(Fruit.class, fruit.getId());
db.setName("Apple");
m_transaction.commit();
db = m_em.find(Fruit.class, fruit.getId());
assertEquals(-1, db.getTest(), "Unexpected test");
assertEquals("Apple", db.getName(), "Unexpected name");
}
#Test
void testUpdateNameOnlyREST() throws Exception {
Fruit fruit = given().when().body("{\"name\" : \"Pear\"}").contentType("application/json").post("/fruits")
.then().statusCode(201).extract().as(Fruit.class);
given().when().body("{\"name\" : \"Apple\"}").contentType("application/json").put("/fruits/" + fruit.getId())
.then().statusCode(200).extract().as(Fruit.class);
Fruit db = m_em.find(Fruit.class, fruit.getId());
assertEquals(-1, db.getTest(), "Unexpected test");
assertEquals("Apple", db.getName(), "Unexpected name");
}
}
What I see is that testUpdateNameOnly and testUpdateNameOnlyREST fail whereas the other tests run as expected. In my original testcase, even changing another field didn't update the TEXT field hence the test with the long name. The reason why the name is altered when writing it to the DB is to encrypt it (the outcome is a BASE64 string).
I am not sure if this is a configuration issue or an actual bug.
Thanks for helps in advance!
As suggested by the comments this seems to be a bug (https://github.com/quarkusio/quarkus/issues/16619).
It works with the AttributeConver:
Fruit.java:
package org.acme.hibernate.orm;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import com.google.common.base.Objects;
#Entity
#Table(name = "known_fruits")
public class Fruit {
#Id
#SequenceGenerator(name = "fruitsSequence", sequenceName = "known_fruits_id_seq", allocationSize = 1, initialValue = 10)
#GeneratedValue(generator = "fruitsSequence")
private Integer id;
#Column(name = "name")
#Convert(converter = NameConverter.class)
private String name = "";
#Column(name = "test")
private Integer test = -1;
public Fruit() {
}
public Fruit(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setTest(Integer test) {
this.test = test;
}
public Integer getTest() {
return test;
}
public void setName(String name) {
this.name = name;
}
#Override
public int hashCode() {
return Objects.hashCode(name, test);
}
#Override
public boolean equals(Object o) {
if (o instanceof Fruit) {
Fruit other = (Fruit) o;
return name.equals(other.name) && test.equals(other.test);
}
return false;
}
}
NameConverter.java:
package org.acme.hibernate.orm;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
#Converter
public class NameConverter implements AttributeConverter<String, String> {
#Override
public String convertToDatabaseColumn(String name) {
return "a" + name;
}
#Override
public String convertToEntityAttribute(String name) {
return name.substring(1);
}
}
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
I have three entity classes Country, State, and City. Now I am trying to display the cities that come under a particular state and states that come under a particular country. but I am facing an error like
org.springframework.dao.DataAccessResourceFailureException:
Could not create JPA EntityManager;
nested exception is org.hibernate.AnnotationException:
#OneToOne or #ManyToOne on com.region.model.State.cities reference
an unknown entity: java.util.List.
Please help me out in one-to-many and many-to-one mapping for the three tables.
package com.region.model;
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.OneToOne;
import javax.persistence.SecondaryTable;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
#Entity
#Table(name = "country")
public class Country {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private Integer country_id;
#Column
private String country_name;
// #Column
// private String status="active";
#Transient
private String statusCode;
#Transient
private String statusmessage;
#OneToMany(targetEntity=State.class, mappedBy="country",cascade=CascadeType.ALL, fetch = FetchType.LAZY)
#JsonBackReference
private List<State> states;
public Country() {
}
public Integer getCountry_id() {
return country_id;
}
public void setCountry_id(Integer country_id) {
this.country_id = country_id;
}
public String getCountry_name() {
return country_name;
}
public void setCountry_name(String country_name) {
this.country_name = country_name;
}
// public String getStatus() {
// return status;
// }
// public void setStatus(String status) {
// this.status = status;
// }
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getStatusmessage() {
return statusmessage;
}
public void setStatusmessage(String statusmessage) {
this.statusmessage = statusmessage;
}
public List<State> getStates() {
return states;
}
public void setStates(List<State> states) {
this.states = states;
}
}
package com.region.model;
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.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
#Entity
#Table(name = "state")
public class State {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private Integer sk_state_id;
#Column
private String state_name;
#Column
private String country_id;
// #Column
// private String status="active";
#Transient
private String statusCode;
#Transient String statusMessage;
#ManyToOne()
#JoinColumn(name="country_id", referencedColumnName = "country_id", insertable = false, updatable = false)
#JsonManagedReference
#OneToMany(targetEntity=City.class, mappedBy="state",cascade=CascadeType.ALL, fetch = FetchType.LAZY)
private List<City>cities;
private Country country;
public State() {
}
public Integer getSk_state_id() {
return sk_state_id;
}
public void setSk_state_id(Integer sk_state_id) {
this.sk_state_id = sk_state_id;
}
public String getState_name() {
return state_name;
}
public void setState_name(String state_name) {
this.state_name = state_name;
}
public String getCountry_id() {
return country_id;
}
public void setCountry_id(String country_id) {
this.country_id = country_id;
}
// public String getStatus() {
// return status;
// }
// public void setStatus(String status) {
// this.status = status;
// }
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getStatusMessage() {
return statusMessage;
}
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
public List<City> getCities() {
return cities;
}
public void setCities(List<City> cities) {
this.cities = cities;
}
}
package com.region.model;
import java.lang.annotation.Repeatable;
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.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
#Entity
#Table(name = "city")
public class City {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private Integer sk_city_id;
#Column
private String city_name;
#Column
private String state_id;
#Column
private String country_id;
#Transient
private String statusCode;
#Transient
String statusMessage;
#ManyToOne(targetEntity = State.class)
#JoinColumn(name="state_id", referencedColumnName ="sk_state_id", insertable = false, updatable = false)
private State state;
private Country country;
//private List<State>states;
public City() {
}
public Integer getSk_city_id() {
return sk_city_id;
}
public void setSk_city_id(Integer sk_city_id) {
this.sk_city_id = sk_city_id;
}
public String getCity_name() {
return city_name;
}
public void setCity_name(String city_name) {
this.city_name = city_name;
}
public String getState_id() {
return state_id;
}
public void setState_id(String state_id) {
this.state_id = state_id;
}
public String getCountry_id() {
return country_id;
}
public void setCountry_id(String country_id) {
this.country_id = country_id;
}
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getStatusMessage() {
return statusMessage;
}
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
#Override
public String toString() {
return "City [sk_city_id=" + sk_city_id + ", city_name=" + city_name + ", state_id=" + state_id
+ ", country_id=" + country_id + ", statusCode=" + statusCode + ", statusMessage=" + statusMessage
+ "]";
}
// public List<State> getStates() {
// return states;
// }
// public void setStates(List<State> states) {
// this.states = states;
// }
}
mappedBy is only used once in a relationship between 2 classes, for the class that you want to define the relationship for both. So in the class Countries you probably don't need mappedBy at all, in the class Cities, you should put mappedBy="state", and in the class State it would make sense to put mappedBy="country"
I have two table Parent table is Credit in that table only one row of data is there and another one is child table Debit that contains multiple row of data. how to fetch data from two table which has to match id of parent class and child class and no duplicate is shown from parent class.
I have try with (from Credit,debit) but that can display with duplicate and not properly data is shown based on id.
package com.rojmat.entity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.core.annotation.Order;
#Entity
#Table(name="credit")
public class Credit extends BaseEntity{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long cid;
#Column #Order
private long openingbalance;
#Column
private Date date;
#Column #Order
private long debittotal;
#Column #Order
private long drawertotal;
#Column #Order
private long debittotalplusdrawertotal;
#Column #Order
private long todaybusiness;
#OneToMany(cascade={CascadeType.ALL})
#JoinTable(name="credit_debit",
joinColumns=#JoinColumn(name="c_id"),
inverseJoinColumns=#JoinColumn(name="d_id"))
/*#JoinColumn(name="cid", referencedColumnName="cid")*/
private List<Debit> debits = new ArrayList<Debit>(Arrays.asList());
public Credit() {
}
public Credit(long cid, long openingbalance, Date date, long debittotal, long drawertotal,
long debittotalplusdrawertotal, long todaybusiness, List<Debit> debits) {
super();
this.cid = cid;
this.openingbalance = openingbalance;
this.date = date;
this.debittotal = debittotal;
this.drawertotal = drawertotal;
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
this.todaybusiness = todaybusiness;
this.debits = debits;
}
public long getCid() {
return cid;
}
public void setCid(long cid) {
this.cid = cid;
}
public long getOpeningbalance() {
return openingbalance;
}
public void setOpeningbalance(long openingbalance) {
this.openingbalance = openingbalance;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public long getDebittotal() {
return debittotal;
}
public void setDebittotal(long debittotal) {
this.debittotal = debittotal;
}
public long getDrawertotal() {
return drawertotal;
}
public void setDrawertotal(long drawertotal) {
this.drawertotal = drawertotal;
}
public long getDebittotalplusdrawertotal() {
return debittotalplusdrawertotal;
}
public void setDebittotalplusdrawertotal(long debittotalplusdrawertotal) {
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
}
public long getTodaybusiness() {
return todaybusiness;
}
public void setTodaybusiness(long todaybusiness) {
this.todaybusiness = todaybusiness;
}
public List<Debit> getDebit() {
return debits;
}
public void setDebit(List<Debit> debit) {
this.debits = debits;
}
/*#Override
public String toString() {
return "Credit [cid=" + cid + ", openingbalance =" + openingbalance + ", date=" + date + ", debittotal= " + debittotal + ", debittotalplusdrawertotal=" + debittotalplusdrawertotal + ", todaybusiness=" + todaybusiness + "]";
}*/
}
package com.rojmat.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="debit")
public class Debit {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long did;
#Column
private String amount;
#Column
private String description;
public Debit() {
}
public Debit(String amount, String description) {
super();
this.amount = amount;
this.description = description;
}
public long getDid() {
return did;
}
public void setDid(long did) {
this.did = did;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Debit [did=" + did + ", amount =" + amount + ", description=" + description + "]";
}
}
1.CreditDaoImpl.java
package com.rojmat.daoImpl;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.rojmat.dao.CreditDao;
import com.rojmat.entity.Credit;
#Repository
public class CreditDaoImpl implements CreditDao{
#Autowired
private SessionFactory sessionFactory;
#Override
public void addCreditDebit(Credit credit) {
try {
sessionFactory.getCurrentSession().saveOrUpdate(credit);
} catch(Exception e) {
e.printStackTrace();
}
}
#Override
public void deleteCreditDebit(int cid) {
/*Credit credit = (Credit)sessionFactory.getCurrentSession().createQuery("from Credit as c LEFT JOIN FETCH c.Debit where c.cid="+cid).uniqueResult();
List<Debit> debits = credit.getDebit();
sessionFactory.getCurrentSession().delete(credit);
debits.forEach((debit) -> {
sessionFactory.getCurrentSession().delete(debit);
});*/
}
#SuppressWarnings("unchecked")
#Override
public List<Credit> getAllCreditDebit() {
List<Credit> credit = sessionFactory.getCurrentSession().createQuery("from Credit,Debit").list();
return credit;
}
}
try this example: you put "distinct" before the property you do not want to be duplicated
//SQL query
select distinct credit.idCredit as idCredit from Credit credit Left Join Debit debit on credit.idCredit= debit.idCredit
//HQL query
#Entity(name = "Credit")
#Table(name = "Credit")
public class Credit{
//if you put #Id --> HQL Query "select credit from Credit credit"
#Column(name = "idCredit")
private Long idCredit;
#Column(name = "label")
private String label;
#OneToMany
#JoinColumns({#JoinColumn(name = "idCredit" ,referencedColumnName = "idCredit")})
List<Debit> debits;
...
}
public class Debit{
....
#Column(name = "idCredit")
private Long idCredit;
...
}
Query query = getSession().createQuery("select distinct credit.idCredit as idCredit, credit.label as label, credit.debits as debits from Credit credit ");
query.setResultTransformer(Transformers.aliasToBean(Credit.class));
return query.list();
package com.rojmat.entity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.core.annotation.Order;
#Entity
#Table(name="credit")
public class Credit extends BaseEntity{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long cid;
#Column #Order
private long openingbalance;
#Column
private Date date;
#Column #Order
private long debittotal;
#Column #Order
private long drawertotal;
#Column #Order
private long debittotalplusdrawertotal;
#Column #Order
private long todaybusiness;
#OneToMany(cascade={CascadeType.ALL})
#JoinTable(name="credit_debit",
joinColumns=#JoinColumn(name="c_id"),
inverseJoinColumns=#JoinColumn(name="d_id"))
/*#JoinColumn(name="cid", referencedColumnName="cid")*/
private List<Debit> debits = new ArrayList<Debit>(Arrays.asList());
public Credit() {
}
public Credit(long cid, long openingbalance, Date date, long debittotal, long drawertotal,
long debittotalplusdrawertotal, long todaybusiness, List<Debit> debits) {
super();
this.cid = cid;
this.openingbalance = openingbalance;
this.date = date;
this.debittotal = debittotal;
this.drawertotal = drawertotal;
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
this.todaybusiness = todaybusiness;
this.debits = debits;
}
public long getCid() {
return cid;
}
public void setCid(long cid) {
this.cid = cid;
}
public long getOpeningbalance() {
return openingbalance;
}
public void setOpeningbalance(long openingbalance) {
this.openingbalance = openingbalance;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public long getDebittotal() {
return debittotal;
}
public void setDebittotal(long debittotal) {
this.debittotal = debittotal;
}
public long getDrawertotal() {
return drawertotal;
}
public void setDrawertotal(long drawertotal) {
this.drawertotal = drawertotal;
}
public long getDebittotalplusdrawertotal() {
return debittotalplusdrawertotal;
}
public void setDebittotalplusdrawertotal(long debittotalplusdrawertotal) {
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
}
public long getTodaybusiness() {
return todaybusiness;
}
public void setTodaybusiness(long todaybusiness) {
this.todaybusiness = todaybusiness;
}
public List<Debit> getDebit() {
return debits;
}
public void setDebit(List<Debit> debit) {
this.debits = debits;
}
/*#Override
public String toString() {
return "Credit [cid=" + cid + ", openingbalance =" + openingbalance + ", date=" + date + ", debittotal= " + debittotal + ", debittotalplusdrawertotal=" + debittotalplusdrawertotal + ", todaybusiness=" + todaybusiness + "]";
}*/
}
package com.rojmat.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="debit")
public class Debit {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long did;
#Column
private String amount;
#Column
private String description;
public Debit() {
}
public Debit(String amount, String description) {
super();
this.amount = amount;
this.description = description;
}
public long getDid() {
return did;
}
public void setDid(long did) {
this.did = did;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/*#Override
public String toString() {
return "Debit [did=" + did + ", amount =" + amount + ", description=" + description + "]";
}*/
}