Why Table is not being created in database using springboot? - java

I have created a new spring boot project. Every thing is fine with the project. The project also starts smoothly. But the table that should be created in the associated database is not being created. Given below is the source code that I have used:
The source code of application file is as follows
package personal;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class PersonalApplication {
public static void main(String[] args) {
SpringApplication.run(PersonalApplication.class, args);
}
}
Application.properties file
spring.datasource.url=jdbc:mysql://localhost:3306/personal
spring.datasource.username=abc
spring.datasource.password=abc
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
Model
#imports
#Entity()
#Table(name="Registration_Table")
public class RegistrationModel {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int personId;
private String personUsername;
private String personPassword;
# getter
# Setter
}
Controller
# Imports
#RestController
#CrossOrigin
public class RegistrationController {
#Autowired
private RegistrationServiceImplementation RegistrationServiceImplementation;
#PostMapping(value = "/save_person", consumes = { MediaType.APPLICATION_JSON_VALUE,
MediaType.MULTIPART_FORM_DATA_VALUE })
public String saveperson(#RequestParam("personUsername") String personUsername,
#RequestParam("personPassword") String personPassword)throws IOException {
this.RegistrationServiceImplementation.savepersonprofile(personUsername, personPassword);
return "Status Ok! Data Successfully saved!";
}
}
Service
#Service
public class RegistrationService implements RegistrationServiceImplementation{
#Autowired
private RegistrationDAO registrationDao;
#Override
public void savepersonprofile(String personUsername, String personPassword) {
RegistrationModel registration = new RegistrationModel();
registration.setPersonUsername(personUsername);
registration.setPersonPassword(personPassword);
registrationDao.save(registration);
}
}
DAO
package personaldao;
import org.springframework.data.jpa.repository.JpaRepository;
import personalmodels.RegistrationModel;
public interface RegistrationDAO extends JpaRepository<RegistrationModel, Integer>{
}
ServiceImplementation
package personalservices;
public interface RegistrationServiceImplementation {
public void savepersonprofile(String personUsername, String personPassword);
}
Output after run
Please let me know where I am doing the mistake. The program starts successfully. But the table is not being created.

Related

Spring boot: Expected json responses, getting XML responses

I'm running a simple Spring boot application that retrieves details of countries from a MySQL database. The initial responses I got while running the application were in json. However, after a few edits in the application.properties file, I get my reponses in XML now. Any way to revert back to json reponses? This application is a part of a microservice application I'm trying to build with Spring cloud gateway and Eureka server.
application.properties
spring.jpa.hibernate.ddl-auto = update
spring.datasource.url= jdbc:mysql://localhost:3306/countries-microservice
spring.datasource.username= root
spring.datasource.password=
spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
spring.application.name=countries-service
server.port=3001
eureka.client.serviceUrl.defaultZone=http://localhost:3000/eureka/
CountryRepository.java
package com.example.countriesservice.repository;
import com.example.countriesservice.model.Country;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface CountryRepository extends JpaRepository<Country, String> {
Country findByCountry(String country);
}
CountryService.java
package com.example.countriesservice.service;
import java.util.List;
import com.example.countriesservice.model.Country;
import com.example.countriesservice.repository.CountryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class CountryService {
private final CountryRepository countryRepository;
#Autowired
public CountryService(CountryRepository countryRepository) {
this.countryRepository = countryRepository;
}
public List<Country> getAllCountries() {
return countryRepository.findAll();
}
public Country getCountry(String country) {
return countryRepository.findByCountry(country);
}
}
CountryController.java
package com.example.countriesservice.controller;
import com.example.countriesservice.service.CountryService;
import java.util.List;
import com.example.countriesservice.model.Country;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
#RequestMapping("/countries")
#RestController
public class CountryController {
private final CountryService countryService;
#Autowired
public CountryController(CountryService countryService) {
this.countryService = countryService;
}
#GetMapping("/getAll")
public List<Country> getAll() {
return countryService.getAllCountries();
}
#GetMapping("/{country}")
public Country getCountry(#PathVariable String country) {
return countryService.getCountry(country);
}
}
Output
Since I am still learning Spring Boot it would be great if you could explain what am I doing wrong and how to correct it in a bit detail.
Explicitly mention that a json response is required.
In CountryController.java
import org.springframework.http.MediaType;
#GetMapping(value = "/getAll", produces = { MediaType.APPLICATION_JSON_VALUE })
public List<Country> getAll() {
return countryService.getAllCountries();
}
#GetMapping(value = "/{country}", produces = { MediaType.APPLICATION_JSON_VALUE })
public Country getCountry(#PathVariable String country) {
return countryService.getCountry(country);
}

Decorating a Bean with both Lombok and Spring annotations

Given the following classes in the same package:
CarOne:
import org.springframework.stereotype.Component;
#Component
public class CarOne {
private String name;
public CarOne() {
System.out.println("Car One instantiated");
}
public String getName() {
return name = "Toyota";
}
}
CarTwo:
import lombok.Data;
import org.springframework.stereotype.Component;
#Component
#Data
public class CarTwo {
public CarTwo() {
System.out.println("Car Two instantiated");
}
private String name = "Ford";
}
And the following test:
#SpringBootTest
public class CarTest {
#Autowired
private CarOne carOne;
#Autowired
private CarTwo carTwo;
#Test
void getCarOneName(){
System.out.println(carOne.getName());
}
#Test
void getCarTwoName(){
System.out.println(carTwo.getName());
}
}
...the second test throws a compilation error in IntelliJ: java: cannot find symbol, symbol: method getName()
I am just starting out learning Spring Boot. I have lots of classes where I'm using Lombok who's data I want to wire up using Spring Boot - it's probably obvious, but where am I going wrong?

I cant #Autowired a DatastoreRepository bean (Goolge cloud datastore)

I'm trying to create a bean of the DatastoreRepository class but I get the following error Iam using spring-boot 2.1.3
Description:
The bean 'bookRepository', defined in null, could not be registered. A bean with that name has already been defined in null and overriding is disabled.
Action:
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
this is my project structure I have the Application main run class in a root package like this
com.mycompany.project
--Application.java
--controller
--domain
--repository
The class with the #SpringBootApplication is in the root package
here is my repository class
import org.springframework.cloud.gcp.data.datastore.repository.DatastoreRepository;
public interface BookRepository extends DatastoreRepository<Book, Long>{
}
Here is my domain class
import org.springframework.cloud.gcp.data.datastore.core.mapping.Entity;
import org.springframework.data.annotation.Id;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Entity(name = "books")
#Data
#NoArgsConstructor
#AllArgsConstructor
public class Book {
#Id
Long id;
String title;
}
and here is my controller class
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class AppUserController {
#Autowired
BookRepository bookRepository;
#GetMapping("/booksave")
public String helloworld() {
bookRepository.save(new Book(3L, "author"));
return "book saved";
}
}
and here is my Application class
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
I think the problem is the way you are using the annotation, try changing the Injection to the Constructor, something like:
#RestController
public class AppUserController {
private BookRepository bookRepository;
#Autowired
public AppUserController (
BookRepository bookRepository){
this.bookRepository= bookRepository;
}
#GetMapping("/booksave")
public String helloworld() {
bookRepository.save(new Book(3L, "author"));
return "book saved";
}
}
Source to understand it: Spring #Autowire on Properties vs Constructor
Add this annotation, #EnableDatastoreRepositories, to your Application.java
How about using Spring data rest :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
you won't need to code controllers
import org.springframework.cloud.gcp.data.datastore.repository.DatastoreRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
#RepositoryRestResource(collectionResourceRel = "xxxxxs", path = "xxxx")
public interface XXXXXRepository extends DatastoreRepository<XXXXX, String>
swagger config !!!
#Configuration
#EnableSwagger2WebMvc
#Import(SpringDataRestConfiguration.class)
public class SwaggerConfig {

How to convert data into json format by using spring rest api in eclipse

I am new to spring rest api so i need to convert data into json format by using spring rest api can i any one tell me how to do this and give me the protype how to proceed this one...
You can use #RestController or #ReponseBody annotation.
Official Tutorial is here.And the code snippet is like
#RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/greeting")
public Greeting greeting(#RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
#RestController annotation can be used when all the controller handler should return a JSON string.However if your need is that some method may return JSON string,just use #ResponseBody above that method.And return a Object.The Spring framework will do the serialize work for you.The code snippet is like:
#Controller
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/greeting")
#ResponseBody
public Greeting greeting(#RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
you can use the jackson library
Jackson library
Use #ResponseBody annotation on your method which is returning data...Also if you can show the code it will be more helpful
Spring boot uses Jackson to deserialize JSON into Java instances and serialize Java objects back to JSON payloads. You may check the sample project written by me here [1]. Literally you don't need to manipulate any JSON. You work using Java Objects. Let Jackson take care of the transformation between Java Objects and JSON payloads. You just need to follow up few rules. For an example your Java class should have same field names as JSON payload and compatible data types, then Jackson will bind them on your behalf. Hope this helps. Happy Coding.
[1] https://github.com/ravindraranwala/SpringBootRxJava/
In addition to CALTyang answer , we can also use ResponseEntity to return the response.
code snippet :
#RestController
public class PersonController {
#Autowired
private PersonRepository personRepository;
#RequestMapping(value = "/persons/{id}", method = RequestMethod.GET,produces={MediaType.APPLICATION_XML_VALUE},headers = "Accept=application/xml")
public ResponseEntity<?> getPersonDetails(#PathVariable Long id, final HttpServletRequest request)throws Exception {
ConnectionManager cm=new ConnectionManager();
Person personResponse=cm.getDetails();
return ResponseEntity.ok(personResponse);
}
}
#user7271107 - here is sample prototype code and response format.I am fetching the data from DB.
=====================================================
Response
{
"records":
[
{
"hr": 1,
"km": 20
},
{
"hr": 2,
"km": 23
},
{
"hr": 3,
"km": 29
},
{
"hr": 4,
"km": 50
},
{
"hr": 5,
"km": 55
},
{
"hr": 6,
"km": 60
}
]
}
package com.subu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
#SpringBootApplication
#Configuration
#ComponentScan
#EnableAutoConfiguration
#EnableScheduling
public class Application extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
private static Class<Application> applicationClass = Application.class;
}
#RestController
public class PersonController {
#Autowired
private RecordRepository recordRepository;
#RequestMapping(value = "/records/", method = RequestMethod.GET,produces={MediaType.APPLICATION_JSON_VALUE},headers = "Accept=application/json")
public ResponseEntity<?> getRecords(final HttpServletRequest request)throws Exception {
DBRecordArray dr= new DBRecordArray();
List<DBRecord> list=recordRepository.findAll();
dr.setRecords(list);
return ResponseEntity.ok(dr);
}
}
package com.subu;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="record")
public class DBRecord implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
private Long id;
private int hr;
private int km;
public int getHr() {
return hr;
}
public void setHr(int hr) {
this.hr = hr;
}
public int getKm() {
return km;
}
public void setKm(int km) {
this.km = km;
}
}
package com.subu;
import java.util.List;
public class DBRecordArray {
private List<DBRecord> records;
public List<DBRecord> getRecords() {
return records;
}
public void setRecords(List<DBRecord> records) {
this.records = records;
}
}
package com.subu;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface RecordRepository extends JpaRepository<DBRecord, Long> {
List<DBRecord> findAll();
}

Nullpointer when using #Autowire

I want to create a DAO object by dependency injection (#Autowire) but unfortunately, this DAO object is never created and hence a Nullpointer exception is thrown.
This is my DAO implementation:
package com.sample.dao.service;
#Component
public class OrderServiceImpl implements OrderService {
private final OrderRepository orderRepository;
#Autowired
OrderServiceImpl(OrderRepository orderRepository) {
this.orderRepository = orderRepository;
}
#Override
public void save(Order order) {
return orderRepository.save(order);
}
The class where the Nullpointer exception is caused:
package com.sample.dispatcher;
#Component
public class OrderDispatcher {
private final OrderServiceImpl orderServiceImpl;
#Autowired
public OrderDispatcher(OrderServiceImpl orderServiceImpl) {
this.orderServiceImpl = orderServiceImpl;
}
public void createOrder(Order order) {
orderServiceImpl.save(order)); // --> Nullpointer
My entry class:
package com.sample;
#SpringBootApplication
#ComponentScan(basePackages = { "com.sample" , "com.webservice"})
#EnableJpaRepositories(basePackages = "com.sample.dao.repository")
public class Application {
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
I think you should change your constructor to have an argument type of interface rather than a concrete implementation. So something like this -
#Component
public class OrderDispatcher {
private final OrderService orderServiceImpl;
#Autowired
public OrderDispatcher(OrderService orderServiceImpl) {
this.orderServiceImpl = orderServiceImpl;
}
When you add the #component notation on OrderServiceImpl, Spring creates proxy for that class and it can be autowired by interface.
Maybe you forgot the #annotation configuration. Try adding this class and also you scan your entities: EntityScan
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#Configuration
#EntityScan("com.sample.model") // Your model package
#ComponentScan(basePackages = { "com.sample" , "com.webservice"})
#EnableJpaRepositories(basePackages = "com.sample.dao.repository")
public class RepositoryConfig {
}

Categories

Resources