How to define a Spring bean using annotation instead of XML? - spring

I have defined in a xml config file:
<bean id="bootstrap" class="com.package.Bootstrap"></bean>
this works fine.
The bootsrap class :
public class Bootstrap {
#PostConstruct
public void onServerStart() {
System.out.println("PRINTSSSSSSSSSSSSSSSSSSS");
}
}
The method gets fired.
But how can I get rid of the xml part, and annotate bootstrap to be a bean instead?
I have
<mvc:annotation-driven />
<context:annotation-config />
and
<context:component-scan base-package="com.package" />
But I was wondering what the annotation used should be that replaces:
<bean id="bootstrap" class="com.package.Bootstrap"></bean>
I could not find anything about this online and in the spring docs :(

There's documentation regarding this; you'll want a stereotype annotation like #Component.
Stereotype bean annotations

this is a simple example that I have just made:
Main.java
package the.test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
public class Main {
public static void main(String[] args) {
AbstractApplicationContext aac = new AnnotationConfigApplicationContext(Person.class, Phones.class);
Person person = aac.getBean(Person.class);
System.out.println(person.getPhones().getPhoneOne());
System.out.println(person.getPhones().getPhoneTwo());
System.out.println(person.getSurname());
System.out.println(person.getName());
System.out.println(person.getAge());
aac.close();
}
}
Person.java
package the.test;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
#Configuration
//you may use #ComponentScan("the.test") here and omit declaring
//"Phone.class" in the main method
public class Person {
private int age;
private String name;
private String surname;
private Phones phones;
public int getAge() {
return age;
}
#Value("33")
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
#Value("John")
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
#Value("Due")
public void setSurname(String surname) {
this.surname = surname;
}
public Phones getPhones() {
return phones;
}
#Resource
public void setPhones(Phones phones) {
this.phones = phones;
}
}
Phones.java
package the.test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
#Configuration
public class Phones {
private String PhoneOne;
private String PhoneTwo;
public String getPhoneOne() {
return PhoneOne;
}
#Value("987654321")
public void setPhoneOne(String phoneOne) {
PhoneOne = phoneOne;
}
public String getPhoneTwo() {
return PhoneTwo;
}
#Value("123456")
public void setPhoneTwo(String phoneTwo) {
PhoneTwo = phoneTwo;
}
}
this is completely based on Spring Annotation and is made on spring framework 4.2.5
hope it helps.

Related

SpringBoot #Autowired NullPointerException when calling method from service class

I'm learning Spring Boot. I'm trying to fetch a value from an ArrayList from the service class by calling its method. But I got a NullPointerException. I add both #Autowired and #Service annotations, it doesn't work. I also looked up some topics about Loc container but it doesn't seem to help.
Here is my MainController:
package com.example.ecommerce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.ArrayList;
#Controller
public class MainController {
#Autowired
private ProductService productService;
//I'm getting a NullPointerException here when I call the method "getAllProduct"
ArrayList<Product> products = productService.getAllProduct();
#GetMapping("/")
public String home(){
return "home";
}
#GetMapping("/products")
public String product(Model model){
model.addAttribute("products",products);
return "product";
}
}
Here is my service class:
package com.example.ecommerce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
#Service
public class ProductService {
ArrayList<Product> products = new ArrayList<>(Arrays.asList(
new Product("iPhone 4","Apple",1000),
new Product("iPhone 5","Banana",2000),
new Product("iPhone 6","Orange",3000)
));
public ArrayList<Product> getAllProduct(){
return products;
}
}
Here is the model class Product:
package com.example.ecommerce;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String brand;
private double price;
public Product() {
}
public Product(String name, String brand, double price) {
this.name = name;
this.brand = brand;
this.price = price;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
#Override
public String toString() {
return "Product{" +
"id=" + id +
", name='" + name + '\'' +
", brand='" + brand + '\'' +
", price=" + price +
'}';
}
}
Edit: was able to fix it by adding a constructor in the MainController
private final ProductService productService;
private final ArrayList<Product> products;
#Autowired
public MainController(ProductService productService) {
this.productService = productService;
this.products = productService.getAllProduct();
}
The service method is called before the dependency is injected. That's why you are getting NPE. Try using constructor dependency injection
#Controller
public class MainController {
public MainController(ProductService productService) {
this.productService = productService;
}
private ProductService productService;
//I'm getting a NullPointerException here when I call the method "getAllProduct"
ArrayList<Product> products = productService.getAllProduct();
#GetMapping("/")
public String home() {
return "home";
}
#GetMapping("/products")
public String product(Model model) {
model.addAttribute("products", products);
return "product";
}
}
Or call the service method inside the controller method
#Controller
public class MainController {
#Autowired
private ProductService productService;
#GetMapping("/")
public String home() {
return "home";
}
#GetMapping("/products")
public String product(Model model) {
model.addAttribute("products", productService.getAllProduct());
return "product";
}
}
your products are never getting initialized in product service class, I would suggest you to try this in ProductService class
#Service
public class ProductService {
ArrayList<Product> products;
ProductService()
{
this.products= new ArrayList<>(Arrays.asList(
new Product("iPhone 4","Apple",1000),
new Product("iPhone 5","Banana",2000),
new Product("iPhone 6","Orange",3000)
));
}
public ArrayList<Product> getAllProduct(){
return products;
}
}
Nice, always use constructor injection instead of field injection. Im just relaying the Spring recommendation. Which is the most adopted conversion lately :)

How use java config to create a inner bean?

Spring Boot version:2.1.3.RELEASE,Spring Framework version:5.1.5.RELEASE.
Simple xml config like this:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="CustomerBean" class="io.github.ctlove0523.Customer">
<property name="person">
<bean class="io.github.ctlove0523.Person">
<property name="name" value="stackoverflow" />
<property name="address" value="address1" />
<property name="age" value="15" />
</bean>
</property>
</bean>
</beans>
how the java config would like?
Person.java
import org.springframework.beans.factory.annotation.Value;
public class Person {
#Override
public String toString() {
return "Person [name=" + name + ", address=" + address + ", age=" + age + "]";
}
private String name;
private String address;
private Integer age;
public String getName() {
return name;
}
#Value("stackoverflow")
public void setName(String name) {
this.name = name;
}
#Value("address1")
public void setAddress(String address) {
this.address = address;
}
#Value("15")
public void setAge(Integer age) {
this.age = age;
}
}
CustomerBean.java
import org.springframework.beans.factory.annotation.Autowired;
public class CustomerBean {
Person person;
public Person getPerson() {
return person;
}
#Autowired
public void setPerson(Person person) {
this.person = person;
}
}
App.java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App
{
public static void main( String[] args )
{
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
context.registerShutdownHook();
CustomerBean customerBean = context.getBean(CustomerBean.class);
System.out.println(customerBean.getPerson());
}
}
AppConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
public class AppConfig {
#Bean
public CustomerBean customerBean() {
return new CustomerBean();
}
#Bean
public Person person() {
return new Person();
}
}
Output :
Person [name=stackoverflow, address=address1, age=15]
Edit: Is this what you are looking for ??
Create beans from inner class using spring
Check the Spring documentation on Java configuration : https://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch02s02.html
Depending on the code of your Person class, it would look something like this :
import io.github.ctlove0523.Customer;
#Configuration
public class AppConfig {
#Bean
public Customer customerBean() {
Customer myBean = new Customer();
// constructor or setter methods for Person
return myBean;
}
}

Getting null value from #configuration

I'm creating pojo class and store the application.properties variable but I'm getting null values
NOTE: need to access env from my Abstract class
POJO class
package mynt.xyz.c4.pushnotif.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
#Configuration("notificationEnvironment")
#ConfigurationProperties(prefix = "app.notif")
public class NotificationEnvironment {
private String key;
private String url;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Initializing class with #autowired
public abstract class NotificationBase {
#Autowired
NotificationEnvironment notificationEnvironment;
public void getEnv(){
system.out.println(notificationEnvironment.getKey()); // null value
}
}
concrete class that extend to my NotificationBaseClass
#Component
#Qualifier("androidNotification")
public class AndroidNotification extends NotificationBase implements Notification {
public AndroidNotification(String message, String title, String datalink, List<String> instanceIds) {
super(message, title, datalink, instanceIds);
}
AndroidNotification(){
super();
}
#Override
public void send() {
this.getEnv();
}
}
application.properties
app.notif.key=jkashdkjashd
app.notif.url=https/some.url
You can auto wire #Configuration class from #Configuration class
#Configuration class may reference the instance of any other #Configuration class using #Autowired. This works because the #Configuration classes themselves are instantiated and managed as individual Spring beans.
Make your class #Component and add prefix value in #ConfigurationProperties, like this. This works for me, hope this works for you as well.
#Component
#ConfigurationProperties(prefix = "app.notif")
public class NotificationEnvironment {
private String key;
private String url;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
You can use this properties like this:
#Component
public class NotificationBase {
private static NotificationEnvironment notificationEnvironment;
#Autowired
public NotificationBase(NotificationEnvironment notificationEnvironment){
this.notificationEnvironment = notificationEnvironment;
}
public static void getEnv(){
System.out.println(notificationEnvironment.getKey()); // null value
}
}
Here is the one of the concrete class definition as OP author mentioned.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class ConcreteNotification extends NotificationBase {
#Autowired
public ConcreteNotification(NotificationEnvironment notificationEnvironment) {
super(notificationEnvironment);
}
}
updated NotificationBase as below
public abstract class NotificationBase {
NotificationEnvironment notificationEnvironment;
public NotificationBase(NotificationEnvironment notificationEnvironment) {
this.notificationEnvironment = notificationEnvironment;
}
public void getEnv(){
System.out.println(notificationEnvironment.getKey());
}
}
The controller class I am using to get configuration values
#RestController
public class ArticleCommentController {
#Autowired
ConcreteNotification concreteNotification;
#RequestMapping(value = "/health_check", method = RequestMethod.GET)
public void getDemo() {
concreteNotification.getEnv();
}
}
output:
jkashdkjashd

Spring MVC to REST

I have a Spring MVC aplication. I want to convert it to a RESTful
webservice, which returns a JSON response. Can somebody help me with this??
Basically, I want to convert my controller to a REST controller.
My Code :
///////////////////////////PersonController//////////////////////////////
package com.journaldev.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.journaldev.spring.model.Person;
import com.journaldev.spring.service.PersonService;
#Controller
public class PersonController {
private PersonService personService;
#Autowired(required=true)
#Qualifier(value="personService")
public void setPersonService(PersonService ps){
this.personService = ps;
}
#RequestMapping(value = "/persons", method = RequestMethod.GET)
public String listPersons(Model model) {
model.addAttribute("person", new Person());
model.addAttribute("listPersons", this.personService.listPersons());
return "person";
}
//For add and update person both
#RequestMapping(value= "/person/add", method = RequestMethod.POST)
public String addPerson(#ModelAttribute("person") Person p){
if(p.getId() == 0){
//new person, add it
this.personService.addPerson(p);
}else{
//existing person, call update
this.personService.updatePerson(p);
}
return "redirect:/persons";
}
#RequestMapping("/remove/{id}")
public String removePerson(#PathVariable("id") int id){
this.personService.removePerson(id);
return "redirect:/persons";
}
#RequestMapping("/edit/{id}")
public String editPerson(#PathVariable("id") int id, Model model){
model.addAttribute("person", this.personService.getPersonById(id));
model.addAttribute("listPersons", this.personService.listPersons());
return "person";
}
}
/////////////////////////////////PersonDAO/////////////////////////////
package com.journaldev.spring.dao;
import java.util.List;
import com.journaldev.spring.model.Person;
public interface PersonDAO {
public void addPerson(Person p);
public void updatePerson(Person p);
public List<Person> listPersons();
public Person getPersonById(int id);
public void removePerson(int id);
}
///////////////////////////////PersonDAOImpl/////////////////////////
package com.journaldev.spring.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import com.journaldev.spring.model.Person;
#Repository
public class PersonDAOImpl implements PersonDAO {
private static final Logger logger = LoggerFactory.getLogger(PersonDAOImpl.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
#Override
public void addPerson(Person p) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(p);
logger.info("Person saved successfully, Person Details="+p);
}
#Override
public void updatePerson(Person p) {
Session session = this.sessionFactory.getCurrentSession();
session.update(p);
logger.info("Person updated successfully, Person Details="+p);
}
#SuppressWarnings("unchecked")
#Override
public List<Person> listPersons() {
Session session = this.sessionFactory.getCurrentSession();
List<Person> personsList = session.createQuery("from Person").list();
for(Person p : personsList){
logger.info("Person List::"+p);
}
return personsList;
}
#Override
public Person getPersonById(int id) {
Session session = this.sessionFactory.getCurrentSession();
Person p = (Person) session.load(Person.class, new Integer(id));
logger.info("Person loaded successfully, Person details="+p);
return p;
}
#Override
public void removePerson(int id) {
Session session = this.sessionFactory.getCurrentSession();
Person p = (Person) session.load(Person.class, new Integer(id));
if(null != p){
session.delete(p);
}
logger.info("Person deleted successfully, person details="+p);
}
}
//////////////////////////////////Person(Model)///////////////////////
package com.journaldev.spring.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Entity bean with JPA annotations
* Hibernate provides JPA implementation
* #author pankaj
*
*/
#Entity
#Table(name="PERSON")
public class Person {
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
private String country;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#Override
public String toString(){
return "id="+id+", name="+name+", country="+country;
}
}
///////////////////////////////////PersonService///////////////////
package com.journaldev.spring.service;
import java.util.List;
import com.journaldev.spring.model.Person;
public interface PersonService {
public void addPerson(Person p);
public void updatePerson(Person p);
public List<Person> listPersons();
public Person getPersonById(int id);
public void removePerson(int id);
}
//////////////////////////////ServiceImpl////////////////////////////
package com.journaldev.spring.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.journaldev.spring.dao.PersonDAO;
import com.journaldev.spring.model.Person;
#Service
public class PersonServiceImpl implements PersonService {
private PersonDAO personDAO;
public void setPersonDAO(PersonDAO personDAO) {
this.personDAO = personDAO;
}
#Override
#Transactional
public void addPerson(Person p) {
this.personDAO.addPerson(p);
}
#Override
#Transactional
public void updatePerson(Person p) {
this.personDAO.updatePerson(p);
}
#Override
#Transactional
public List<Person> listPersons() {
return this.personDAO.listPersons();
}
#Override
#Transactional
public Person getPersonById(int id) {
return this.personDAO.getPersonById(id);
}
#Override
#Transactional
public void removePerson(int id) {
this.personDAO.removePerson(id);
}
}
First you have to add Jackson Databind dependency in your pom file then you can define your rest controller for exemple :
#RestController
public class PersonRestService {
#Autowired
private PersonService personService ;
#RequestMapping(value="/persons",method=RequestMethod.POST)
public Person addPerson(#RequestBody Person Person) {
return personService.addPerson(Person);
}
#RequestMapping(value="/persons",method=RequestMethod.Delete)
public void deletePerson(int code) {
personService.deletePerson(code);
}
#RequestMapping(value="/persons",method=RequestMethod.GET)
public Person getPerson(#RequestParam int code) {
return personService.getPersonById(code);
}
#RequestMapping(value="/allPersons",method=RequestMethod.GET)
public List<Person> getAllPerson() {
return personService.getAllPerson();
}
}
Its easy, what you need to do is add a response in JSON for all request which need it.
The annotation is #ResponseBody and you can return any object, jackson will serialize it to json format for you.
For example in your code:
#RequestMapping("/remove/{id}")
#ResponseBody
public boolean removePerson(#PathVariable("id") int id){
this.personService.removePerson(id);
//true if everything was OK, false if some exception
return true;
}
...
#RequestMapping(value = "/persons", method = RequestMethod.GET)
#ResponseBody
public List<Person> listPersons(Model model) {
return this.personService.listPersons();
}
You only need to modify your controller, to make it RESTFul
Also you will have to add logic to your JS code to handle the new responses values.
Simply use the annotation #RestController.
You can also refer to previously asked question on this link
Difference between spring #Controller and #RestController annotation

Spring Hibernate get tuple by id

I am trying to create a simple "teacher" database. I was able to create a method for adding a new teacher to database, now I need to be able to get one and delete one by "Id". I would like some help, of how should I implement it. I have added following code files: AppConfig, Teacher (entity class), ITeacherDao (interface), TeacherDao(implementation of interface) and class with main method TimeStarApplication.
AppConfig
package com.superum.timestar;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.superum.timestar.dao.ITeacherDao;
import com.superum.timestar.dao.TeacherDao;
import com.superum.timestar.entity.Teacher;
#Configuration
#EnableTransactionManagement
public class AppConfig {
#Bean
public ITeacherDao teacherDao() {
return new TeacherDao();
}
#Bean
public HibernateTemplate hibernateTemplate() {
return new HibernateTemplate(sessionFactory());
}
#Bean
public SessionFactory sessionFactory() {
return new LocalSessionFactoryBuilder(getDataSource())
.addAnnotatedClasses(Teacher.class)
.buildSessionFactory();
}
#Bean
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/time_star");
dataSource.setUsername("root");
dataSource.setPassword("password");
return dataSource;
}
#Bean
public HibernateTransactionManager hibTransMan(){
return new HibernateTransactionManager(sessionFactory());
}
}
Teacher
package com.superum.timestar.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="teachers")
public class Teacher {
#Id#GeneratedValue
#Column(name="t_id")
private int Id;
#Column(name="t_name")
private String name;
#Column(name="t_lastname")
private String lastname;
#Column(name="t_phone")
private String phone;
#Column(name="t_age")
private int age;
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
ITeacherDAO
package com.superum.timestar.dao;
public interface ITeacherDao {
public void addTeacher(String name, String lastname, String phone, int age);
// public void getTeacher(int id);
`` // public void deleteTeacher();
}
TeacherDao
package com.superum.timestar.dao;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import com.superum.timestar.entity.Teacher;
#Transactional
public class TeacherDao implements ITeacherDao{
#Autowired
private HibernateTemplate hibernateTemplate;
public void addTeacher(String name, String lastname, String phone, int age){
Teacher teacher = new Teacher();
teacher.setName(name);
teacher.setLastname(lastname);
teacher.setPhone(phone);
teacher.setAge(age);
hibernateTemplate.save(teacher);
}
// I need to create get by Id
// public void getTeacher(int Id){
//
// }
I hope the question is not entirely horrible.
}
ITeacherDAO
package com.superum.timestar.dao;
public interface ITeacherDao {
public void addTeacher(String name, String lastname, String phone, int age);
public Teacher getTeacher(int id); //Method to get the teacher by id
public void deleteTeacher(int id); //Method to delete the teacher by id
}
TeacherDao
package com.superum.timestar.dao;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import com.superum.timestar.entity.Teacher;
#Transactional
public class TeacherDao implements ITeacherDao{
#Autowired
private HibernateTemplate hibernateTemplate;
public void addTeacher(String name, String lastname, String phone, int age){
Teacher teacher = new Teacher();
teacher.setName(name);
teacher.setLastname(lastname);
teacher.setPhone(phone);
teacher.setAge(age);
hibernateTemplate.save(teacher);
}
public Teacher getTeacher(int id){
Teacher teacher = (Teacher)hibernateTemplate.get(Teacher.class, id);
return teacher;
}
public void deleteTeacher(int id){
Teacher teacher = (Teacher)hibernateTemplate.get(Teacher.class, id);
hibernateTemplate.delete(teacher);
}

Resources