Student, Faculty, Staff Directory in Java - java

I am just getting into Java and I have a project due for my class soon and keep running into the same error. I am to create a student, faculty, staff directory that can add new entries, update them, and print them using the to String() method. I was recommended to use a treeMap collection also. The error involves the .getKey() method and being unable to find it. I will include my code and would greatly appreciate any input to help me figure this out. Thank you in advance.
import java.util.TreeMap;
import java.util.*;
import java.util.Map.Entry;
import java.util.Iterator;
import java.util.Map;
/**
* Write a description of class Persons here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class Directory {
private String firstName, lastName;
private TreeMap<String, Persons> schoolDirectory;
private int numberInDirectory;
public Directory() {
schoolDirectory = new TreeMap<String, Persons>();
}
public String getKey() {
return lastName + firstName;
}
public void addPerson(Persons newPersons) {
schoolDirectory.put(Persons.getKey(), newPersons);
numberInDirectory++;
}
public void addPerson(Staff newStaff) {
schoolDirectory.put(newStaff.getKey(), newStaff);
numberInDirectory++;
}
public int getNumber() {
return numberInDirectory;
}
public class Persons {
// instance variables - replace the example below with your own
private String firstName;
private String lastName;
private String email;
}
}
/**
* Write a description of class People here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class People extends Directory {
private String firstName, lastName, emailAddress, phoneNumber, ID;
public People(String firstName, String lastName, String emailAddress, String phoneNumber, String ID) {
this.firstName = firstName;
this.lastName = lastName;
this.emailAddress = emailAddress;
this.phoneNumber = phoneNumber;
this.ID = ID;
}
public String getKey() {
return lastName + firstName;
}
}
/**
* Write a description of class Students here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class Students extends People {
// instance variables - replace the example below with your own
private String classlevel;
private int SudentID;
}
/**
* Write a description of class Faculty here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class Faculty extends People {
private String RoomNumber;
private String EmployeeStatus;
private String ProgramOfInstruction;
public Faculty(String firstName, String lastName, String emailAddress, String phoneNumber, String ID, String room, String status, String instruction) {
super(firstName, lastName, emailAddress, phoneNumber, ID);
RoomNumber = room;
EmployeeStatus = status;
ProgramOfInstruction = instruction;
}
}
/**
* Write a description of class Staff here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class Staff extends People {
private String OfficeNumber;
private String JobTitle;
public Staff(String firstName, String lastName, String emailAddress, String phoneNumber, String ID, String office, String position) {
super(firstName, lastName, emailAddress, phoneNumber, ID);
OfficeNumber = office;
JobTitle = position;
}
}

First of all change:
import java.util.TreeMap;
import java.util.*;
import java.util.Map.Entry;
import java.util.Iterator;
import java.util.Map;
to just:
import java.util.*
(this is just to keep things tidy)
then I would recommend using a Map or HashMap instead of a treeMap (However I am unfamiliar with treeMap)
EDIT: just change Persons.getKey() to newPersons.getKey()
You were trying to call it statically.
Hope this helps!

Related

Room one-to-many warning

When creating my contact DAO and related classes, I am getting the following error:
The query returns some columns [mContactId, mAddress, mPostcode, mCity, mCountry, mAddressType]
which are not used by org.linphone.contacts.managementWS.ContactWithAddresses. You can use
#ColumnInfo annotation on the fields to specify the mapping.
org.linphone.contacts.managementWS.ContactWithAddresses has some fields [mName, mSurname,
mFullName, mCompany, mNote, mIsBlocked] which are not returned by the query. If they are not
supposed to be read from the result, you can mark them with #Ignore annotation. You can suppress
this warning by annotating the method with #SuppressWarnings(RoomWarnings.CURSOR_MISMATCH).
Columns returned by the query: id, mContactId, mAddress, mPostcode, mCity, mCountry,
mAddressType. Fields in org.linphone.contacts.managementWS.ContactWithAddresses: id, mName,
mSurname, mFullName, mCompany, mNote, mIsBlocked.
In my ContactsDao:
#Query("SELECT * FROM contacts_table")
List<Contact> getAll();
#Transaction
#Query("SELECT * FROM phone_numbers_table")
List<ContactWithNumbers> getContactsWithPhoneNumbers();
ContactsWithNumbers.java:
#Embedded public Contact contact;
#Relation(parentColumn = "id", entityColumn = "mContactId", entity = PhoneNumbers.class)
public List<PhoneNumbers> numbers;
And below is my Contact.java:
#Entity(tableName = "contacts_table")
public class Contact {
// TODO - members should be private, not public. Changed to workaround error.
#PrimaryKey(autoGenerate = true)
public int id;
/* String resource ID for the user name */
#SerializedName("first_name")
public String mName;
/* String resource ID for the user surname */
#SerializedName("last_name")
public String mSurname;
/* String resource ID for the user's full name */
#SerializedName("full_name")
public String mFullName;
/* String resource ID for the user company */
#SerializedName("company")
public String mCompany;
/* String resource ID for the user's phone number(s) */
/** String resource ID for the user's note */
#SerializedName("note")
public String mNote;
#SerializedName("blocked")
public boolean mIsBlocked;
/**
* #param firstName
* #param lastName
* #param fullName
* #param company
* #param note
* #param isBlocked
*/
#Ignore
public Contact(
String firstName,
String lastName,
String fullName,
String company,
String note,
boolean isBlocked) {
super();
this.mName = firstName;
this.mSurname = lastName;
this.mFullName = fullName;
this.mCompany = company;
this.mNote = note;
this.mIsBlocked = isBlocked;
}
public Contact(String name, String surname, String company, String note, boolean isBlocked) {
this.mName = name;
this.mSurname = surname;
this.mCompany = company;
this.mNote = note;
this.mIsBlocked = isBlocked;
}
public int getId() {
return id;
}
public String getmName() {
return mName;
}
public String getmSurname() {
return mSurname;
}
public String getmFullName() {
return mName + " " + mSurname;
}
public String getmCompany() {
return mCompany;
}
public String getmNote() {
return mNote;
}
public boolean getmIsBlocked() {
return mIsBlocked;
}
}
It is quite likely that I have not fully grasped the concept of Room one-to-many relations, but what exactly am I doing wrong here and getting that warning?
It's say very clear: You can use #ColumnInfo annotation on the fields to specify the mapping.
Change your code like this:
#NonNull
#PrimaryKey
#ColumnInfo(name = "id")
private String id;
More at codelab: https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#0

Writing a Spring Boot application using an in-memory H2 Database

I am trying to create a in memory database in spring boot... Still learning about spring boot and databases. How would I create an in memory database for this.
I want to create an in memory database with 3 REST endpoints...
This is what I've done so far:
package com.jason.spring_boot;
/**
* The representational that holds all the fields
* and methods
* #author Jason Truter
*
*/
public class Employee {
private final long id;
private final String name;
private final String surname;
private final String gender;
public Employee(long id, String name, String surname, String gender){
this.id = id;
this.name = name;
this.surname = surname;
this.gender = gender;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getGender() {
return gender;
}
}
package com.jason.spring_boot;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* The resource controller handles requests
* #author Jason Truter
*
*/
#Controller
#RequestMapping("/employee")
public class EmployeeController {
private final AtomicLong counter = new AtomicLong();
/**
* GET method will request and return the resource
*/
#RequestMapping(method=RequestMethod.GET)
public #ResponseBody Employee getEmployee(#RequestParam(value = "name", defaultValue = "Stranger") String name,
String surname, String gender){
return new Employee(counter.getAndIncrement(), name, surname, gender);
}
}
package com.jason.spring_boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

Model class is being embedded without specifying #Embeddable annotation to the class

I have been trying hibernate-core-4.3.10.Final.jar to create a dummy project. I have created model class UserDetails which have one Address field which is in fact an embeddable object. In model class I have declared this field with #Embedded annotation but I haven't defined Address class as Embeddable using #Embeddable annotation. Still the object is being embedded in the UserDeatils entity. Is #Embeddable annotation optional?? Is #Embedded annotation sufficient for hibernate to do the mapping accordingly?
Following are the code snippets:-
/** UserDetails Class **/
package com.st.hibernate.models;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
#Entity
#Table(name="USER_DETAILS")
public class UserDetails {
#Id
#Column(name="USER_ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="USER_NAME")
#Transient
private String userName;
#Embedded
private Address address;
/**
* #return the address
*/
public Address getAddress() {
return address;
}
/**
* #param address the address to set
*/
public void setAddress(Address address) {
this.address = address;
}
#Temporal(TemporalType.DATE)
private Date currentDate;
#Lob // Large Objects----> CLob/BLob---->Character/Byte Larger Object
private String description;
/**
* #return the description
*/
public String getDescription() {
return description;
}
/**
* #param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* #return the currentDate
*/
public Date getCurrentDate() {
return currentDate;
}
/**
* #param currentDate the currentDate to set
*/
public void setCurrentDate(Date currentDate) {
this.currentDate = currentDate;
}
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* #return the userName
*/
public String getUserName() {
return userName;
}
/**
* #param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
}
and Address Class:-
package com.st.hibernate.models;
public class Address {
private String pincode;
private String city;
private String state;
/**
* #return the pincode
*/
public String getPincode() {
return pincode;
}
/**
* #param pincode the pincode to set
*/
public void setPincode(String pincode) {
this.pincode = pincode;
}
/**
* #return the city
*/
public String getCity() {
return city;
}
/**
* #param city the city to set
*/
public void setCity(String city) {
this.city = city;
}
/**
* #return the state
*/
public String getState() {
return state;
}
/**
* #param state the state to set
*/
public void setState(String state) {
this.state = state;
}
}
Thanks in advance.

Calling A Created Class In A Test Class In Java

I have created a public class: Employee. Now I would like to create a drive class to test this new class. However, I cannot figure out how to call my created class within the driver class: EmployeeTest. I have placed each class (Employee and EmployeeTest) in the same directory; however, I am still receiving the error message: "Cannot find class Employee."
Can anyone help me to get on the right track?
Here is my code for class Employee:
package employee;
/**
*
* #author ljferris
*/
public class Employee {
private String first; // Instance variable for first name
private String last; // Instance variable for last name
public double salary; // Instance variable for monthly salary
// Constructor initializes first with parameter firstName and intializes last with parameter lastName
public Employee(String firstName, String lastName){
this.first = firstName;
this.last = lastName;
}
// Constructor initializes salary with parameter monthlySalary
public Employee(double monthlySalary){
this.salary = monthlySalary;
}
// Method to set the first and last name
public void setName(String firstName, String lastName){
this.first = firstName;
this.last = lastName;
}
// Method to set the monthly salary
public void setSalary (double monthlySalary){
this.salary = monthlySalary;
if (salary > 0.0)
this.salary = monthlySalary;
}
// Method to retrive the first and last name
public String getName(){
return first + last;
}
// Method to retrive monthly Salary
public double getSalary (){
return salary;
}
} // End class Employee
Here is the code for EmployeeTest:
package employeetest;
/**
*
* #author ljferris
*/
import java.util.Scanner;
public class EmployeeTest {
public static void main(String[] args) {
Employee employee1 = new Employee("Leviticus Ferris", 1200.00);
}
As per your code Employee and EmployeeTest are in different packages. You need to add import employee in EmployeeTest class. Then you can create new Employee instance from EmployeeTest.
package employeetest;
import employee;
import java.util.Scanner;
public class EmployeeTest {
public static void main(String[] args) {
Employee employee1 = new Employee("Leviticus Ferris", 1200.00);
}
UPDATE For below comment:
Add one more constructor with firstName and salary as parameters.
public Employee(String firstName, double salary){
this.first = firstName;
this.salary = salary;
}
If you want 3 values to be intialized. Add one more constructor by taking all fields.
public Employee(String firstName, String lastName, double salary){
this.first = firstName;
this.last = lastName;
this.salary = salary;
}

StackOverflowError on Hibernate Save

I have a Student table with an auto generated id as primary key and one to many mappings to Phone table.
My Phone table has a composite primary key PhonePK with phone number and the foreign key id to the Student table.
If I just do student.setPhones and not do phonepk.setStudent, its complaining about id cannot be null. So I am setting student.setPhones and phonePk.setStudent. But now I am getting a stackoverflow error on toString.
I really don't like setting it on both ways in the first place but don't know how to get around the id cannot be null error. I've been asking lot of people but they could not help. Could someone take a look please?
Student.java
import java.io.Serializable;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
#Entity
#SuppressWarnings("serial")
public class Student implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String fName;
private String lName;
private String mName;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "id")
private Set<Phone> phones;
/**
* #return the fName
*/
public String getfName() {
return fName;
}
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #return the lName
*/
public String getlName() {
return lName;
}
/**
* #return the mName
*/
public String getmName() {
return mName;
}
/**
* #return the phones
*/
public Set<Phone> getPhones() {
return phones;
}
/**
* #param fName
* the fName to set
*/
public void setfName(final String fName) {
this.fName = fName;
}
/**
* #param id
* the id to set
*/
public void setId(final int id) {
this.id = id;
}
/**
* #param lName
* the lName to set
*/
public void setlName(final String lName) {
this.lName = lName;
}
/**
* #param mName
* the mName to set
*/
public void setmName(final String mName) {
this.mName = mName;
}
/**
* #param phones
* the phones to set
*/
public void setPhones(final Set<Phone> phones) {
this.phones = phones;
}
/**
* {#inheritDoc}
*/
#Override
public String toString() {
return String.format("Student [id=%s, fname=%s, lname=%s, mname=%s, phones=%s]",
id,
fName, lName, mName, phones);
}
}
Phone.java
import java.io.Serializable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
#Entity
#SuppressWarnings("serial")
public class Phone implements Serializable {
#EmbeddedId
private PhonePK PK;
private String color;
/**
* #return the color
*/
public String getColor() {
return color;
}
public PhonePK getPK() {
return PK;
}
/**
* #param color
* the color to set
*/
public void setColor(final String color) {
this.color = color;
}
public void setPK(final PhonePK pK) {
PK = pK;
}
/**
* {#inheritDoc}
*/
#Override
public String toString() {
return String.format("Phone [PK=%s, color=%s]", PK, color);
}
}
PhonePK.java
import java.io.Serializable;
import javax.persistence.Embeddable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Embeddable
#SuppressWarnings({ "serial" })
public class PhonePK implements Serializable {
#ManyToOne
#JoinColumn(name = "id", insertable = false, updatable = false)
private Student student;
private String phoneNumber;
public String getPhoneNumber() {
return phoneNumber;
}
public Student getStudent() {
return student;
}
public void setPhoneNumber(final String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setStudent(final Student student) {
this.student = student;
}
/**
* {#inheritDoc}
*/
#Override
public String toString() {
return String.format("PhonePK [student=%s, phoneNumber=%s]", student, phoneNumber);
}
}
Main.java
import java.util.LinkedHashSet;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(final String args[]) {
Configuration configuration = new Configuration();
Transaction transaction = null;
configuration.addAnnotatedClass(Student.class);
configuration.addAnnotatedClass(Phone.class);
configuration.configure("hibernate.cfg.xml");
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Student student = new Student();
student.setfName("Bob");
student.setlName("Buster");
Set<Phone> phones = new LinkedHashSet<Phone>();
Phone phone = new Phone();
phone.setColor("Black");
PhonePK phonePK = new PhonePK();
phonePK.setPhoneNumber("1111111111");
phonePK.setStudent(student); // Do not do this? But won't work (id cannot be null
error) if
// commented out??
phone.setPK(phonePK);
phones.add(phone);
student.setPhones(phones);
try {
transaction = session.beginTransaction();
System.out.println(student.toString()); // stackoverflow error!
session.save(student);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
It is happening because of the way you have defined toString() methods
Student's toString() is invoking Phone's toString() which is invoking PhonePK's toString() which in turn is invoking Student's toString()...causing infinite loop.
Let see how it is happening in detailed way
In Student toString() because of phones instance variable in it .it will iterate through each phone and call Phone toString()
public String toString() {
return String.format("Student [id=%s, fname=%s, lname=%s, mname=%s, phones=%s]",
id,
fName, lName, mName, phones);
}
In Phone toString() because of PK instance variable in it .it will invoke PhonePK toString()
public String toString() {
return String.format("Phone [PK=%s, color=%s]", PK, color);
}
In PhonePK toString() because of phoneNumber instance variable in it .it will invoke Phone toString()
public String toString() {
return String.format("PhonePK [student=%s, phoneNumber=%s]", student, phoneNumber);
}

Categories

Resources