I would like to link two classes where the consultant have an ID and I would like to send this ID to the customer so a customer will be assigned to the consultant.
I created a class for the consultant with the ID, name and surname and the same for the customer. I am trying to get the ID from the consultant using the code below
Consultant newconsultant = new Consultant(Consultant.getConsultantID());
The consultantID is the id of the consultant in the class consultant.I am stuck and I appreciate any help with any information for this issue.
Consultant code:
public class Consultant extends Person implements Serializable {
public String ConsultantID;
private String Consfirstname;
private String Conslastname;
Consultant(String consultantID) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* #return the ConsultantID
*/
public String getConsultantID() {
return ConsultantID;
}
/**
* #param ConsultantID the ConsultantID to set
*/
public void setConsultantID(String ConsultantID) {
this.ConsultantID = ConsultantID;
}
/**
* #return the Consfirstname
*/
public String getConsfirstname() {
return Consfirstname;
}
/**
* #param Consfirstname the Consfirstname to set
*/
public void setConsfirstname(String Consfirstname) {
this.Consfirstname = Consfirstname;
}
/**
* #return the Conslastname
*/
public String getConslastname() {
return Conslastname;
}
/**
* #param Conslastname the Conslastname to set
*/
public void setConslastname(String Conslastname) {
this.Conslastname = Conslastname;
}
Customers Code:
public class Customer extends Person implements Serializable {
private String CustomerID;
public String Custfirstname;
public String Custlastname;
private Consultant Consultant;
public String CID;
Consultant newconsultant = new Consultant(Consultant.getConsultantID());
/**
* #return the CustomerID
*/
public String getCustomerID() {
return CustomerID;
}
/**
* #param CustomerID the CustomerID to set
*/
public void setCustomerID(String CustomerID) {
this.CustomerID = CustomerID;
}
/**
* #return the Custfirstname
*/
public String getCustfirstname() {
return Custfirstname;
}
/**
* #param Custfirstname the Custfirstname to set
*/
public void setCustfirstname(String Custfirstname) {
this.Custfirstname = Custfirstname;
}
/**
* #return the Custlastname
*/
public String getCustlastname() {
return Custlastname;
}
/**
* #param Custlastname the Custlastname to set
*/
public void setCustlastname(String Custlastname) {
this.Custlastname = Custlastname;
}
/**
* #return the Consultant
*/
public Consultant getConsultant() {
return Consultant;
}
/**
* #param Consultant the Consultant to set
*/
public void setConsultant(Consultant Consultant) {
this.Consultant = Consultant;
}
/**
* #return the CID
*/
public String getCID() {
return CID;
}
/**
* #param CID the CID to set
*/
public void setCID(String CID) {
this.CID = CID;
}
There are two forms were the consultant and customers details will be inputted.
In your Customer class are using Consultant class incorrectly.
You are trying to access a non-static method in a static way.
It is not clear if you have getter and setter methods then why you are trying to create a Consultant instance saperately. This looks to be incrrect in design perspective
What you can do is:
From a another class say MyApplication you can first set Consultant and using the same object you can pass it to Customer.
Consultant consultant = new Consultant("123");
consultant.setConsultantID("123");
consultant.setConsfirstname("firstname");
consultant.setConslastname("lastname");
Customer customer = new Customer();
customer.setConsultant(consultant);
This way your customer instance will have a reference to a Consultant instance in it with all the details. This is has-a relationship also called as a composition.
You are calling getConsultatntId in a static way. If your variable is not static you should call the method from a instance of the object (instead of the Class name)
That would look like:
Consumer c = new Consumer(1000);
Consultant con = new Consultant(c.getConsumerId());
Note that I'm calling getId from 'c' that is a instance of Consumer.
Firstly, you should make your Consultant constructor public. Secondly, you cannot access a non-static method in a static way, meaning you need to make a public static String getConsultantID() or something like this:
Consultant c = new Consultant("c2418");
Consultant d = new Consultant(c.getConsultantID());
Two things:
1:
To give a customer a consultant id, you would use an instance method instead of a static method:
Consultant james = new Consultant("123");
Customer customer1 = new Customer(james.getConsultantId());
2:
Consider using an Array or List of Customers in the Consultant class. It would seem more appropriate for a consultant to have multiple customers, rather than a single Consultant to Client relationship. In this way, you create a one-to-many relationship between Consultants and Customers.
Customers would have a reference to their Consultant, and Consultants would have a reference to all of their Customers.
public class Consultant extends Person implements Serializable {
public String ConsultantID;
private String Consfirstname;
private String Conslastname;
private ArrayList<Customer> customers;
Consultant(String consultantID) {
customers = new ArrayList();
}
public boolean addCustomer(Customer c){
customers.add(c);
}
//snipped for brevity
}
public class Customer extends Person implements Serializable {
private String CustomerID;
public String Custfirstname;
public String Custlastname;
public String CID;
Customer(Consultant c){
CID = c.getConsultantID();
}
//snipped for brevity
}
When you create the relationship, you'd create the customer first, assign them a consultant, then add the customer to the Consultant.
Consultant kingston = new Consultant("kingston88"); //created elsewhere
Customer jack = new Customer(kingston); //create customer, give id
kingston.add(jack); //assign customer to consultant
Related
I have an abstract class named Staff. Instructor and Lecturer are the derived classes from the Staff superclasses. I need to use hibernate annotations into the Instructor and Lecturer classes.
Staff.java
public abstract class Staff {
private int staffID;
private String firstName;
private String lastName;
private String mobile;
private String email;
private double salary;
private String city;
private String street;
//getters and setters
}
This is the subclass and I used staffID again in the subclass to apply the #Id annotation.
Lecturer.java
#Entity
#Table(name = "lecturer")
public class Lecturer extends Staff {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int staffID;
private int lectureHours;
public int getLectureHours() {
return lectureHours;
}
public void setLectureHours(int lectureHours) {
this.lectureHours = lectureHours;
}
}
I used the service classes and controllers and the JPARepositories as usually. but the database table only contain 2 values fields only (staffID and lectureHours). as follows.
LecturerRepository.java
package com.example.backend.admin.Repositories;
import com.example.backend.admin.models.Lecturer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface LecturerRepository extends JpaRepository<Lecturer, Integer> {
}
LecturerController.java
#RestController
#RequestMapping("/lecturers")
public class LecturerController {
private static Logger logger = LoggerFactory.getLogger(LecturerController.class);
#Autowired
LecturerService lecturerService;
/**
* to insert a new lecturer
* #param lecturer new lecturer
* #return insert lecturer
*/
#PostMapping("/add")
public Lecturer addLecturer(#RequestBody Lecturer lecturer) {
Lecturer lecturer1 = null;
try {
lecturer1 = lecturerService.addLecturer(lecturer);
} catch (NullPointerException e) {
logger.error("check the payload, null pointer is throwing", e);
}
return lecturer1;
}
}
LecturerService.java
#Service
public class LecturerService {
#Autowired
LecturerRepository lecturerRepository;
/**
* to invoke save method in jpa
* #param lecturer new lecturer
* #return inserted lecturer
*/
public Lecturer addLecturer(Lecturer lecturer){
return lecturerRepository.save(lecturer);
}
}
I want to add all the fields of the Lecturer class into the database. So what should I do for that?
You need to annotate the abstract class with #MappedSuperclass, in this way your #Entity class will inherit all the attributes from the extended class.
I would like to get objects ResponsableEntity by id from the Database where they are saved. I use Spring-boot and hibernate for the first time and the slouches on other topics don't work in my project
Here are my code :
ResponsableEntity :
#Entity
#Table(name = "responsable")
public class ResponsableEntity {
/**
* Id of the responsable
*/
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
/**
* First name of the responsable
*/
#Column(nullable=false)
private String firstName;
/**
* Lst name of the responsable
*/
#Column(nullable=false)
private String lastName;
/**
* Last latitude of the responsable position
*/
private Double latitude;
/**
* Last longitude of the responsable position
*/
private Double longitude;
/**
* All getters and setters [...]
*/
}
ResponsableDBRepository :
#Repository
public interface ResponsableDBRepository extends CrudRepository<ResponsableEntity, Long> {
}
ResponsableController (REST) :
#RestController
#RequestMapping("/responsable")
public class ResponsableController {
/**
* CRUD Repository atribut needed for the methods below
*/
private final ResponsableDBRepository responsableDBRepository;
private final ResponsableStatDBRepository responsableStatDBRepository;
/**
* Constructor
*
* #param responsableDBRepository CRUD repository for ResponsableEntity
* #param responsableStatDBRepository CRUD repository for ResponsableStatEntity
*/
#Autowired
public ResponsableController(ResponsableDBRepository responsableDBRepository, ResponsableStatDBRepository responsableStatDBRepository){
this.responsableDBRepository = responsableDBRepository;
this.responsableStatDBRepository = responsableStatDBRepository;
}
#GetMapping(path = "/get")
public #ResponseBody String getAllResponsable(){
//get object with id given
return "Returned";
}
}
I'd like that when we call this request, the entity is load from the database and an object ResponsableEntity is created with the infos saved in the database. I already tried most of the answer I found on other topics but most of the time my IDE told me he can't find the class required and it seems to be "default" classes from Hibernate and Spring
Thank you in advance for your answer !
Use this:-
ResponsableEntity responsableEntity = responsableDBRepository.findById(id);
I have a column name viewed_by on Firebase server
Test
|
|--viewed_by: 30
On the app I have a POJO class which has the member viewed_by
Test.class has member
private int viewed_by;
In onDataChange function when I receive the data, I get the Test object using the getValue function
Test t = dataSnapshot.getValue(Test.class);
But I get the value as 0 instead of 30.
If I change the field name from viewed_by to viewedBy (both on server and POJO class), I get the expected value (30)
Is it a parsing issue in getValue function? Or the field name are not supposed to have underscores in the name?
Jus figured it out, had to change the function names as well from ViewedBy to Viewed_By for it to work with viewed_by field
/**
*
* #return
* The viewed_by
*/
public int getViewed_By() {
return viewed_by;
}
/**
*
* #param viewed_by
* The viewed_by
*/
public void setViewed_By(int viewed_by) {
this.viewed_by = viewed_by;
}
Another option is to just declare the properties like below-using #PropertyName("property_name") in your model and use your getter and setter just like you like to do.
public class Actor {
#NonNull
#PrimaryKey
#ColumnInfo(name = "profile_id")
#PropertyName("profile_id")
private String profileId;
#ColumnInfo(name = "name")
#PropertyName("name")
private String name;
#PropertyName("profile_id")
public String getProfileId() {
return profileId;
}
#PropertyName("profile_id")
public void setProfileId(String profileId) {
this.profileId = profileId;
}
#PropertyName("name")
public String getName() {
return name;
}
}
I need help with this issue in JAXB, while I run the project I always got the error below
Property assignment is present but not specified in #XmlType.propOrder
this problem is related to the following location:
at public int edu.asu.cse446.sample1.server.test.GradBook.getAssignment()
at edu.asu.cse446.sample1.server.test.GradBook
This is my code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.asu.cse446.sample1.server.test;
/**
*
* #author luayalmamury
*/
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author luayalmamury
*/
#XmlRootElement
#XmlType(propOrder={
"id",
"Assignment",
"MidTerm",
"Quiz",
"ClassLab"})
public class GradBook {
private static final Logger LOG = LoggerFactory.getLogger(GradBook.class);
private int id;
private int Assignment;
private int MidTerm;
private int Quiz;
private int ClassLab;
public GradBook(){
LOG.info(" Creating Student Grade Object");
}
public int getId() {
return id;
}
#XmlAttribute // Read it in XML Format
public void setId(int id) {
LOG.info(" Setting Student Id", id);
this.id=id;
LOG.debug(" Update Student Id",this);
}
public int getAssignment() {
return Assignment;
}
#XmlElement
public void setAssignment(int Assignment) {
LOG.info(" Create Student Assignment",Assignment);
this.Assignment=Assignment;
LOG.debug("Update Student Assignment",this);
}
public int getMidTerm() {
return MidTerm;
}
#XmlElement // Read it in XML Format
public void setMidTerm(int MidTerm) {
LOG.info(" Create Student MidTerm ",MidTerm);
this.MidTerm=MidTerm;
LOG.debug("Update Student MidTerm ",this);
}
public int getQuiz() {
return Quiz;
}
#XmlElement // Read it in XML Format
public void setQuiz(int Quiz) {
LOG.info(" Create Student Quiz",Quiz);
this.Quiz=Quiz;
LOG.debug("Update Student Assignment",this);
}
public int getClassLab() {
return ClassLab;
}
#XmlElement // Read it in XML Format
public void setClassLab(int ClassLab) {
LOG.info(" Create Class Lab",ClassLab);
this.ClassLab=ClassLab;
LOG.debug("Update Student Class Lab",this);
}
#Override
public String toString() {
return "GradeBook{" + "id=" + id + ", Assignment=" + Assignment + ",MidTerm=" + MidTerm + " Quiz=" + Quiz + ", ClassLab=" + ClassLab + '}';
}
}
Okay. This is why they say - follow standard and conventions.
Problem is - you have member variable names capitalized.
Change them to something like - "id", "assignment", "midTerm", "quiz", "classLab" and it should work.
Based on an archetype i created a java ee app. There is an included arquillian test that runs fine. it just calls a method on a #Stateless bean that persists an pre-made entity.
now i added some entity with some relations and i wrote a test for them. But on peristing any entity i get
Transaction is required to perform this operation (either use a transaction or extended persistence context)
I think i need to mark the testmethod with #Transactional but it seems not to be in class path.
Manually invoking the transaction on injected EntityManager yields another error.
So how to correctly setup such tests and dependencies.
EDIT As Grzesiek D. suggested here are some details. this is the entity (the one thta links others):
#Entity
public class Booking implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* internal id.
*/
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", updatable = false, nullable = false)
private Long id;
/**
* Used for optimistic locking.
*/
#Version
#Column(name = "version")
private int version;
/**
* A booking must have a project related.
*/
#ManyToOne
#JoinColumn(name = "project_id")
#NotNull
private Project project;
/**
* A booking must have an owner.
*/
#ManyToOne
#JoinColumn(name = "user_id")
#NotNull
private User owner;
/**
* A booking always has a start time.
*/
#Column
#NotNull
private Timestamp start;
/**
* A booking always has an end time.
*/
#Column
#NotNull
private Timestamp end;
/**
*
* #return true if start is befor end. false otherwise (if equal or after end).
*/
#AssertTrue(message = "Start must before end.")
public final boolean isStartBeforeEnd() {
return start.compareTo(end) < 0;
}
/**
* #return the id
*/
public final Long getId() {
return id;
}
/**
* #param id
* the id to set
*/
public final void setId(final Long id) {
this.id = id;
}
/**
* #return the version
*/
public final int getVersion() {
return version;
}
/**
* #param version
* the version to set
*/
public final void setVersion(final int version) {
this.version = version;
}
/**
* #return the project
*/
public final Project getProject() {
return project;
}
/**
* #param project
* the project to set
*/
public final void setProject(final Project project) {
this.project = project;
}
/**
* #return the owner
*/
public final User getOwner() {
return owner;
}
/**
* #param owner
* the owner to set
*/
public final void setOwner(final User owner) {
this.owner = owner;
}
/**
* #return the start
*/
public final Timestamp getStart() {
return start;
}
/**
* #param start
* the start to set
*/
public final void setStart(final Timestamp start) {
this.start = start;
}
/**
* #return the end
*/
public final Timestamp getEnd() {
return end;
}
/**
* #param end
* the end to set
*/
public final void setEnd(final Timestamp end) {
this.end = end;
}
//hashCode, equals, toString omitted here
}
Here is the test:
#RunWith(Arquillian.class)
public class BookingTest {
#Deployment
public static Archive<?> createDeployment() {
return ArquillianContainer.addClasses(Resources.class, Booking.class, Project.class, User.class);
}
#Inject
private EntityManager em;
#Test
public void createBooking() {
Booking booking = new Booking();
booking.setStart(new Timestamp(0));
booking.setEnd(new Timestamp(2));
User user = new User();
user.setName("Klaus");
booking.setOwner(user);
Project project = new Project();
project.setName("theOne");
project.setDescription("blub");
booking.setProject(project);
em.persist(booking);
System.out.println("here");
}
}
And here the exception:
javax.persistence.TransactionRequiredException: JBAS011469: Transaction is required to perform this operation (either use a transaction or extended persistence context)
I know it will work if i create a #Stateless bean and encapsulate the persist there but i want a direct test of entity's validation and i need a playground to evolve the data model.
In order to have transaction support in Arquillian tests you will need to bring in extension which enables this feature. In your case jta dependency should do the job.
<dependency>
<groupId>org.jboss.arquillian.extension</groupId>
<artifactId>arquillian-transaction-jta</artifactId>
<scope>test</scope>
</dependency>
In addition, if you are using JBoss, you will need to provide its JNDI for UserTranscation, so put following section in your arquillian.xml:
<?xml version="1.0" ?>
<arquillian xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://jboss.org/schema/arquillian" xsi:schemaLocation="http://jboss.org/schema/arquillian
http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
<extension qualifier="transaction">
<property name="manager">java:jboss/UserTransaction</property>
</extension>
</arquillian>
This way you can use #Transactional which comes from this extension's API.