extending MongoRepository - spring

I'm new to spring and confused as to how autowiring works on an interface that extends MongoRepository
Here is the code:
App.java
package com.db.mongo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class App implements CommandLineRunner
{
#Autowired
private CustomerRepository repository;
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
repository.deleteAll();
repository.save(new Customer("Alice", "Smith"));
repository.save(new Customer("Bob", "Smith"));
System.out.println("Customers found with findAll():");
System.out.println("-------------------------------");
for (Customer customer : repository.findAll()) {
System.out.println(customer);
}
System.out.println();
System.out.println("Customer found with findByFirstName('Alice'):");
System.out.println("--------------------------------");
System.out.println(repository.findByFirstName("Alice"));
System.out.println("Customers found with findByLastName('Smith'):");
System.out.println("--------------------------------");
for (Customer customer : repository.findByLastName("Smith")) {
System.out.println(customer);
}
}
}
CustomerRepository
package com.db.mongo;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface CustomerRepository extends MongoRepository {
public Customer findByFirstName(String firstName);
public List<Customer> findByLastName(String lastName);
}
Customer.java
package com.db.mongo;
import org.springframework.data.annotation.Id;
public class Customer {
#Id
public String id;
public String firstName;
public String lastName;
public Customer() {}
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString() {
return String.format(
"Customer[id=%s, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
}

if you are using spring data mongodb.It has the capability to create the query which are in your domain. The CrudRepository provides sophisticated CRUD functionality for the entity class that is being managed.for more details read here

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.

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

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

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