I was wondering if anyone could help me with a problem I am encountering when trying to extend a class. I want to be able to add a first name and a last name which is part of my base class to an extended class.
Here is a snippet from my base class Person.java
public class Person
{
private String firstName = "";
private String lastName = "";
private String id = "";
public Person()
{
}
public Person(String firstName, String lastName, String id)
{
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
}
And here is the class where I am trying to extend the base class:
public TeamMember(String firstName, String lastName, String team, String id, String role)
{
super(firstName, lastName);
this.team = team;
this.id = id;
this.role = role;
}
The error I receive is:
Error:(25, 9) java: constructor Person in class xxx.xxxx.xxx.xx
cannot be applied to given types;
required: no arguments
found: java.lang.String,java.lang.String
reason: actual and formal argument lists differ in length
I had to create a constructor that matched what was in the super() in the extended class in the base class.
This is what I added to the base class to make it work.
public Person(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
Try this.
public TeamMember(String firstName, String lastName, String team, String id, String role)
{
super(firstName, lastName, id);
this.team = team;
this.role = role;
}
Id is a private property of base class, so cannot be accessed in derived class.
private String id = "";
Related
My professor asked for us to make two separate java classes for a popular problem where you have to build an employee email based off of a first name, last name, and employee ID number.
If you'd like to see the problem:
Assignment
The problem is happening in the substring. I think I vaguely know why, but I'm not actually entirely sure how to solve the issue.
Here's the first class:
public class EmployeeSchmidt
{
public String FirstName = "";
public String LastName = "";
public String EmID = "";
public String Email = "";
public EmployeeSchmidt(String FirstName, String LastName, String EmID)
{
this.FirstName = FirstName;
this.LastName = LastName;
this.EmID = EmID;
Generator();
}
public String getFirstName()
{
return FirstName;
}
public void setFirstName(String em)
{
FirstName = em;
}
public String getLastName()
{
return LastName;
}
public void setLastName(String em)
{
LastName = em;
}
public String getEmID()
{
return EmID;
}
public void setEmID(String em)
{
EmID = em;
}
public String getEmail()
{
return Email;
}
public void setEmail(String em)
{
Email = em;
}
String fName = (FirstName.substring(0,2));
String lName = (LastName.substring(0,4));
String eID = (EmID.substring(3,4));
public void Generator()
{
Email = (fName + lName + eID + "#initech.com");
}
}
And the second class:
import java.util.Scanner;
public class EmployeeInfo
{
public static void main(String[] args)
{
EmployeeSchmidt em1 = new EmployeeSchmidt("","","");
Scanner in = new Scanner (System.in);
System.out.println("Please enter your first name.");
em1.setFirstName(in.next());
System.out.println("Please enter your last name.");
em1.setLastName(in.next());
System.out.println("Please enter your 5-digit Employee ID.");
em1.setEmID(in.next());
em1.Generator();
System.out.println();
System.out.println(em1.getFirstName());
System.out.println(em1.getLastName());
System.out.println(em1.getEmID());
System.out.println("Your Employee Email is " + em1.getEmail());
}
}
And this is the error I'm getting:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.substring(String.java:1963)
at EmployeeSchmidt.<init>(EmployeeSchmidt.java:57)
at EmployeeInfo.main(EmployeeInfo.java:6)
The Scanner isn't necessary, but our professor offered extra credit if we were able to do it. I'm just absolutely lost.
There is an error cause you are trying to substring the name variables and assign them to member variables in the class body. Not inside any method. As they will be empty strings when the class gets intialized, the exception is thrown.
Change the EmployeeSchmidt java class to following.
public class EmployeeSchmidt {
public String FirstName = "";
public String LastName = "";
public String EmID = "";
public String Email = "";
public EmployeeSchmidt(String FirstName, String LastName, String EmID) {
this.FirstName = FirstName;
this.LastName = LastName;
this.EmID = EmID;
Generator();
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String em) {
FirstName = em;
}
public String getLastName() {
return LastName;
}
public void setLastName(String em) {
LastName = em;
}
public String getEmID() {
return EmID;
}
public void setEmID(String em) {
EmID = em;
}
public String getEmail() {
return Email;
}
public void setEmail(String em) {
Email = em;
}
public void Generator() {
String fName = null;
if (FirstName != null && FirstName.length() >= 2) {
fName = (FirstName.substring(0, 2));
}
String lName = null;
if (LastName != null && LastName.length()>=4) {
lName = (LastName.substring(0, 4));
}
String eID = null;
if (EmID != null && EmID.length()>=4) {
eID = (EmID.substring(3, 4));
}
Email = (fName + lName + eID + "#initech.com");
}
}
Note the placement of the declarations of variables fName, lName, and eID in your code:
String fName = (FirstName.substring(0,2));
String lName = (LastName.substring(0,4));
String eID = (EmID.substring(3,4));
public void Generator()
{
Email = (fName + lName + eID + "#initech.com");
}
They are outside any method, and therefore they are instance variables. These initializations will be performed when each instance is initialized, before the body of the constructor. At that point, you are guaranteed that the base strings are all empty (because of their own, prior, initializers).
Perhaps you want those to be local variables of the Generator() method. In that case, their initializers would not run until Generator() is invoked, at which point the FirstName, LastName, and EmID variables will have the values set by the constructor.
Note, however, that even that does not fully protect you from an out-of-bounds string index. Consider, for instance, an employee whose last name is "Wu" -- that's fewer than four characters. There are two things you can do to solve this problem:
Pad the strings with blanks or some other character to ensure that they are at least as long as you need them to be before computing the substrings (and be prepared for trailing blanks/whatever in the results; example: fName = (FirstName + "..").subString(0,2);), or
Test the string lengths before trying to extract substrings, and use the whole string instead where appropriate. Alternatively, fail (throwing an exception) if the string is not long enough.
you must make the substring in method because if it outside the method you make substring of the
FirstName = "";
LastName = "";
EmID = "";
Email = "";
and that's error you want to substring of the input of user
you can make that solution make it in method
public String getinfo()
{ String fName = (FirstName.substring(0,2));
String lName = (LastName.substring(0,4));
String eID = (EmID.substring(3,4));
Email=Generator(fName,lName,eID);
return Email;}
public String Generator(String fName,String lName,String eID)
{
Email = (fName + lName + eID + "#initech.com");
return Email;
then in the second class you do that
System.out.println("Your Employee Email is " + em1.getinfo());
without Generator before
i hope you understand me
I am trying to get multiple values from a web page form and search the value from databate using hibernate query and retrieve the result and display it in a new page.
I need to get these text fields and even if any of the field is empty, I need to run a search query in database via controller and return set of results in a new page. I tried to store the result in array list of ArrayList but it didnt work. Could anyone please help me?
I am trying to get the text values from from web page in controller:
String lastname = request.getParameter("lastname");
String firstname = request.getParameter("firstname");
String gender = request.getParameter("gender");
String speciality = request.getParameter("speciality");
String keyword = request.getParameter("keyword");
I have Doctor's table which has all these texts fields stored. Lastname, firstname, gender, speciality. I have a class named doctor which links to the database.
#Entity
#Table(name="DOCTOR_DETAILS")
public class Doctor {
#Id
#Column (nullable=false)
private int npi;
#Column (nullable=false)
private String firstName;
#Column (nullable=false)
private String lastName;
#Column (nullable=false)
private String gender;
#Column (nullable=false)
private String speciality;
public int getNpi() {
return npi;
}
public void setNpi(int npi) {
this.npi = npi;
}
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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getSpeciality() {
return speciality;
}
public void setSpeciality(String speciality) {
this.speciality = speciality;
}
}
I need to run a select query to retrieve the records from table. Even if any of the 4 fields are empty, the query should retrieve the records.
try {
begin();
ArrayList <String> cntList = new ArrayList<String>();
Query q = getSession().createQuery("select * from
doctor where lastName = :lastName or firstName =:firstName or
gender=:gender or speciality = :speciality");
q.setString("username", username);
cntList = (ArrayList<String>) q.list();
commit();
return cntList;
}
I tried the below way of using Hibernate criteria, but I am getting an error. Am I going wrong anywhere?.
I wrote below code in my controller:
Below part in my DAO class which connects to the database.
But I am getting below error:
Could you please help me out?
The code worked fine and returned the list of results. I tried to follow the steps provided in tutorial point site, but I am getting a cast error.
"Type mismatch: cannot convert from int to doctor.
A type mismatch asking me to change
Doctor doctor = iterator.next();
to
int doctor = iterator.next();
which is something weird, since I cannot retrieve values from Doctor class.
You should use Hibernate criteria query with disjunction. It's been designed to handle this sort of situations. Try this code snippet
public List<Doctor> getSearchResult(String firstName, String lastName, String gender, String speciality, Session session) {
Criteria cr = session.createCriteria(Doctor.class);
Disjunction or = Restrictions.disjunction();
if (firstName != null)
or.add(Restrictions.ilike("firstName", firstName+"%"));
if (lastName != null)
or.add(Restrictions.ilike("lastName", "%"+lastName));
if (gender != null)
or.add(Restrictions.eq("gender", gender));
if (speciality != null)
or.add(Restrictions.ilike("speciality", "%"+speciality+"%"));
cr.add(or);
return (List<Doctor>) cr.list();
}
You can get idea about Hibernate Criteria queries here.
How to add a calculated field to an entity?
DB table
table person {
id number,
first_name varchar,
last_name varchar,
...
}
Java entity
public class person {
BigDecimal id;
String firstName;
String lastName;
...//getters and setters
//what to add here???
public String getFullName() {
return firstName + " " + lastname;
}
}
I tried adding #Transient, but the field is ignored when converting to json.
I tried just leaving the method there, throws an exception that the setter is missing. adding the setter throws another exception that the field does not exist in the DB.
I tried adding #Transient and #JsonPropert, but the field is ignored when converting to json.
I tried adding #Formula, but hibernate (i think) says it is not implemented.
The idea is to have a simple calculated field that is ignored by jpa/hibernate but is used by jackson.
How can I accomplish this?
EDIT
Example full class
#Entity
#Table(name="FDF_PATIENT_COUNTIE")
#JsonIdentityInfo(generator = JSOGGenerator.class)
#JsonIgnoreProperties(ignoreUnknown = true)
#Audited
public class PatientCounty extends FgaBaseClass {
private static final long serialVersionUID = 1425318521043179798L;
private BigDecimal id;
private County FCounties;
private Patient patients;
public PatientCounty() {
}
public PatientCounty(County FCounties, Patient patients) {
this.FCounties = FCounties;
this.patients = patients;
}
#SequenceGenerator(name="generator", sequenceName="FDF_PATIENT_COUNTIE_SEQ")
#Id
#GeneratedValue(strategy=SEQUENCE, generator="generator")
#Column(name="ID", unique=true, nullable=false, precision=22, scale=0)
public BigDecimal getId() {
return this.id;
}
public void setId(BigDecimal id) {
this.id = id;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="ID_F_COUNTIE")
public County getFCounties() {
return this.FCounties;
}
public void setFCounties(County FCounties) {
this.FCounties = FCounties;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="ID_FDF_PATIENT")
public Patient getPatients() {
return this.patients;
}
public void setPatients(Patient patients) {
this.patients = patients;
}
}
The method in myController looks like this
#RequestMapping(value="/{processId}/dependents", method=RequestMethod.POST,consumes="application/json")
#ResponseBody
public Dependents postdependent(#ModelAttribute ProcessContext process,#RequestBody Dependent dependent) {
return process.getDependents().addDependent(dependent);
}
My gets and delete work perfectly.
But whenever I do a post I am getting the request sent by the client was syntactically incorrect.
JSON for post request:
"{
'dependentId' : '1003',
'firstName' : 'Vishu',
'lastName' : 'poodari',
'birthDate' : '1970/04/15'
}"
Please I tried all combinations by using single quotes, doubles quotes everything.
I am using rest-shell for doing the operations.
Please find my Dependent Class
public class Dependent {
private String dependentId;
private String firstName;
private String lastName;
private String birthDate;
#JsonCreator
public Dependent(#JsonProperty("dependentId") String dependentId, #JsonProperty("firstName") String firstName, #JsonProperty("lastName")String lastName,
#JsonProperty("birthDate") String birthDate) {
this.dependentId = dependentId;
this.firstName = firstName;
this.lastName = lastName;
this.birthDate = birthDate;
}
public String getDependentId() {
return dependentId;
}
public void setDependentId(String dependentId) {
this.dependentId = dependentId;
}
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 getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
}
syntactically incorrect means problem with the json,please replace the single quote with double.
{"dependentId" : "1003",
"firstName" : "Vishu",
"lastName" : "poodari",
"birthDate" : "1970/04/15"
}
also check the json keys should match with your Dependent class attribute names, and the data should be convertible by the parser.
Error *The request sent by the client was syntactically incorrect"** in most of the case means that jackson is not able to desalinize(convert json string to object) because default constructor is missing.
In your case there is missing default constructor, you have parameterized constructor which override default and jackson is not able create object
public Dependent(#JsonProperty("dependentId") String dependentId, #JsonProperty("firstName") String firstName, #JsonProperty("lastName")String lastName,
#JsonProperty("birthDate") String birthDate) { this.dependentId = dependentId;
this.firstName = firstName;
this.lastName = lastName;
this.birthDate = birthDate;
}
Add also default constructor into your class and everything will be working
public Dependent() {
}
When using curl (on dos) i had the same problem. I needed to use all double quotes and therefore mask the ones within the body part:
C:>curl -H "Content-Type: application/json" -X POST -d "{\"id\":1,\"firstName\":\"Hans\",\"lastName\":\"Muster\"}" http://localhost:8081/persons
I'm gonna try to explain my problem as well I can
I have some user groups to manage user rights.
Some users may be customers. There's a OneToOne connection between the user table and the customers table. And a OneToOne connection between users and groups. When I delete a client, I would like the user group changes from customer to user, the default group (Id=4).
With this code:
public static void delete(Long id) {
Customer entity = Customer.findById(id);
User entityUser = User.findById(entity.user.id);
entity.delete();
entityUser.groups.id = (long)4;
entityUser.merge();
entityUser.save();
flash.success(Messages.get("Users.deleted"));
Customers.list();
}
Group model:
#Entity
#Table(name = "groups")
public class Group extends Model{
#Required
public String name;
#Required
public String description;
public Group(String name, String description)
{
this.name = name;
this.description = description;
}
User model:
#Entity
#Table(name = "users")
public class User extends Model{
#Required
public String firstname;
#Required
public String lastname;
#As("dd/MM/yyyy")
#Required
public Date birthday;
#Required
public String avatar;
#Required
public String adress;
#Required
public String phonenumber;
#Required
#Email
public String email;
#Required
public String username;
#Required
#Password
public String password;
#OneToOne
#Required
public Group groups;
public User(
String firstname,
String lastname,
#As("dd/MM/yyyy") Date birthday,
String avatar,
String adress,
String phonenumber,
String email,
String username,
String password,
Group groups
)
{
if(groups == null){
groups.id = (long)4;
}
else
{
this.groups = groups;
}
this.firstname = firstname;
this.lastname = lastname;
this.birthday = birthday;
this.avatar = avatar;
this.adress = adress;
this.phonenumber = phonenumber;
this.email = email;
this.username = username;
this.password = password;
}
Customer model:
#Entity
#Table(name = "customers")
public class Customer extends Model{
#As("dd/MM/yyyy")
public Date dateinscription;
public Double amountdue;
public Double amountpaid;
#Required
public String picture;
#OneToOne
public User user;
public Customer(#As("dd/MM/yyyy") Date dateinscription, Double amountdue, Doubleamountpaid, String picture, User user)
{
this.dateinscription = dateinscription;
this.amountdue = amountdue;
this.amountpaid = amountpaid;
this.picture = picture;
this.user = user;
}
}
But I've got an error:
PersistenceException occured : org.hibernate.HibernateException: identifier of an instance of models.Group was altered from 3 to 4
In /app/controllers/Customers.java (around line 69)
65:
66:
entityUser.groups.id = (long)4;
67:
68:
entityUser.merge();
69:
entityUser.save();
70:
71:
flash.success(Messages.get("Users.deleted"));
72:
Customers.list();
73:
74:
}
75:
I tried with GenericModel but it didn’t work.
Please help me !!
Thank you.
In your code, you are explicitly changing the ID of the group, not the group. Hibernate assumes you want to change that field. But when you try to save the change, it won't let you, since it's the ID. It doesn't assume you mean "change the group to the one that has an ID of 4."
Instead, you'll need to load the default group, and set the user's group that that group.
Group group = Group.findById(4);
entityUser.groups = group;