Spring with REST - json

I am learning Spring framework. I have created a sample project with SpringMVC with REST + JSON. I can able to compile successfully but when i hit the rest url, the system says below message
org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/SpringMVC/rest/employee] in DispatcherServlet with name 'springmvc'.
Below is the springmvc-servlet.xml
<context:component-scan base-package="com.springmvc.beans" />
<context:annotation-config />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonMessageConverter" />
</list>
</property>
</bean>
<!-- Configure bean to convert JSON to POJO and vice versa -->
<bean id="jsonMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>
And the Web.xml
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
And the EmployeeController.java
package com.springmvc.beans;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class EmployeeController {
public static final String GET_EMPLOYEE = "/rest/employee/{empId}";
public static final String CREATE_EMPLOYEE = "/rest/employee/create/";
public static final String DELETE_EMPLOYEE = "/rest/employee/delete/{empId}";
public static final String GET_ALL_EMPLOYEES = "/rest/employee/";
private Map<String, Employee> employeeData = new HashMap<String, Employee>();
private Integer count = 1;
#RequestMapping(method=RequestMethod.GET, value=GET_EMPLOYEE)
public #ResponseBody Employee getEmployee(#PathVariable ("empId") String empId){
return employeeData.get(empId);
}
#RequestMapping(method=RequestMethod.PUT, value=CREATE_EMPLOYEE)
public #ResponseBody void createEmployee(){
employeeData.put(String.valueOf(count++), new Employee(String.valueOf(count++), "Batman"+Math.random(), "23"+Math.random(), "Andartica"+Math.random(), "dash2#gmail.com"+Math.random()));
}
#RequestMapping(method=RequestMethod.PUT, value=DELETE_EMPLOYEE)
public #ResponseBody void deleteEmployee(#PathVariable ("empId") String empId){
employeeData.remove(empId);
}
#RequestMapping(method=RequestMethod.GET, value=GET_ALL_EMPLOYEES)
public #ResponseBody Map<String, Employee> getAllEmployees(){
return employeeData;
}
{
employeeData.put(String.valueOf(count), new Employee("1", "Mani", "31", "America", "Dash#gmail.com"));
}
}
Finally the Employee.java pojo
package com.springmvc.beans;
/**
* #author Mani
*
*/
public class Employee {
private String empId;
private String name;
private String age;
private String address;
private String email;
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Employee(String empId, String name, String age, String address, String email) {
super();
this.empId = empId;
this.name = name;
this.age = age;
this.address = address;
this.email = email;
}
}
Note : My Spring version is 4.1 and I have added below jars in my classpath to convert output to JSON message
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.1</version>
</dependency>
</dependencies>
Kindly help to solve this.
Thanks in Advance
Manivannan

looking at the code the endpoint is mapped to
public static final String GET_ALL_EMPLOYEES = "/rest/employee/";
where as the url being accessed is
/SpringMVC/rest/employee
org.springframework.web.servlet.PageNotFound noHandlerFound WARNING: No mapping found for HTTP request with URI [/SpringMVC/rest/employee] in DispatcherServlet with name 'springmvc'.
Try making as below:
GET_ALL_EMPLOYEES = "/rest/employee";

Related

Spring Boot Application : java.lang.IllegalArgumentException: At least one JPA metamodel must be present

I am trying to use a Simple Spring boot application to create Users and save them to the database using Hibernate but i am getting this error.
Can you please direct me to be able to solve this problem ?
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'jpaMappingContext': Invocation of init
method failed; nested exception is java.lang.IllegalArgumentException:
At least one JPA metamodel must be present! at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
My Application includes :
Pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springboot</groupId>
<artifactId>SpringBootHibernateInt</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath />
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
DataSource COnfiguration:
package com.spring.security.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
#Configuration
#EnableTransactionManagement
public class DataSourceConfig {
#Autowired
Environment env;
#Bean
public DataSource getDataSource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
ds.setUrl(env.getProperty("spring.datasource.url"));
ds.setUsername(env.getProperty("spring.datasource.username"));
ds.setPassword(env.getProperty("spring.datasource.password"));
return ds;
}
#Bean
public Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("spring.hibernate.dialect", env.getProperty("spring.hibernate.dialect"));
properties.put("spring.hibernate.show-sql", env.getProperty("spring.hibernate.show-sql"));
properties.put("spring.hibernate.format-sql", env.getProperty("spring.hibernate.format-sql"));
properties.put("spring.hibernate.ddl-auto", env.getProperty("spring.hibernate.ddl-auto"));
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager htm = new HibernateTransactionManager();
htm.setSessionFactory(getSessionFactory().getObject());
return htm;
}
#Bean
public LocalSessionFactoryBean getSessionFactory() {
LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
lsfb.setDataSource(getDataSource());
lsfb.setHibernateProperties(getHibernateProperties());
// lsfb.setAnnotatedClasses(User.class);
lsfb.setPackagesToScan(env.getProperty("entitymanager.packagesToScan"));
return lsfb;
}
}
User.java
package com.spring.security.model;
import javax.persistence.*;
#Entity
#Table(name = "User")
public class User {
public User(String name) {
this.name = name;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
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;
}
}
UserDAOImpl.java
package com.spring.security.dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.spring.security.model.User;
#Repository
#Transactional
public class UserDAOImpl {
#Autowired
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public User findUser(String userName) {
return (User) sessionFactory.getCurrentSession()
.createQuery("from User where name = " + userName);
}
public void createUser(User user) {
sessionFactory.getCurrentSession()
.save(user);
}
}
Controller
package com.spring.security.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.spring.security.dao.UserDAOImpl;
import com.spring.security.model.User;
#Controller
public class HomeController {
#Autowired
private UserDAOImpl userService;
#RequestMapping(value = "/save")
#ResponseBody
public String create(String name) {
try {
User user = new User(name);
userService.createUser(user);
} catch (Exception ex) {
return ex.getMessage();
}
return "User succesfully saved!";
}
}
Run.java
package com.spring.security;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Run {
public static void main(String[] args) {
SpringApplication.run(Run.class, args);
}
}
Application.properties
################### JDBC Configuration ###############################
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3307/***
spring.datasource.username=***
spring.datasource.password=***
################### Hibernate Configuration ##########################
spring.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.hibernate.show-sql=true
spring.hibernate.format-sql=true
spring.hibernate.ddl-auto=create
entitymanager.packagesToScan = com
As I said in my comment you can remove all the manual data source configuration as Spring Boot will auto configure it all for you. You can also use JPA repositories for what you need. Replace your UserDaoImpl class with a new repository interface:
#Repository
interface UserRepository implements CrudRepository<User, Integer> {
User findByName(String name);
}
Then in your controller:
#Controller
public class HomeController {
#Autowired
private UserRepository userService;
#RequestMapping(value = "/save")
#ResponseBody
public String create(String name, String city) {
try {
User user = new User("JAYESH");
userService.save(user);
} catch (Exception ex) {
return ex.getMessage();
}
return "User succesfully saved!";
}
}
If you really really want to use Hibernate SessionFactory you can do the following:
#Component
public SomeClass {
#Autowired
private EntityManagerFactory emFactory;
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return emFactory.unwrap(SessionFactory.class);
}
}
Spring Boot by Default Enable Auto Configuration class for the data source, you can simply disable this by something like this.
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class,JndiConnectionFactoryAutoConfiguration.class,
HibernateJpaAutoConfiguration.class,JpaRepositoriesAutoConfiguration.class,DataSourceTransactionManagerAutoConfiguration.class})
#ComponentScan
public class SpringBootStarter {
public static void main(String[] args) {
SpringApplication.run(MyBootApplication.class, args);
}
}
This may help you :)

HTTP Status 500 - Servlet.init() for servlet management threw exception

Emp.java
package com.management;
public class Emp {
private int id;
private String name;
private float salary;
private String designation;
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 float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
EmpController.java
package com.management;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 org.springframework.web.servlet.ModelAndView;
import com.management.Emp;
import com.management.EmpDao;
#Controller
public class EmpController {
#Autowired
EmpDao dao;//will inject dao from xml file
/*It displays a form to input data, here "command" is a reserved request attribute
*which is used to display object data into form
*/
#RequestMapping("/empform")
public ModelAndView showform(){
return new ModelAndView("empform","command",new Emp());
}
/*It saves object into database. The #ModelAttribute puts request data
* into model object. You need to mention RequestMethod.POST method
* because default request is GET*/
#RequestMapping(value="/save",method = RequestMethod.POST)
public ModelAndView save(#ModelAttribute("emp") Emp emp){
dao.save(emp);
return new ModelAndView("redirect:/viewemp");//will redirect to viewemp request mapping
}
/* It provides list of employees in model object */
#RequestMapping("/viewemp")
public ModelAndView viewemp(){
List<Emp> list=dao.getEmployees();
return new ModelAndView("viewemp","list",list);
}
/* It displays object data into form for the given id.
* The #PathVariable puts URL data into variable.*/
#RequestMapping(value="/editemp/{id}")
public ModelAndView edit(#PathVariable int id){
Emp emp=dao.getEmpById(id);
return new ModelAndView("empeditform","command",emp);
}
/* It updates model object. */
#RequestMapping(value="/editsave",method = RequestMethod.POST)
public ModelAndView editsave(#ModelAttribute("emp") Emp emp){
dao.update(emp);
return new ModelAndView("redirect:/viewemp");
}
/* It deletes record for the given id in URL and redirects to /viewemp */
#RequestMapping(value="/deleteemp/{id}",method = RequestMethod.GET)
public ModelAndView delete(#PathVariable int id){
dao.delete(id);
return new ModelAndView("redirect:/viewemp");
}
}
EmpDao.java
package com.management;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.management.Emp;
public class EmpDao {
JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public int save(Emp p){
String sql="insert into Emp99(name,salary,designation) values('"+p.getName()+"',"+p.getSalary()+",'"+p.getDesignation()+"')";
return template.update(sql);
}
public int update(Emp p){
String sql="update Emp99 set name='"+p.getName()+"', salary="+p.getSalary()+", designation='"+p.getDesignation()+"' where id="+p.getId()+"";
return template.update(sql);
}
public int delete(int id){
String sql="delete from Emp99 where id="+id+"";
return template.update(sql);
}
public Emp getEmpById(int id){
String sql="select * from Emp99 where id=?";
return template.queryForObject(sql, new Object[]{id},new BeanPropertyRowMapper<Emp>(Emp.class));
}
public List<Emp> getEmployees(){
return template.query("select * from Emp99",new RowMapper<Emp>(){
public Emp mapRow(ResultSet rs, int row) throws SQLException {
Emp e=new Emp();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getFloat(3));
e.setDesignation(rs.getString(4));
return e;
}
});
}
}
servlet-management.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.spring" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://loclahost:3306/test1" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="dao" class="com.spring.EmpDao">
<property name="template" ref="jt"></property>
</bean>
</beans>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>management</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>management</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
hi
my trying to insert the value to the database by using the spring-mvc.
and using the mysql database.
while execution process it shows the error like that-org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.spring.EmpDao] for bean with name 'dao' defined in ServletContext resource [/WEB-INF/management-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.spring.EmpDao .
please provide the soluation.
thank you.

Spring Boot connect Mysql and MongoDb

I have a problem with Spring Boot application. I want to connect a MongoDB database and a MySql database in my Spring boot application. I would to know if it is possible, in positive case How I can make this multiple connection. I had made a try based on an example with Mysql and Post without success. So I'm wondering if someone have an easy example to know the method.
thanks
It is possible to do this.you will have create different configuration for different datasources. This link has good examples on that
http://www.baeldung.com/spring-data-jpa-multiple-databases
Another useful stackoverflow question: Spring Boot Configure and Use Two DataSources
To get started with mongo and mysql , you can follow example from spring.io guides.
https://spring.io/guides/gs/accessing-data-mongodb/
https://spring.io/guides/gs/accessing-data-mysql/
EDIT :
I have created this one example, merging two samples above
package hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import hello.model.Customer;
import hello.model.User;
import hello.mongodao.CustomerRepository;
import hello.mysqldao.UserRepository;
#EnableMongoRepositories(basePackageClasses = CustomerRepository.class)
#EnableJpaRepositories (basePackageClasses = UserRepository.class)
#SpringBootApplication
public class Application implements CommandLineRunner {
#Autowired
private CustomerRepository repository;
#Autowired
private UserRepository userRepository;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("getting data from Mongo");
repository.deleteAll();
// save a couple of customers
repository.save(new Customer("Alice", "Smith"));
repository.save(new Customer("Bob", "Smith"));
// fetch all customers
System.out.println("Customers found with findAll():");
System.out.println("-------------------------------");
for (Customer customer : repository.findAll()) {
System.out.println(customer);
}
System.out.println();
// fetch an individual customer
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);
}
System.out.println("gettting data from mysql");
userRepository.deleteAll();
// save a couple of customers
userRepository.save(new User("Alice", "Alice#Smith.com"));
userRepository.save(new User("Bob", "Bob#Smith.com"));
// fetch all customers
System.out.println("Users found with findAll():");
System.out.println("-------------------------------");
for (User user : userRepository.findAll()) {
System.out.println(user);
}
}
}
CustomerRepository.java
package hello.mongodao;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import hello.model.Customer;
public interface CustomerRepository extends MongoRepository<Customer, String> {
public Customer findByFirstName(String firstName);
public List<Customer> findByLastName(String lastName);
}
UserRepository.java
package hello.mysqldao;
import org.springframework.data.repository.CrudRepository;
import hello.model.User;
// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
// CRUD refers Create, Read, Update, Delete
public interface UserRepository extends CrudRepository<User, Long> {
}
Customer.java
package hello.model;
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);
}
}
User.java
package hello.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity // This tells Hibernate to make a table out of this class
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
private String email;
public User() {
// TODO Auto-generated constructor stub
}
public User(String string, String string2) {
// TODO Auto-generated constructor stub
name = string;
email = string2;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.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;
}
#Override
public String toString() {
return String.format(
"User[id=%s, name='%s', email='%s']",
id, name, email);
}
}
application.properties
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
spring.data.mongodb.uri=mongodb://localhost:27017/local
You really don't need to make additional config and property files because MongoDB has different property names than sql so all you will need is an application.properties file
application.properties
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/dbName?useUnicode=yes&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=
spring.data.mongodb.uri=mongodb://localhost:27017
spring.data.mongodb.database=dbName
example models
MongoDB document
import org.springframework.data.mongodb.core.mapping.Document;
import javax.persistence.Id;
#Document("Gyros")
public class Gyros {
public Gyros(String description) {
this.description = description;
}
#Id
public String id;
public String description;
}
Mysql JPA entity
import javax.persistence.*;
#Entity
#Table(name = "Kebab")
public class Kebab {
public Kebab(String description) {
this.description = description;
}
public Kebab() {
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int id;
public String description;
}
MongoDB repository
#Repository
public interface GyrosRepository extends MongoRepository<Gyros, String> {
}
Mysql Jpa repository
#Repository
public interface KebabRepository extends JpaRepository<Kebab, Integer> {
}
TestService
#org.springframework.stereotype.Service
public class Service {
private final GyrosRepository gyrosRepository;
private final KebabRepository kebabRepository;
#Autowired
public Service(GyrosRepository gyrosRepository, KebabRepository kebabRepository) {
this.gyrosRepository = gyrosRepository;
this.kebabRepository = kebabRepository;
}
#PostConstruct
void test() {
this.gyrosRepository.insert(new Gyros("ham ham"));
this.kebabRepository.saveAndFlush(new Kebab("yum yum"));
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.example</groupId>
<artifactId>stack</artifactId>
<version>1.0-SNAPSHOT</version>
<name>stackoverflow</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
I also faced the same kind of problem once. I had to connect my spring boot application to two different databases. One was Mongo db and other was Postgres db.
You can see that i have used both JPA as well as spring-boot-starter-data-mongodb. Still my project is running absolutely fine.Hope for you also it work successfully. There are suggestions over the internet to not use JPA but i am not able to use JPA repository without include JPA.
Here I am posting the solution which worked for me.
Hope it helps someone:
application.properties file:
MONGODB (MongoProperties)
spring.data.mongodb.uri=mongodb://XX.XX.XX.XX:27017/testdb
#POSTGRES properties
spring.datasource.platform=postgres
spring.datasource.url= jdbc:postgresql://localhost:5432/database_name
spring.datasource.username=postgres_usr_name
spring.datasource.password=postgres_pwd
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
My pom dependencies:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
To access my data Using Repositories:
(i): MONGO REPOSITORY
import org.springframework.data.mongodb.repository.MongoRepository;
public interface MRepositories extends MongoRepository<YourEntityClass, String>{
}
(ii): JPA repository
#Repository public interface PostGresRepo extends JpaRepository<TestEntity,Long> {}

MVC not returning json... request not available

Hi all I want to return a userName with a rest http request in Spring + Mysql.
Controller:
#Controller
#SessionAttributes("user")
public class UserController {
#Autowired
private UserService userService;
#RequestMapping(method=RequestMethod.GET, value="/userss/{userName}")
public #ResponseBody String getUserName(#PathVariable String userName) {
return userName;
}
}
Model:
#Entity
#Table(name="users")
public class User {
#Id
#GeneratedValue
private Long id;
#NotEmpty
#Size(min=4, max=20)
private String userName;
#NotEmpty
private String firstName;
#NotEmpty
private String lastName;
#NotEmpty
#Size(min=4, max=8)
private String password;
#NotEmpty
private String status;
#NotEmpty
#Email
private String emailAddress;
#NotNull
#Past
#DateTimeFormat(pattern="MM/dd/yyyy")
private Date dateOfBirth;
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 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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
I just want to retrieve my services put,delete,post and get with requestmappings connecting with my model to my mysql DB. I´m trying to make the request in this way:
http://localhost:8080/portuzona/userss?userName=Arnoldo
But I get this:
HTTP Status 404 - /portuzona/userss
type Status report
message /portuzona/userss
description The requested resource is not available.
portuzona and userss is correctly handled (html views) but I cannot make a get in my controllers.
Log says correctly the Table has been found by the bean:
sep 25, 2015 2:07:22 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: portuzona.users
sep 25, 2015 2:07:22 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [dateofbirth, password, firstname, emailaddress, id, username, lastname, status]
As a User requested here is more info that could be help .. or not:
/WEB-INF/servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>usersHibernateServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/servletConfig.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>usersHibernateServlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/jpaContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<display-name>Archetype Created Web Application</display-name>
</web-app>
/WEB-INF/config/servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.portuzona" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
</beans>
Looks like you're mixing up mapping and path variables. Two options:
1:
#RequestMapping(method=RequestMethod.GET, value="/userss/{userName}")
public #ResponseBody String getUname(#PathVariable String userName) {
return userName;
}
http://localhost:8080/portuzona/userss/Arnoldo
2:
#RequestMapping(method=RequestMethod.GET, value="/userss/yourmapping")
public #ResponseBody String getUserName(#RequestParam String username) {
return username;
}
http://localhost:8080/portuzona/userss/yourmapping?username=Arnoldo
Try the following with http://localhost:8080/portuzona/userss?userName=Arnoldo
#RequestMapping(method=RequestMethod.GET, value="/userss")
public #ResponseBody String getUserName(#RequestParam String userName) {
return userName;
}

calling rest api in spring

I am having rest method in spring controller like below:
#RequestMapping(value="/register/{userName}" ,method=RequestMethod.GET)
#ResponseBody
public String getUserName(HttpServletRequest request,#PathVariable String userName ){
System.out.println("User Name : "+userName);
return "available";
}
In jquery I have writeen ajax call like:
$(document).ready(function(){
$('#userName').blur(function(){
var methodURL = "http://localhost:8085/ums/register/"+$('#userName').val();
$.ajax({
type : "get",
URL : methodURL,
data : $('#userName').val(),
success : function(data){
alert(data);
$('#available').show();
}
})
});
});
In web.xml I have:
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
In spring-servlet.xml I have the view resolver like below:
<context:component-scan base-package="com.users.controller" />
<context:annotation-config />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1"/>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="text/xml" />
<entry key="htm" value="text/html" />
</map>
</property>
<property name="ignoreAcceptHeader" value="true" />
<!-- <property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />-->
<property name="defaultContentType" value="text/html" />
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="2" />
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
When I am running this in server, it is not going to controller.
Please let me know the problem with this code.
Please can any one help on this.
Regards,
Shruti
Since you have the #RequestMapping(value="register/{userName}" on your method definition, your jquery call must follow the same syntax.
var methodURL = "http://localhost:8085/users/register/"+$('#userName').val()+".html";
But you have also a problem in your RequestMapping value, it should start with /
#RequestMapping(value="/register/{userName}"
Also I doubt that you need the ".html" at the end
Add this line to your spring-servlet.xml. It will enable the Web MVC specific annotations like #Controller and #RequestMapping
<mvc:annotation-driven />
Example of an annotated controller
Assuming the url with context is http://localhost:8080/webapp and you want an api call like url /users/register/johnDoe. (johnDoe being the username)
You controller class would look something like the following.
#Controller
#RequestMapping(value="/users")
class UserController {
#ResponseBody
#RequestMapping(value="/register/{username}", method=RequestMethod.GET)
public String registerUser(#PathVariable String username) {
return username;
}
}
Please find my solution for calling REST web-services in Spring Framework.
/**
* REST API Implementation Using REST Controller
* */
#RestController
public class RestReqCntrl {
#Autowired
private UserService userService;
#Autowired
private PayrollService payrollService;
//-------------------Create a User--------------------------------------------------------
#RequestMapping(value = "/registerUser", method = RequestMethod.POST)
public ResponseEntity<User> registerUser(#RequestBody User user, UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("Creating User " + user.getFirstName());
boolean flag = userService.registerUser(user);
if (flag)
{
user.setStatusCode(1);
user.setStatusDesc("PASS");
}else{
user.setStatusCode(0);
user.setStatusDesc("FAIL");
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/registerUser").buildAndExpand(user.getId()).toUri());
return new ResponseEntity<User>(user,headers, HttpStatus.CREATED);
}
//-------------------Authenticating the User--------------------------------------------------------
#RequestMapping(value = "/authuser", method = RequestMethod.POST)
public ResponseEntity<User> authuser(#RequestBody User user,UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("Creating User " + user.getFirstName());
boolean flag = userService.authUser(user);
if (flag)
{
user.setStatusCode(1);
user.setStatusDesc("PASS");
}else{
user.setStatusCode(0);
user.setStatusDesc("FAIL");
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/authuser").buildAndExpand(user.getFirstName()).toUri());
return new ResponseEntity<User>(user,headers, HttpStatus.ACCEPTED);
}
//-------------------Create a Company--------------------------------------------------------
#RequestMapping(value = "/registerCompany", method = RequestMethod.POST)
public ResponseEntity<String> registerCompany(#RequestBody ComypanyDTO comypanyDTO, UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("Creating comypanyDTO " + comypanyDTO.getCmpName());
String result ="";
boolean flag = payrollService.registerCompany(comypanyDTO);
if (flag)
{
result="Pass";
}else{
result="Fail";
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand(result).toUri());
return new ResponseEntity<String>(result,headers, HttpStatus.ACCEPTED);
}
//-------------------Create a Employee--------------------------------------------------------
#RequestMapping(value = "/registerEmployee", method = RequestMethod.POST)
public ResponseEntity<String> registerEmployee(#RequestBody EmployeeDTO employeeDTO, UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("Creating registerCompany " + employeeDTO.getEmpCode());
String result ="";
boolean flag = payrollService.registerEmpbyComp(employeeDTO);
if (flag)
{
result="Pass";
}else{
result="Fail";
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand(result).toUri());
return new ResponseEntity<String>(result,headers, HttpStatus.ACCEPTED);
}
//-------------------Get Company Deatils--------------------------------------------------------
#RequestMapping(value = "/getCompanies", method = RequestMethod.GET)
public ResponseEntity<List<ComypanyDTO> > getCompanies(UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("getCompanies getCompanies ");
List<ComypanyDTO> comypanyDTOs =null;
comypanyDTOs = payrollService.getCompanies();
//Setting the Respective Employees
for(ComypanyDTO dto :comypanyDTOs){
dto.setEmployeeDTOs(payrollService.getEmployes(dto.getCompanyId()));
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand("LISt").toUri());
return new ResponseEntity<List<ComypanyDTO>>(comypanyDTOs,headers, HttpStatus.ACCEPTED);
}
}
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
#Entity
#Table(name="USER_TABLE")
public class User implements Serializable {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String firstName;
private String lastName;
private String email;
private String userId;
private String password;
private String userType;
private String address;
#Transient
private int statusCode;
#Transient
private String statusDesc;
public User(){
}
public User(String firstName, String lastName, String email, String userId, String password, String userType,
String address) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.userId = userId;
this.password = password;
this.userType = userType;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
/**
* #return the userType
*/
public String getUserType() {
return userType;
}
/**
* #param userType the userType to set
*/
public void setUserType(String userType) {
this.userType = userType;
}
/**
* #return the address
*/
public String getAddress() {
return address;
}
/**
* #param address the address to set
*/
public void setAddress(String address) {
this.address = address;
}
/**
* #return the statusCode
*/
public int getStatusCode() {
return statusCode;
}
/**
* #param statusCode the statusCode to set
*/
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
/**
* #return the statusDesc
*/
public String getStatusDesc() {
return statusDesc;
}
/**
* #param statusDesc the statusDesc to set
*/
public void setStatusDesc(String statusDesc) {
this.statusDesc = statusDesc;
}
}