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);
}
}
Related
Getting null values in database for the embedded Address entity. Using MySql database. The user entity is storing values fine but embedded Address entity is returning null value, can't figure out why it's not working. help me out guys.I am a beginner tried searching everywhere but no luck. Just a novice Api but it won't work the way i want it's really annoying.
Model class
package com.example.demo;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class User {
#Id
private int id;
private String name;
#Embedded
private Address address;
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String toString() {
return "user [id=" + id + ", name=" + name + ",Address="+address+" ]";
}
public User(int id, String name, Address address) {
this.id = id;
this.name = name;
this.address = address;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
---------------------------------------------------------------------------------------------------------
**Model class**
package com.example.demo;
import javax.persistence.Embeddable;
#Embeddable
public class Address {
private String cityname;
private String streetname;
private String Housename;
public Address() {
}
public Address(String cityname, String streetname, String housename) {
super();
this.cityname = cityname;
this.streetname = streetname;
Housename = housename;
}
public String getStreetname() {
return streetname;
}
public void setStreetname(String streetname) {
this.streetname = streetname;
}
public String getHousename() {
return Housename;
}
public void setHousename(String housename) {
Housename = housename;
}
public String getCityname() {
return cityname;
}
public void setCityname(String cityname) {
this.cityname = cityname;
}
}
---------------------------------------------------------------------------------------------------------
**controller class**
package com.example.demo;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class Croller {
#Autowired
TestRepo repo;
#PostMapping("/add")
public String save(#RequestBody User mode) {
repo.save(mode);
return "details saved";
}
#GetMapping("/get")
public List<User> retrive(){
return repo.findAll();
}
#GetMapping("/search")
public List<User> searchname(#RequestParam("name")String name){
return repo.name(name);
}
#GetMapping("/byid/{id}")
public Optional <User> getone (#PathVariable int id){
return repo.findById(id);
}
#PutMapping("/update")
public String updateid(#RequestBody User mode ) {
repo.save(mode);
return " user updated sucessfully";
}
#DeleteMapping("/remove/{id}")
public String delete(#PathVariable int id) {
repo.deleteById(id);
return "deleted with the given id:"+ id;
}
}
---------------------------------------------------------------------------------------------------------
Repository
package com.example.demo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TestRepo extends JpaRepository <User, Integer> {
List <User> name(String name);
}
**Application.java**
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Demoapi2Application {
public static void main(String[] args) {
SpringApplication.run(Demoapi2Application.class, args);
}
}
Your request has to match the #RequestBody object for spring to map the keys appropriately
Try this request -
{
"id":19,
"name":"Alex",
"address":{
"cityname":"california",
"streetname":"ring road",
"Housename":"Housename"
}
}
Please make sure you give input as per your Model.
My application is returning "[{},{}]" when I request asList. But when I request String it displays ok on browser.
Images: 1.IDE EndPoint 2.Browser Return
Endpoint
package br.com.devdojo.app.endpoint;
import br.com.devdojo.app.model.Student;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import static java.util.Arrays.asList;
#RestController
#RequestMapping("student")
public class StudentEndPoint {
#RequestMapping(method = RequestMethod.GET, path = ("/list"))
public List<Student> listAll(){
return asList(new Student("Aluno1"), new Student("Aluno2"));
}
}
Your Student class must be like below:
public class Student {
private String name;
public Student() {
}
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I am facing an issue with the code shown below. The below code is generating the json as follows :
[{"id":123,"subjects":"English"},{"id":456,"subjects":"Maths"}]
We can see that the name tag is missing in generated JSON. I don't understand when I am returning Student List, the resulting json should contain the name tag since there is a property in the Student class of type "Name". Please help !
PS: I have taken the code in debug & I saw that "students arraylist" 0 index & index does contain the name prpoperty along with id & subject. But the JSON doesn't contain this property.
Restcontroller:
package com.example.demo;
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
#SpringBootApplication
#RestController
public class Demo1Application {
#Autowired
Student student;
List<Student> students = new ArrayList<>();
#RequestMapping(value="/getStudents", method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
public List<Student> getstudent () {
students = student.setStudent();
return students;
}
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
System.out.println("Hello");
}
}
Student Bean Class:
package com.example.demo;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
#Component
public class Student {
int id;
String Subject;
#Autowired
#Qualifier("name")
Name name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSubjects() {
return Subject;
}
public void setSubject(String subject) {
Subject = subject;
}
public void setName(String Fname, String Mname, String Lname) {
Name nm = new Name();
name = nm.setfullname(Fname,Mname,Lname) ;
}
public Student(int id, String Subject) {
this.id = id;
this.Subject = Subject;
}
public Student() {
System.out.println("Student Object created");
}
public List<Student> setStudent() {
List<Student> Students = new ArrayList<>();
Student s = new Student ();
Student s1 = new Student ();
s.setId(123);
s.setSubject("English");
s.setName("Hemant", "123", "Mamod");
s1.setId(456);
s1.setSubject("Maths");
s1.setName("Akshay", "123", "pandey");
Students.add(s);
Students.add(s1);
return Students;
}
}
Name Bean Class:
package com.example.demo;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
#Component
#Qualifier("name")
public class Name {
String Firstname;
String Middlename;
String Lastname;
public Name() {
System.out.println("Name Object created");
}
public String getFirstname() {
return Firstname;
}
public void setFirstname(String firstname) {
Firstname = firstname;
}
public String getMiddlename() {
return Middlename;
}
public void setMiddlename(String middlename) {
Middlename = middlename;
}
public String getLastname() {
return Lastname;
}
public void setLastname(String lastname) {
Lastname = lastname;
}
public Name setfullname(String Fname, String Mname, String Lname) {
Firstname = Fname;
Middlename = Mname;
Lastname = Lname;
return this;
}
}
The problem is that you have not getter of the Name in the Student class.
Please add the getter as follow:
#Component
public class Student {
int id;
String Subject;
Name name;
/******/
public Name getName() {
return name;
}
}
Speaking of NullPinterException with a name property - it means that it has not been autowired for some reasons, so in your case you can remove an #Autowired and #Qualifier annotations or figure out what is a problem with autowiring
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!
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);
}