Hibernate. Person is not mapped - spring

I just want to find all rows from the database (postgres:alpine) with Hibernate but got "not mapped" error.
Exception in thread "main" java.lang.IllegalArgumentException:
org.hibernate.hql.internal.ast.QuerySyntaxException: Person is not
mapped [from Person p]
I've a lot of read about this error. So people in createQuery write incorrect name. I have right one (classname). But still get this error. Any ideas please?
Entity:
import javax.persistence.*;
import javax.persistence.Entity;
import java.io.Serializable;
#Entity
#Table(name="users")
public class Person implements Serializable {
protected int id;
protected String name;
protected int age;
protected String email;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name = "age")
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Repository:
import ch.fdsgn.models.Person;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
#Transactional
#Repository("personDao")
public class PersonDAO {
private SessionFactory sessionFactory;
#Transactional(readOnly=true)
public List<Person> findAll() {
return this.getSessionFactory().getCurrentSession().createQuery("from Person p").list();
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
#Resource(name = "sessionFactory")
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
applicationContext.xml:
<util:properties id="hibernateProperties">
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL10Dialect</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">false</prop>
</util:properties>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
p:dataSource-ref="webDataSource"
p:packagesToScan="ch.fdsgn.dao"
p:hibernateProperties-ref="hibernateProperties"/>

You don't scan the correct package.
Your entity is in ch.fdsgn.models
You scan p:packagesToScan="ch.fdsgn.dao"

Related

when I post ,it shows error of 404 not found in spring boot even when I have declared #RequestMapping

I have made a userservice where I want to add new user, find user by id and also by other attributes. I have extended JPA repository since I learned that there is already functions. But I can't even save a new user.
This is my model
package bt.gov.dit.userservice.model;
import javax.persistence.*;
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column
private Long Id;
#Column
private String name;
#Column
private String email;
#Column
private String role;
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public User(Long id, String name, String email, String role) {
Id = id;
this.name = name;
this.email = email;
this.role = role;
}
public User() {
}
}
This is my repository
package bt.gov.dit.userservice.dao;
import bt.gov.dit.userservice.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends JpaRepository<User,Long> {
User findUserByRole(String role);
}
This is my service
package bt.gov.dit.userservice.service;
import bt.gov.dit.userservice.dao.UserRepository;
import bt.gov.dit.userservice.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class UserService {
#Autowired
private UserRepository userRepository;
public User save(User user){
return userRepository.save(user);
}
public User getByRole(String role){
return userRepository.findUserByRole(role);
}
}
And this is my Controller
package bt.gov.dit.userservice.controller;
import bt.gov.dit.userservice.model.User;
//import bt.gov.dit.userservice.service.UserService;
import bt.gov.dit.userservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
#RestController
#RequestMapping("/api")
public class UserController {
#Autowired
private UserService userService;
#PostMapping
public ResponseEntity<User> create(#Valid #RequestBody User user) {
User updated = userService.create(user);
return new ResponseEntity<User>(updated, new HttpHeaders(), HttpStatus.OK);
}
#GetMapping("/{role_id}")
public ResponseEntity<User> getUserByRole(#PathVariable("role_id") String role)
{
User entity = userService.getByRole(role);
return new ResponseEntity<User>(entity, new HttpHeaders(), HttpStatus.OK);
}
}
I have just started learning Spring boot and I can't seem to understand what is wrong in code. I want to insert/save new user. But when I call /api/user it says 404 not found. I am using h2 in-memory db.
I think the issue is the controller method argument name - role->role_id
#GetMapping("/{role_id}")
public ResponseEntity<User> getUserByRole(#PathVariable("role_id") String role_id)
{
User entity = userService.getByRole(role_id);
return new ResponseEntity<User>(entity, new HttpHeaders(), HttpStatus.OK);
}
the role_id should be same as you mentioned in the routes.
Route example->localhost:8080/api/2
you need to map the other part of the request like this:
#PostMapping(value="/user", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE )
I also recommend you to use Springfox Swagger UI using the annotation #EnableSwagger2
This will provide you an user interface with all requests at http://localhost:8080/swagger-ui.html
Link:
https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api

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

No property findOne() found for type class User

I have searched many pages but didnt found the answer so i paste the whole code.I am testing the testclass and getting the error like "Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract org.home.mysystem.entity.User org.home.mysystem.repository.UserRepository.findOne(java.lang.String)! No property findOne found for type User!". Please someone help me
Role.java
package org.home.mysystem.entity;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
#Entity
public class Role {
#Id
private String name;
#ManyToMany(mappedBy = "roles")
private List<User> users;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public Role(String name, List<User> users) {
this.name = name;
this.users = users;
}
public Role() {
}
public Role(String name) {
this.name = name;
}
}
Task.java
package org.home.mysystem.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
public class Task {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotEmpty
private String date;
#NotEmpty
private String startTime;
#NotEmpty
private String stopTime;
#NotEmpty
#Column(length=1000)
private String description;
#ManyToOne
#JoinColumn(name="USER_EMAIL")
private User user;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getStopTime() {
return stopTime;
}
public void setStopTime(String stopTime) {
this.stopTime = stopTime;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Task(String date, String startTime, String stopTime, String description, User user) {
this.date = date;
this.startTime = startTime;
this.stopTime = stopTime;
this.description = description;
this.user = user;
}
public Task(String date, String startTime, String stopTime, String description) {
this.date = date;
this.startTime = startTime;
this.stopTime = stopTime;
this.description = description;
}
public Task() {
}
}
User.java
package org.home.mysystem.entity;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
public class User {
#Id
#Email
#NotEmpty
#Column(unique = true)
private String email;
#NotEmpty
private String name;
#Size(min = 4)
private String password;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<Task> tasks;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "USER_ROLES", joinColumns={
#JoinColumn(name = "USER_EMAIL", referencedColumnName = "email") }, inverseJoinColumns = {
#JoinColumn(name = "ROLE_NAME", referencedColumnName = "name") })
private List<Role> roles;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Task> gettasks() {
return tasks;
}
public void settasks(List<Task> tasks) {
this.tasks = tasks;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public User(String email, String name, String password) {
this.email = email;
this.name = name;
this.password = password;
}
public User() {
}
}
RoleRepository.java
package org.home.mysystem.repository;
import org.home.mysystem.entity.Role;
import org.springframework.data.jpa.repository.JpaRepository;
public interface RoleRepository extends JpaRepository<Role, String> {
}
TaskRepository.java
public interface TaskRepository extends JpaRepository<Task, Long> {
List<Task> findByUser(User user);
}
UserRepository.java
package org.home.mysystem.repository;
import org.home.mysystem.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User,String> {
User findOne(final String email);
}
TaskService.java
package org.home.mysystem.service;
import java.util.ArrayList;
import java.util.List;
import org.home.mysystem.entity.Role;
import org.home.mysystem.entity.Task;
import org.home.mysystem.entity.User;
import org.home.mysystem.repository.TaskRepository;
import org.home.mysystem.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
#Service
public class TaskService {
#Autowired
private TaskRepository taskRepository;
public void addTask(Task task, User user) {
task.setUser(user);
taskRepository.save(task);
}
public List<Task> findUserTask(User user){
return taskRepository.findByUser(user);
}
}
UserService.java
import java.util.ArrayList;
import java.util.List;
import org.home.mysystem.entity.Role;
import org.home.mysystem.entity.User;
import org.home.mysystem.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
#Service
public class UserService {
#Autowired
private UserRepository userRepository;
public void createUser(User user) {
BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
user.setPassword(encoder.encode(user.getPassword()));
Role userRole=new Role("USER");
List<Role> roles=new ArrayList<>();
roles.add(userRole);
user.setRoles(roles);
userRepository.save(user);
}
public void createAdmin(User user) {
BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
user.setPassword(encoder.encode(user.getPassword()));
Role userRole=new Role("ADMIN");
List<Role> roles=new ArrayList<>();
roles.add(userRole);
user.setRoles(roles);
userRepository.save(user);
}
public User findOne(String email) {
return userRepository.findOne(email);
}
}
MyApplicationTest.java
package org.home.mysystem;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.List;
import org.home.mysystem.entity.Task;
import org.home.mysystem.entity.User;
import org.home.mysystem.service.TaskService;
import org.home.mysystem.service.UserService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#SpringBootTest
public class MySystemApplicationTests {
#Autowired
private UserService userService;
#Autowired
private TaskService taskService;
#Before
public void initDb() {
{
User newUser = new User("testUser#mail.com", "testUser", "123456");
userService.createUser(newUser);
}
{
User newUser = new User("testAdmin#mail.com", "testAdmin", "123456");
userService.createUser(newUser);
}
Task userTask = new Task("03/01/2018", "00:11", "11:00", "You need to work today");
User user = userService.findOne("testUser#mail.com");
taskService.addTask(userTask, user);
}
#Test
public void testUser() {
User user=userService.findOne("testUser#mail.com");
assertNotNull(user);
User admin=userService.findOne("testAdmin#mail.com");
assertEquals(admin.getEmail(),"testAdmin#mail.com");
}
#Test
public void testTask() {
User user=userService.findOne("testUser#mail.com");
List<Task> task=taskService.findUserTask(user);
assertNotNull(task);
}
}
The issue is that Spring is expecting something else as you are giving it.
findOne is by default defined to take an ID (primary key) to load the entity by. So it expects a long or Long (as far as I know). It takes the name of the parameter given (email) and is searching for an ID with that name and that simply doesn't add up.
If you want to search by an email or other field that has been defined by you, you need to use the following syntax:
Example 1
Example field to search by: email
Method in repository:
User findByEmail(String email)
Example 2
Example field to search by: username
Method in repository:
User findByUsername(String username)
I hope this helps!

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

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

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.

Resources