sessionfactory always null when done with javaconfig - spring

The sessionFactory Bean which is autowired in my DAO is always showingup to be null. below is my project.
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;
#Configuration
#Import({HibernateConfig.class})
public class AppConfig {
#Bean
public PropertyPlaceholderConfigurer propertyPlaceHolderConfigurer(){
PropertyPlaceholderConfigurer prop = new PropertyPlaceholderConfigurer();
prop.setLocation(new ClassPathResource("dbProperties.properties"));
prop.setIgnoreUnresolvablePlaceholders(true);
return prop;
}
}
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.model.Person;
#Configuration
//#EnableTransactionManagement
//#PropertySource(value={"classpath:dbProperties.properties"})
public class HibernateConfig {
#Value("${driverClassName}")
private String driverClassName;
#Value("${url}")
private String url;
#Value("${username}")
private String username;
#Value("${password}")
private String password;
#Value("${hibernate.dialect}")
private String hibernateDielect;
#Value("${hibernate.show_sql}")
private String hibernateShowSQL;
#Value("${hibernate.hbm2ddl.auto}")
private String hibernateHbm2Ddlauto;
#Bean
public DataSource datasource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
public Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", hibernateDielect);
properties.put("hibernate.show_sql", hibernateShowSQL);
properties.put("hibernate.hbm2ddl.auto", hibernateHbm2Ddlauto);
return properties;
}
#Bean
#Autowired
public SessionFactory sessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
sessionBuilder.scanPackages("com.configuration");
sessionBuilder.addAnnotatedClass(Person.class);
sessionBuilder.addProperties(hibernateProperties());
return sessionBuilder.buildSessionFactory();
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory);
return transactionManager;
}
}
import java.util.List;
import com.model.Person;
public interface PersonDao {
void savePerson(Person persom);
void deletePerson(String taxid);
List<Person> getAllPersons();
Person updatePerson(Person person);
Person findPersonById(String taxid);
}
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.model.Person;
#Service
public class PersonDaoImpl implements PersonDao {
#Autowired
SessionFactory sessionFactory;
#Override
#Transactional
public void savePerson(Person person) {
sessionFactory.getCurrentSession().persist(person);
}
#Override
#Transactional
public void deletePerson(String taxid) {
// TODO Auto-generated method stub
// Criteria criteria = getSession().createCriteria(Person.class);
Query query = sessionFactory.getCurrentSession().createSQLQuery("DELETE FROM PERSON WHERE taxid = :taxid");
query.setString(taxid, "taxid");
}
#SuppressWarnings("unchecked")
#Override
#Transactional
public List<Person> getAllPersons() {
// TODO Auto-generated method stub
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Person.class);
return (List<Person>) criteria.list();
}
#Override
#Transactional
public Person updatePerson(Person person) {
// TODO Auto-generated method stub
sessionFactory.getCurrentSession().update(person);
return person;
}
#Override
#Transactional
public Person findPersonById(String taxid) {
// TODO Auto-generated method stub
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Person.class);
criteria.add(Restrictions.eq("taxid", taxid));
return (Person) criteria.uniqueResult();
}
}
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name ="person")
public class Person {
#Column(name ="FIRSTNAME")
private String firstName;
#Column(name ="LASTNAME")
private String lastName;
#Column(name ="DOB")
private Date DOB;
#Column(name ="TAXID")
#Id
private String taxid;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getDOB() {
return DOB;
}
public void setDOB(Date dOB) {
DOB = dOB;
}
public String getTaxid() {
return taxid;
}
public void setTaxid(String taxid) {
this.taxid = taxid;
}
#Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + ", DOB=" + DOB + ", taxid=" + taxid + "]";
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((DOB == null) ? 0 : DOB.hashCode());
result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
result = prime * result + ((taxid == null) ? 0 : taxid.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (DOB == null) {
if (other.DOB != null)
return false;
} else if (!DOB.equals(other.DOB))
return false;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
if (taxid == null) {
if (other.taxid != null)
return false;
} else if (!taxid.equals(other.taxid))
return false;
return true;
}
}
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import com.configuration.AppConfig;
import com.dao.PersonDaoImpl;
import com.model.Person;
public class AppMain {
public static void main(String args[]) {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Person person = new Person();
person.setFirstName("Akhil");
person.setLastName("goli");
person.setTaxid("123abc456");
PersonDaoImpl impl = new PersonDaoImpl();
impl.savePerson(person);
}
}
Exception in thread "main" java.lang.NullPointerException at
com.dao.PersonDaoImpl.savePerson(PersonDaoImpl.java:25) at
main.AppMain.main(AppMain.java:20)

You have to call afterPropertiesSet() for initializing the bean. Now you only created the bean but not initialized.

I figured it out. As I was using Hibernate4 I need to use
StandardServiceRegistryBuilder class to get SessionFactory.
Hope this snippet helps.
public class HibernateUtil {
public SessionFactory getSessionFactory()
{
Configuration config = new Configuration().configure();
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder().applySettings(config.getProperties());
SessionFactory session = config.buildSessionFactory(serviceRegistryBuilder.build());
return session;
}

I am putting sessionFactory configuration code here. Hope it will help you.
#Bean
// #Autowired
// #Bean(name = "sessionFactory")
public SessionFactory sessionFactory() throws IOException {
Properties hibernateProperties = new Properties();
hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL);
hibernateProperties.put("hibernate.hbm2ddl.auto", HIBERNATE_HBM2DDL_AUTO);
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
sessionFactory.setHibernateProperties(hibernateProperties);
sessionFactory.afterPropertiesSet(); // Used in Spring-boot 2.x for initializing the bean
SessionFactory sf = sessionFactory.getObject();
System.out.println("## getSessionFactory: " + sf);
return sf;
}

Related

Can not configuring a Global Date and Time Format

I wrote a DateTimeFormatAnnotationFormatterFactory to use for global conversion of LocalDateTime, imitating LocalDateTimeFormatAnnotationFormatterFactory
package com.taimi.localdatetimedemo.format.date;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.springframework.format.AnnotationFormatterFactory;
import org.springframework.format.Formatter;
import org.springframework.format.Parser;
import org.springframework.format.Printer;
/**
* LocalDateTimeFormatAnnotationFormatterFactory
*/
public class LocalDateTimeFormatAnnotationFormatterFactory implements AnnotationFormatterFactory<LocalDateTimeFormat> {
private static final Set<Class<?>> FIELD_TYPES;
static {
Set<Class<?>> fieldTypes = new HashSet<>(1);
fieldTypes.add(LocalDateTime.class);
FIELD_TYPES = Collections.unmodifiableSet(fieldTypes);
}
#Override
public Set<Class<?>> getFieldTypes() {
return FIELD_TYPES;
}
#Override
public Printer<?> getPrinter(LocalDateTimeFormat annotation, Class<?> fieldType) {
return getFormatter(annotation, fieldType);
}
#Override
public Parser<?> getParser(LocalDateTimeFormat annotation, Class<?> fieldType) {
return getFormatter(annotation, fieldType);
}
protected Formatter<LocalDateTime> getFormatter(LocalDateTimeFormat annotation, Class<?> fieldType) {
LocalDateTimeFormater localDateTimeFormater=new LocalDateTimeFormater(annotation.pattern());
return localDateTimeFormater;
}
}
public #interface LocalDateTimeFormat {
String pattern() default "";
}
package com.taimi.localdatetimedemo.format.date;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import org.springframework.format.Formatter;
import org.springframework.util.StringUtils;
/**
* LocalDateFormater
*/
public class LocalDateTimeFormater implements Formatter<LocalDateTime> {
private String pattern;
public LocalDateTimeFormater(String pattern) {
if (StringUtils.isEmpty(pattern)) {
throw new IllegalArgumentException("Pattern can't be empty.", null);
}
this.pattern = pattern;
}
#Override
public String print(LocalDateTime localDateTime, Locale locale) {
return createDateTimeFormatter(locale).format(localDateTime);
}
#Override
public LocalDateTime parse(String text, Locale locale) throws ParseException {
return LocalDateTime.parse(text, createDateTimeFormatter(locale));
}
private DateTimeFormatter createDateTimeFormatter(Locale locale) {
return DateTimeFormatter.ofPattern(pattern, locale);
}
}
The configuration is
#Configuration
public class TimeConfig extends WebMvcConfigurationSupport {
#Override
public FormattingConversionService mvcConversionService() {
// DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(false);
FormattingConversionService conversionService=new FormattingConversionService();
conversionService.addFormatterForFieldAnnotation(new LocalDateTimeFormatAnnotationFormatterFactory());
return conversionService;
}
}
But it always failed in conversion because converterCache can not find a suitable converter or is empty.
The source code of finding converter is showing down below from GenericConversionService
#Nullable
protected GenericConverter getConverter(TypeDescriptor sourceType, TypeDescriptor targetType) {
ConverterCacheKey key = new ConverterCacheKey(sourceType, targetType);
GenericConverter converter = this.converterCache.get(key);
if (converter != null) {
return (converter != NO_MATCH ? converter : null);
}
converter = this.converters.find(sourceType, targetType);
if (converter == null) {
converter = getDefaultConverter(sourceType, targetType);
}
if (converter != null) {
this.converterCache.put(key, converter);
return converter;
}
this.converterCache.put(key, NO_MATCH);
return null;
}
I've found out where I was wrong, the #Interface should be
#Target(ElementType.FIELD)
#Retention(RetentionPolicy.RUNTIME)
public #interface LocalDateTimeFormat {
String pattern() default "";
}

No qualifying bean of type 'com.springmvc.dao.UserDAO' available: expected at least 1 bean which qualifies as autowire candidate

I am getting an error as No qualifying bean of type 'com.springmvc.dao.UserDAO' available: expected at least 1 bean which qualifies as autowire candidate. for the following code, My base class is "com.springmvc"
My Controller Class is
package com.springmvc.controller;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.springmvc.dao.UserDAO;
import com.springmvc.dao.UserDAOImpl;
import com.springmvc.type.User;
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#Autowired
private UserDAO usrdao;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("Date", formattedDate );
return "index";
}
/*
#RequestMapping(value="/login",method = RequestMethod.POST)
public String welcome(Locale locale,Model model,#ModelAttribute("LoginBean")LoginBean login){
if(login != null && login.getUserName() != "" && login.getPassword() != ""){
if(login.getUserName().equals("ajith") && login.getPassword().equals("123")){
model.addAttribute("msg","Welcome "+login.getUserName());
return "welcome";
}
else{
model.addAttribute("error","Invalid Login Details");
return "index";
}
}
else{
model.addAttribute("error","Please Enter Login Details");
return "index";
}
}
*/
#RequestMapping(value="/checkLogin",method = RequestMethod.POST)
public String CheckUser(Model model,#ModelAttribute("User")User user){
if(user != null && user.getUserName() != "" && user.getPass() != ""){
boolean isActive = usrdao.isActiveUser(user.getUserName(), user.getPass());
if(isActive){
List<User> usrLst = usrdao.ListAllUsers();
model.addAttribute("message",user.getUserName());
model.addAttribute("usrLst",usrLst);
return "home";
}
else{
model.addAttribute("error","Invalid Login Details");
return "index";
}
}
return "index";
}
#RequestMapping(value="/createUser", method = RequestMethod.GET)
public String RedirectCreateUser(Model model){
return "createUser";
}
public String createUser(Model model, #ModelAttribute User user){
usrdao.CreateOrUpdateUser(user);
return "";
}
}
UserDAO
package com.springmvc.dao;
import java.util.List;
import com.springmvc.type.User;
public interface UserDAO {
public void CreateOrUpdateUser(User user);
public void DeleteUser(int uid);
public User GetUser(int uid);
public List<User> ListAllUsers();
public boolean isActiveUser(String userName,String pass);
}
UserDAOImpl
package com.springmvc.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Repository;
import com.springmvc.type.User;
#Repository("UserDAO")
public class UserDAOImpl implements UserDAO {
private JdbcTemplate jdbc;
/*
public void setJdbc(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
*/
public UserDAOImpl(DataSource DS) {
jdbc = new JdbcTemplate(DS);
}
#Override
public void CreateOrUpdateUser(User user) {
if(user.getUid() == 0){
String query = "INSERT INTO userdetails(UserName,Name,Pass) VALUES(?,?,?)";
jdbc.update(query,user.getUserName(),user.getName(),user.getPass());
}
else{
String query = "UPDATE userdetails SET UserName = ?,Name = ?,Pass = ?,isActive = ? WHERE id = ?";
jdbc.update(query, user.getUserName(),user.getName(),user.getPass(),user.getIsActive(),user.getUid());
}
}
#Override
public void DeleteUser(int uid) {
String query = "DELETE FROM userdetails WHERE id = ?";
jdbc.update(query, uid);
}
#Override
public User GetUser(int uid) {
String query = "SELECT * FROM userdetails WHERE id = ?";
return jdbc.query(query, new ResultSetExtractor<User>() {
#Override
public User extractData(ResultSet rs) throws SQLException, DataAccessException {
if(rs.next()){
User user = new User();
user.setUid(rs.getInt("id"));
user.setUserName(rs.getString("UserName"));
user.setName(rs.getString("Name"));
user.setIsActive(rs.getInt("isActive"));
return user;
}
return null;
}
});
}
#Override
public List<User> ListAllUsers() {
String query = "SELECT * FROM userdetails";
List <User> usrLst = jdbc.query(query, new RowMapper<User>() {
#Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setUid(rs.getInt("id"));
user.setUserName(rs.getString("UserName"));
user.setName(rs.getString("Name"));
user.setIsActive(rs.getInt("isActive"));
return user;
}
});
return usrLst;
}
#Override
public boolean isActiveUser(String userName, String pass) {
String query = "SELECT id FROM userdetails WHERE UserName = ? AND Pass = ? AND isActive = 1";
SqlRowSet rs = jdbc.queryForRowSet(query,userName,pass);
if(rs.next())
return true;
else
return false;
}
}
Thank You
UserDAOImpl do not have default constructor. either add default constructor or autowire the construction arg.
Spring is using a strong naming convention.
Try to use as a variable userDao as the autowired variable and use the same string in the #repository.
See this little explanation here:
https://www.tutorialspoint.com/spring/spring_beans_autowiring.htm

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