ContextRefreshedEvent is not being catched - spring-boot

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);
}
}

Related

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.

Spring boot (data jpa ) i am not able to save eumn value in database

package com.kk.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#ComponentScan(basePackages="com.kk")
#EnableJpaRepositories(basePackages="com.kk.respositry")
#EntityScan(basePackages="com.kk.entity")
#SpringBootApplication
public class SpringBootEnumExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootEnumExampleApplication.class, args);
}
}
package com.kk.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 com.kk.entity.Account;
import com.kk.service.AccountService;
#Controller
public class AccountController {
#Autowired
private AccountService accountService;
#RequestMapping(value="create",method=RequestMethod.POST)
private #ResponseBody String createAccout(#RequestBody Account account) {
Long l=accountService.save(account);
return "{\"accountId\":l}";
}
}
package com.kk.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import com.kk.enums.AccountRole;
#Entity
#Table(name = "account_tab")
public class Account {
#Id
#GeneratedValue
private Long id;
private String accountHolderName;
private String mobile;
private Integer age;
#Enumerated(EnumType.STRING)
#Column(name = "account_role", length = 40)
private AccountRole accountRole;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAccountHolderName() {
return accountHolderName;
}
public void setAccountHolderName(String accountHolderName) {
this.accountHolderName = accountHolderName;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public AccountRole getAccountRole() {
return accountRole;
}
public void setAccountRole(AccountRole accountRole) {
this.accountRole = accountRole;
}
}
package com.kk.enums;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.kk.enums.utils.AccountRoleDeserializer;
#JsonDeserialize(using = AccountRoleDeserializer.class)
public enum AccountRole {
EMPLOYEE_CUSTOMER("Employee customer"),
JOINTER_ACSCOUNT("Jointer customer"),
PRIMARY_ACCOUNT("Primary customer"),
TENANT_ACCOUNT("Tenant customer");
private final String text;
AccountRole(final String text) {
this.text = text;
}
#Override
public String toString() {
return text;
}
public String getText() {
return this.text;
}
public static AccountRole fromText(String text) {
for (AccountRole r : AccountRole.values()) {
if (r.getText().equals(text)) {
return r;
}
}
throw new RuntimeException("Your AccountRole not valied: "+text );
}
}
package com.kk.enums.utils;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.kk.enums.AccountRole;
public class AccountRoleDeserializer extends JsonDeserializer<AccountRole> {
#Override
public AccountRole deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
if (node == null) {
return null;
}
String text = node.textValue(); // gives "A" from the request
if (text == null) {
return null;
}
return AccountRole.fromText(text);
}
}
package com.kk.respositry;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.kk.entity.Account;
#Repository
public interface AccountRespositry extends JpaRepository<Account, Long> {
}
package com.kk.service;
import com.kk.entity.Account;
public interface AccountService {
Long save(Account account);
}
package com.kk.service;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.kk.entity.Account;
import com.kk.respositry.AccountRespositry;
#Service
#Transactional
public class AccountServiceImpl implements AccountService{
#Autowired
private AccountRespositry accountRespositry;
#Override
public Long save(Account account) {
account=accountRespositry.save(account);
return account.getId();
}
}
server.port=8088
server.servlet.context-path=/SpringBootEnum/
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/Account?useSSL=false
spring.datasource.username = root
spring.datasource.password = root
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
#Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
I am using spring boot (data jpa ) but am getting the wrong value in the database.
The #Enumerated is behaving as expected. It's going to return the name of the enum and that's what gets persisted. Remember JPA uses the name() of the enum and not the toString() even if you have overridden the toString(). I would recommend using an AttributeConverter (JPA 2.1+) to control the persistence of your enum. In your case, create the converter to use the getText() method you already have defined in your Enum.
#Converter(autoApply = true)
public class AccountRoleConverter implements AttributeConverter<AccountRole, String> {
#Override
public String convertToDatabaseColumn(AccountRole role) {
return role.getText();
}
#Override
public AccountRole convertToEntityAttribute(String dbData) {
return AccountRole.fromText(dbData);
}
}
Note: #Converter(autoApply = true), tells JPA provider to use it to map all AccountRole enums.
Now you just need to make sure you remove the #Enumerated from your Account Entity:
#Enumerated(EnumType.STRING)
#Column(name = "account_role", length = 40)
private AccountRole accountRole;
becomes
#Column(name = "account_role", length = 40)
private AccountRole accountRole;
Ok you may ask how you use the converter. Well that is the nice part, you don't have to do anything. The persistence provider will use it for all read and write operations. I hope this helps.

Spring-boot batch file read and send data to Kafka

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();
}
}

Can't integrate Spring Boot Data with Neo4j

I just started with Spring Boot Data Neo4j and trying to finish the movie tutorial. I got this ERROR but not really sure how to debug. Error summary : (1) Error creating bean (2)Could not autowire field. Any help, thank you.
My files structure as follows :
SpringBootApplication.java
package com.test.springdataneothree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.test.services.MovieService;
#EnableAutoConfiguration
#SpringBootApplication
public class SpringdataneothreeApplication implements CommandLineRunner {
#Autowired
MovieService movieService;
public static void main(String[] args) {
SpringApplication.run(SpringdataneothreeApplication.class, args);
}
#Override
public void run(String... arg0) throws Exception {
System.out.println("Main Spring Boot Class");
movieService.countMovie();
}
}
Movie.java
package com.test.movie;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
#NodeEntity(label ="Movie")
public class Movie {
#GraphId
private Long id;
String title;
int released;
String tagline;
public Movie() { }
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getReleased() {
return released;
}
public void setReleased(int released) {
this.released = released;
}
public String getTagline() {
return tagline;
}
public void setTagline(String tagline) {
this.tagline = tagline;
}
}
MovieService.java
package com.test.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.test.repositories.MovieRepository;
#Service("MovieService")
public class MovieService {
#Autowired
MovieRepository movieRepository;
public void countMovie() {
movieRepository.count();
}
}
MovieRepository.java
package com.test.repositories;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.test.movie.Movie;
#Repository
public interface MovieRepository extends GraphRepository<Movie> {
Movie findById(long id);
Movie findByTitle(#Param("title") String title);
#Query("MATCH (m:Movie) WHERE m.title =~ ('(?i).*'+{title}+'.*') RETURN m")
Collection<Movie> findByTitleContaining(#Param("title") String title);
#Query("MATCH (m:Movie)<-[:ACTED_IN]-(a:Person) RETURN m.title as movie, collect(a.name) as cast LIMIT {limit}")
List<Map<String,Object>> graph(#Param("limit") int limit);
}
MyNeo4jConfiguration.java
package com.test.configuration;
import org.neo4j.ogm.session.SessionFactory;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.config.Neo4jConfiguration;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#EnableTransactionManagement
#EnableScheduling
#ComponentScan(basePackages = {"com.test"})
#Configuration
#EnableNeo4jRepositories(basePackages = "com.test.repositories")
public class MyNeo4jConfiguration extends Neo4jConfiguration {
#Override
public SessionFactory getSessionFactory() {
return new SessionFactory("com.test.movie");
}
}
You have a problem with auto wiring: the annotation on the MovieService is wrong, it should be:
#Service("movieService")
or just
#Service
You are trying to inject a bean with the capitalised name, and the context can't find it (the injection is done by name). Another solution is to use the #Qualifier annotation on the auto wired field, like
#Autowired
#Qualifier("MovieService")
MovieService movieService;

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