Spring-boot batch file read and send data to Kafka - spring-boot

I am having trouble sending data from CSV file to Kafka. Here is my code for writer.java for batch processing
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder.In;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import com.codenotfound.kafka.repository.*;
import java.util.*;
import com.codenotfound.kafka.Car;
import com.codenotfound.kafka.producer.Sender;
public class Writer implements ItemWriter<Car>{
private final Repository repo;
public Writer(Repository repo) {
this.repo = repo ;
}
#Override
public void write(List<? extends Car> car) throws Exception {
repo.save(car);
}
}
So instead of repo.save(car), I want this car class details to be sent to Kafka.
Here is my Car class and Repository interface respectively
#Entity
#Table(name = "Car")
public class Car {
private String make;
private String manufacturer;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
public Car() {
//super();
}
public Car(String make, String manufacturer) {
super();
this.make = make;
this.manufacturer = manufacturer;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Override
public String toString() {
return "Car [make=" + make + ", manufacturer=" + manufacturer + ", id=" + id + "]";
}
}
and Repository class
public interface Repository extends CrudRepository<Car, Long>,CustomRepository {
}
My Sender file for Kafka is:
package com.codenotfound.kafka.producer;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import com.codenotfound.kafka.Car;
public class Sender {
private static final Logger LOGGER = LoggerFactory.getLogger(Sender.class);
#Value("${topic.json}")
private String jsonTopic;
#Autowired
private KafkaTemplate<String, Car> kafkaTemplate;
public void send(Car car) {
LOGGER.info("sending car='{}'", car.toString());
kafkaTemplate.send(jsonTopic, car);
}
}
Please suggest to me a method to send data from a CSV file to my Kafka.

it seems you already have all the pieces of the puzzle laid out for you. What you need to do is change your ItemWriter using your Sender class, so you'd have something like this:
#Component
public class Writer implements ItemWriter<Car> {
#Value("${topic.json}")
private String jsonTopic;
#Autowired
private KafkaTemplate<String, Car> kafkaTemplate;
#Override
public void write(List<? extends Car> cars) throws Exception {
cars.forEach(car -> kafkaTemplate.send(jsonTopic, car));
}
}
and in your job configuration, you need to autowire it like this (the code below is simplified, just showing how to declare the writer in the step):
#Configuration
#EnableBatchProcessing
public class BatchConfiguration {
#Autowired
public StepBuilderFactory stepBuilderFactory;
#Autowired
private Writer carWriter;
#Bean
public Step myStep() {
this.stepBuilderFactory.get("myStep")
.<Car,Car> chunk(10)
.reader(reader())
.writer(carWriter) // don't use new here
.build();
}
}

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 :)

Spring boot application failed to start with exception org.springframework.beans.factory.NoSuchBeanDefinitionException:

I am using spring boot v2.5.2. Below is my folder structure and code. This is simple test project.
My folder structure:
RESTController Class:
package com.user.UserManagementSystem.controller;
import com.user.UserManagementSystem.model.User;
import com.user.UserManagementSystem.service.UserServiceImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/api/v1/")
public class UserController {
#Autowired
private UserServiceImpl userRepository;
#GetMapping("/getAllUsers")
public List<User> getAllUsers() {
return userRepository.getUsers();
}
#GetMapping("/")
public String home() {
return "Hello";
}
}
User.java
package com.user.UserManagementSystem.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
#Table(name= "Users")
public class User {
public User() {
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name ="userName")
private String userName;
#Column(name ="name")
private String name;
#Column(name ="language")
private String language;
#Column(name ="mobileNumber")
private int mobileNumber;
public User(String userName, String name, String language, int mobileNumber) {
this.userName = userName;
this.name = name;
this.language = language;
this.mobileNumber = mobileNumber;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public int getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(int mobileNumber) {
this.mobileNumber = mobileNumber;
}
}
UserRepository.java
package com.user.UserManagementSystem.repository;
import com.user.UserManagementSystem.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends JpaRepository<User, Long>{
}
UserService.java
package com.user.UserManagementSystem.service;
import com.user.UserManagementSystem.model.User;
import java.util.List;
public interface UserService {
List<User> getUsers();
User getUserById(Long id);
User addUser(User user);
void deleteUser(Long id);
}
UserServiceImpl.java
package com.user.UserManagementSystem.service;
import com.user.UserManagementSystem.repository.UserRepository;
import com.user.UserManagementSystem.model.User;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class UserServiceImpl implements UserService{
#Autowired
UserRepository userRepository;
#Override
public List<User> getUsers() {
return userRepository.findAll();
}
#Override
public User getUserById(Long id) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public User addUser(User user) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void deleteUser(Long id) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
UserManangmentSystemApplication.java
package com.user.UserManangmentSystem;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication(scanBasePackages = {"com.user.UserManangmentSystem", "com.user.UserManagementSystem.controller", "com.user.UserManagementSystem.repository", "com.user.UserManagementSystem.service"})
//#SpringBootApplication
public class UserManangmentSystemApplication {
public static void main(String[] args) {
SpringApplication.run(UserManangmentSystemApplication.class, args);
}
}
application.properties:
spring.datasource.url=jdbc:mariadb://localhost:3306/ums
spring.datasource.username=ums
spring.datasource.password=ums
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDB53Dialect
server.port=8888
debug=true
When it build the project i am getting :
Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.user.UserManagementSystem.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1790) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1346) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:657) ~[spring-beans-5.3.8.jar:5.3.8]
Thanks in Advance.
Typo in your base package name which makes packages different.
Change
com.user.UserManangmentSystem
To
com.user.UserManangementSystem
Correct management spelling.
You have correct package structure it will collect all bean within base package and sub package also. No need explicitly mention package scan. If you have any spell mistakes then that error will occur.

ContextRefreshedEvent is not being catched

I am setting up a spring boot application with postgres database
The postgres server is up and does not have much to do with the issue.
Following are my classes:
package com.example.demo.service.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ContextStartedEvent;
#SpringBootApplication
public class ServiceConfiguration {
public static void main(String[] args) {
SpringApplication.run(ServiceConfiguration.class, args);
}
}
package com.example.demo.service.config;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableAutoConfiguration
#EntityScan(basePackages = {"com.example.demo.persistence"})
#EnableJpaRepositories(basePackages = {"com.example.demo.repositories"})
#EnableTransactionManagement
public class RepositoryConfiguration {
}
package com.example.demo.repositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;
import com.example.demo.persistence.Product;
#Component
public interface ProductRepository extends CrudRepository<Product, Integer>{
}
package com.example.demo.persistence;
import javax.persistence.*;
import java.math.BigDecimal;
#Entity
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#SequenceGenerator(name="product_id_sequence", sequenceName="product_id_sequence", allocationSize=1)
#Column(name="ID")
private Integer id;
#Version
private Integer version;
private String productId;
private String description;
private String imageUrl;
private BigDecimal price;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
}
package com.example.demo.bootstrap;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import com.example.demo.persistence.Product;
import com.example.demo.repositories.ProductRepository;
import java.math.BigDecimal;
#Component
public class ProductLoader implements ApplicationListener<ContextRefreshedEvent> {
private ProductRepository productRepository;
private Logger log = Logger.getLogger(ProductLoader.class);
#Autowired
public void setProductRepository(ProductRepository productRepository) {
this.productRepository = productRepository;
}
#Override
public void onApplicationEvent(ContextRefreshedEvent event) {
System.err.println("Flow never comes here !!");
Product shirt = new Product();
shirt.setDescription("Spring Framework Guru Shirt");
shirt.setPrice(new BigDecimal("18.95"));
shirt.setImageUrl("https://springframework.guru/wp-content/uploads/2015/04/spring_framework_guru_shirt-rf412049699c14ba5b68bb1c09182bfa2_8nax2_512.jpg");
shirt.setProductId("235268845711068308");
productRepository.save(shirt);
log.info("Saved Shirt - id: " + shirt.getId());
Product mug = new Product();
mug.setDescription("Spring Framework Guru Mug");
mug.setImageUrl("https://springframework.guru/wp-content/uploads/2015/04/spring_framework_guru_coffee_mug-r11e7694903c348e1a667dfd2f1474d95_x7j54_8byvr_512.jpg");
mug.setProductId("168639393495335947");
productRepository.save(mug);
log.info("Saved Mug - id:" + mug.getId());
}
}
The ProductLoader class is a component and implements ApplicationListener, still the flow never comes in onApplicationEvent(ContextRefreshedEvent event) method.
Can anybody help?
Got the issue resolved.
Added following annotations to the ServiceConfiguration class
#SpringBootApplication(scanBasePackages = {"com.example.demo.bootstrap","com.example.demo.persistence"})
#EnableJpaRepositories(basePackageClasses = {ProductRepository.class})
#EntityScan(basePackageClasses=Product.class)
public class ServiceConfiguration {
public static void main(String[] args) {
SpringApplication.run(ServiceConfiguration.class, args);
}
}

Not supported for DML operations .Unable to update data in postgresql database using spring data

Hi I am using spring boot and Spring data i want to fetch data from database on the basis of id but m not able to retreive it.
M getting this error "exception":
"org.springframework.dao.InvalidDataAccessApiUsageException",
"message": "org.hibernate.hql.internal.QueryExecutionRequestException:
Not supported for DML operations [Update
com.ge.health.poc.model.SpringModel SET name='sneha' where id=?];
nested exception is java.lang.IllegalStateException:
org.hibernate.hql.internal.QueryExecutionRequestException: Not
supported for DML operations [Update
com.ge.health.poc.model.SpringModel SET name='sneha' where id=?]",
"path": "/updatedata"
}
Main Class
package com.ge.health.poc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringDataApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDataApplication.class, args);
}
}
Controller Class
package com.ge.health.poc.controller;
import java.io.IOException;
import java.text.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ge.health.poc.model.SpringModel;
import com.ge.health.poc.service.BookServiceImpl;
#RestController
public class SpringController {
#Autowired
BookServiceImpl bookserviceimpl;
#RequestMapping(value = "/insertdata", method = RequestMethod.POST)
#ResponseBody
public void helloService(#RequestBody String input, final RedirectAttributes redirectAttributes)
throws JsonParseException, JsonMappingException, IOException, ParseException {
System.out.println(input);
ObjectMapper mapper = new ObjectMapper();
SpringModel pojodata = mapper.readValue(input, SpringModel.class);
System.out.println(pojodata);
System.out.println(pojodata.getAuthor());
bookserviceimpl.save(pojodata);
}
#RequestMapping(value = "/getdata/{id}")
#ResponseBody
public void retreiveData(#PathVariable("id") int id)
throws JsonParseException, JsonMappingException, IOException, ParseException {
System.out.println("id is:" + id);
bookserviceimpl.retreive(id);
}
#RequestMapping(value = "/deletedata", method = RequestMethod.DELETE)
#ResponseBody
public void deleteData(#RequestBody String id)
throws JsonParseException, JsonMappingException, IOException, ParseException {
System.out.println("M in delete");
System.out.println(id);
ObjectMapper mapper = new ObjectMapper();
SpringModel pojodata = mapper.readValue(id, SpringModel.class);
int idd = (pojodata.getId());
System.out.println("value oof idd is:" + idd);
System.out.println("M into delete method");
bookserviceimpl.delete(idd);
}
#RequestMapping(value = "/updatedata", method = RequestMethod.PUT)
#ResponseBody
public void updateData(#RequestBody String id)
throws JsonParseException, JsonMappingException, IOException, ParseException {
System.out.println("M in update");
System.out.println(id);
ObjectMapper mapper = new ObjectMapper();
SpringModel pojodata = mapper.readValue(id, SpringModel.class);
int idd = (pojodata.getId());
System.out.println("value oof idd is:" + idd);
bookserviceimpl.update(idd);
}
}
Repository
package com.ge.health.poc.interfac;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.ge.health.poc.model.SpringModel;
#Repository
#Transactional
public interface BookRepository extends JpaRepository<SpringModel, Long> {
#Query("select author from SpringModel where id=?")
String findName(int id);
#Query("Update SpringModel SET name='sneha' where id=?")
String UpdateByID(int id);
#Query("delete from SpringModel where id=?")
String deleteById(int id);
}
BookServiceImpl.java
package com.ge.health.poc.service;
import javax.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ge.health.poc.interfac.BookRepository;
import com.ge.health.poc.model.SpringModel;
#Component
public class BookServiceImpl implements BookService {
#Autowired
EntityManager entitymanager;
#Autowired
BookRepository bookrepo;
#Override
public void save(SpringModel bookdata) {
bookrepo.save(bookdata);
}
public String retreive(int id) {
String s = bookrepo.findName(id);
System.out.println("Author name is:" + s);
return null;
}
public void delete(int id) {
System.out.println("M into service delete method");
bookrepo.deleteById(id);
}
public void update(int id) {
System.out.println("M in service update");
bookrepo.UpdateByID(id);
}
}
this is model class
package com.ge.health.poc.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "spring_model")
public class SpringModel {
#Id
private Long id;
#Column
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column
private String isbn;
#Override
public String toString() {
return "SpringModel [id=" + id + ", name=" + name + ", isbn=" + isbn + ", author=" + author + ", pages=" + pages
+ "]";
}
#Column
private String author;
#Column
private String pages;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPages() {
return pages;
}
public void setPages(String pages) {
this.pages = pages;
}
}
Try the annotation #Modifying(org.springframework.data.jpa.repository.Modifying) on the repository methods and #Transactional(org.springframework.transaction.annotation.Transactional) in service implementation which does DML operation. please refer this answer for more information.
By Default spring jpa will think query is select query.So, To make sure the query is updating the existed row for a particular entity
add #modifying Annotation on the method which is updating the existed row
This might works for you

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