Inherited parent class values are not reflected in JPA save entity - java

I have a class Vehicle and Car
Vehicle extends Car
Lets take an example
Class Vehicle {
String vehicleMade;
boolean fourWheeler;
Vehicle(String vehicleMade, boolean fourWheeler) {
this.vehicleMade=vehicleMade;
this.fourWheeler=fourWheeler;
}
// getters and setters
}
Class Car extends Vehicle {
String model;
Car(String vehicleMade, boolean fourWheeler) {
super(vehicleMade, fourWheeler);
}
// getters and setters
}
Class JavaMainClass {
private static CarInfoRepository carInfoRepo;
private static AnnotationConfigApplicationContext ctx;
public static void main(String args[]) {
carInfoRepo= ctx.getBean(CarInfoRepository.class);
//Now where I have doubt and problem
Car carInfo = new Car("Bentley", true);
carinfo.setModel("Flying Spur");
log.debug(carInfo.getVehicleMade); // I get Bentley here
carInfoRepo.save(carInfo);
}
}
Now when I get the car object from the repo, I get vehicleMade and fourWheeler attribute as null
You can see when I get that vehicleMade before saving but after saving to the repo I am getting null as the attribute.

Related

Can you change a immutable class?

This is a theoretical question for practice.
The question is
Create an immutable class Car.
Create some instances of car to fill an Arraylist<Car> inside a Garage class.
The MyGarage class implements these methods from Garage:
getCar(String reg) – search for the car with registration number reg.
getMake(String make) – returns a list of cars that match the given make.
totalValue() – calculates the total value of all cars in the list.
changeOwner(String reg, String ow) – change the owner of car that has registration number reg to ow.
I do not understand the changeOwner method as it is not suppose to be able to change a instances of a immutable class I thought???
This is what I have done to work around it but just seems silly
import java.util.ArrayList;
public class MyGarage implements Garage {
private ArrayList<Car> myGarage;
public MyGarage() {
myGarage = new ArrayList<Car>();
}
#Override
//Adds a Car if the registration is unique
public boolean add(Car c) {
for(Car car : myGarage) {
if(car.getRegistration().equals(c.getRegistration())) {
System.out.println("Car has the same Registration as another illegal");
return false;
}
}
myGarage.add(new Car(c.getOwner(),c.getRegistration(),c.getMake(),c.getkilometres(), c.getprice()));
return true;
}
#Override
public Car getCar(String carID) {
for(Car car : myGarage) {
if(carID.equals(car.getRegistration())) {
System.out.println("Car Found");
return car;
}
}
System.out.println("No car of that record");
return null;
}
#Override
public ArrayList<Car> getMake(String make) {
ArrayList<Car> carModel = new ArrayList<Car>();
for(Car car : myGarage) {
if (car.getMake().equals(make)) {
carModel.add(car);
}
}
System.out.println(carModel.toString());
return carModel;
}
#Override
public void totalValue() {
double amount = 0;
for(Car car : myGarage) {
amount = car.getprice() + amount;
}
System.out.println("The total amount is: " + amount);
}
#Override
public boolean changeOwner(String registration, String ow) {
for(Car car : myGarage) {
if(car.getRegistration().equals(registration)) {
myGarage.remove(car);
car = new Car(ow, "444","F-50", 4, 4000.99);
myGarage.add(car);
return true;
}
}
return false;
}
}
In object-oriented and functional programming, an immutable object
(unchangeable object) is an object whose state cannot be modified
after it is created. This is in contrast to a mutable object
(changeable object), which can be modified after it is created. In
some cases, an object is considered immutable even if some internally
used attributes change, but the object's state appears unchanging from
an external point of view. - WikiPedia
Immutable objects are thus instances whose state doesn’t change after they have been initialized. These types of classes are generally good for applications that need to implement some form of caching and where you are worried about thread-safety in a multi-threaded environment (immutable objects are inherently thread-safe).
I don't see your Car class, but assuming it'll look something like this:
public final class Car {
final String registration;
final String owner;
public Car(String registration, String owner) {
this.registration = registration;
this.owner= owner;
}
public String getRegistration() {
return registration;
}
public String getOwner() {
return owner;
}
}
... notice that there are no setter methods in this class. Hence a car can only be initialized (i.e Car myCar = new Car("abcd", "John"); and the variables in them (namely, registration and owner) can never be updated.
So your changeOwner method is essentially looping through the instances of car in your garage and when it finds a matching registration number it removes that instance of car from your garage and then adds a whole new one.
To demonstrate this, you can run the following:
public class Garage {
public static void main(String ... args) {
List<Car> myGarage = new ArrayList<>();
myGarage.add(new Car("CG404GH", "John"));
System.out.println(myGarage);
for(Car car : myGarage) {
if("CG404GH".equals(car.getRegistration())) {
myGarage.remove(car);
Car updateCar = new Car("DD404GH", "John");
myGarage.add(updateCar);
}
}
System.out.println(myGarage);
}
}
This would print out something similar to the following (the portion after the # would be different on each run):
[Car#4411d970]
[Car#6442b0a6]
The important thing to notice here is that the value after the # are different, hence they are two completely different classes (instances) of car

Instantiate objects using a helper class

I want to create an instance of my object, car. The problem I have is that i can create an instance of the car object such as, Car car1 = new car("Audi","A4","BF10YMR"); however I want to create car objects through a helper class. How do I call this helper class in main so that is of type car and not of type carHelper?
The car object requires a random registration number to be created and this is created in the carHelper class. The object is returned.
public class Car implements Comparable<Car>
{
public class Car
{
private String make;
private String model;
private String registration;
public Car(String make, String model, String reg)
{
this.make= make;
this.model= model;
registration = reg;
}
}
public class carHelper
{
public car genCar()
{
String reg = //some method to generate random registration.
String Make = //some method to randomly pick make from a list
String model = //some method to randomly pick model from a list
return new Car(make,model,registration);
}
}
public class Garage
{
public static void main (String args[])
{
Garage MyGarage = new Garage();
Car car1 = new Car("Audi","A4","BF10YMR") //works, but doesn't use helper
Car car2 = carHelper.genCar(); // something like this?
carHelper c = new carHelper(); // thought something like this but
System.out.println(c.genCar()); // creates object of type carHelper
// not car.
MyGarage.add(car1);
MyGarage.add(car2); // gives me carHelper cannot be converted to Car
}
}
public class GarageOp implements CarList
{
public GarageOp()
{
list = new ArrayList<Car>();
}
public boolean add(Car car)
{
if (list.contains(car) == false)
{
list.add(car);
return true;
}
}
}
Expected result is create car object using the helper class and add it to an ArrayList.
You could create this lists in the CarHelper and than, randomly, select the values and create a new Car with them. The UUID creates a random 128 bits (including hex) number and converts to a String
public class CarHelper {
private List<String> makeList = Arrays.asList("s", "t", "f", "n");
private List<String> modelList = Arrays.asList("yyt", "32g", "dc3", "aas");
public Car genCar() {
String reg = UUID.randomUUID().toString();
String make = makeList.get(new Random().nextInt(makeList.size() - 1));
String model = modelList.get(new Random().nextInt(modelList.size() - 1));
return new Car(make,model,reg);
}
}
Make the genCar() method as Static in the CarHelper class.
public car static genCar(){
// do stuff to create object
}
a non-static method can access a static variable or call a static method in Java.

Need to code Manager and Employee classes. How do I make them "visible" to each other without breaking encapsulation?

The Manager and the Employee classes are both subclasses of EnterpriseMember. How do I write a "getManager" method (that returns the Manager instance that has this Employee in their List of reports) for the Employee class?
Thanks in advance!
public class Manager extends EnterpriseMember {
/*Fields */
private List reports = new ArrayList();
/*Constructor */
public Manager(String name){
super(name);
}
/*Methods */
public void addReport(Employee employee){
reports.add(employee);
}// How can "employee" know it is in this List?
}
public class Employee extends EnterpriseMember {
/*Constructor */
public Manager(String name){
super(name);
}
/*Methods */
public Manager getManager(){
return ???;
}
}
Something like this:
public class Manager {
private List<Employee> reports = new ArrayList<Employee>();
public void addReport(Employee e) {
if (e != null) {
this.reports.add(e);
e.setManager(this);
}
}
}
public class Employee {
private Manager manager;
public void setManager(Manager m) {
if (m != null) {
this.manager = m;
}
}
}
Just in case it's not clear, you should add all the other methods you need. I only illustrated how to update the Manager reference in Employee when it's added to the List of direct reports.
You should also have a removeReport method that removes an Employee from the List and sets its Manager to null.
How do you intend to find an Employee in this List? By name? Employee id? Hint: think about overriding equals and hashCode properly for your classes.
Aren't Managers also Employees? Don't bosses have bosses? This is a hierarchy, a tree.
Usually a Object with different Attributes looks like this:
public class Employee extends EnterpriseMember {
private Manager manager;
private String name; // You probably don't need this because you defined it in the Superclass.
.
.
.
/*Constructor */
public Employee(String name){
super(name);
}
/*Methods */
public Manager getManager(){
return manager;
}
public void setManager(Manager manager){
this.manager = manager
}
// Other getters and setters for the attributes.
}

Accessing particular, the same instance of an object from different java classes

I have 4 different classes: Main, Employee, Company and HRDepartment
Class Company stores employees, new instances of Employees are created in this class
John Doe instance was created in Company class
How to access this particular instance in other classes to change its fields/invoke methods
Please find code below. Thank you.
public class Main
{
public static void main(String[] args)
{
HRDepartment hr = new HRDepartment();
hr.payRenumeration(5000);
// how to print cash of John Doe? I can't type System.out.println(john_doe.getCash())
// because this instance was created in another class
}
}
public class Employee
{
private double cash;
public void addCash(double cash)
{
this.cash += cash;
}
public double getCash()
{
return cash;
}
}
public class Company
{
// New employee is created in Company system
Employee john_doe = new Employee();
}
public class HRDepartment
{
public void payRenumeration(double renumerationToPay)
{
// how to access instance john_doe created in Company class?
// if this was in the same class I could type simply john_doe.addCash(renumerationToPay);
}
}

Java - project, adding an object to class

I am currently struggling to figure out this problem for my project. I currently have a Food class that stores name, price and description with getters and setters and a toString. And a course class with subclasses (starter, main dessert). I am trying to figure out how to attach a Food to a Course.
public abstract class Course{
//fields
//protected only accessible to subclasses
protected MenuList starter;
protected MenuList main;
protected MenuList dessert;
protected MenuList drinks;
//Constructor
public Course(){
starter = new MenuList();
main = new MenuList();
dessert = new MenuList();
drinks = new MenuList();
}
//getters and setters
//methods
public abstract MenuList getList();
//add item
public void addItem(String course, String foodName, double price, String description, int calories){
this.addItem(course, foodName, price, description, calories);
}
}
starter subclass its the same with main and dessert subclasses
public class StarterFood extends Course{
//fields
//constructor
public StarterFood(){
//course,
starter.addItem("starter", "chicken wings", 2.30, "very nice", 150, false);
}
#Override
public MenuList getList() {
return starter;
}
//Constructors
//getters and setters
//methods
}
so far ive:
adding food (with a name, price, description, calories)
listing all food items
adding courses
searching for a course (by course number or name)
listing all courses
I only need to do this but I'm struggling any help is appreciated
attaching food to courses
If your trying to add a Food to a Course, you should use a "has a" relationship for example:
public class Course {
private Food food;
public Course(Food food) {
this.food = food;
}
public Course() {
}
public Food getFood() {
return this.food;
}
public void setFood(Food food) {
this.food = food;
}
}
I also wouldn't use StarterFood to extend a Course, because extends is for and "is a" relationship, I would call it StarterCourse and then add a default food for that course in the constructor.
public class StarterCourse extends Course {
public StarterCourse(Food food) {
// here call the super classes constructor
// add items via the Course constructor
super(food);
}
}
Then in your main class to test it out try this:
public class Main() {
public static void main() {
// First create new Food object
Food food = new Food();
// Create a new StarterCourse and add the Food object to it
StarterCourse starterCourse = new StarterCourse(food);
}
}

Categories

Resources