HsqlDB with spring-boot-starter-parent 1.4.0.RELEASE - java

This the pom.xml for maven build project that I am using to resolve dependencies.
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>
<groupId>com.raj</groupId>
<artifactId>hSQLdb1</artifactId>
<version>0.1.0</version>
<properties>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</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>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>build-info</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Below are the properties file for my sample application here I am using applicationproperties and application-hsqldb.properties
application.properties
spring.profiles.active=hsqldb
# Hibernate
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.properties.jadira.usertype.autoRegisterUserTypes=true
**application-hsqldb.properties**
# Hibernate
spring.jpa.hibernate.ddl-auto=validate
# Initialization
spring.datasource.schema=classpath:/data/hsqldb/schema.sql
spring.datasource.data=classpath:/data/hsqldb/data.sql
data.sql
INSERT INTO EMP(f_name, l_name) VALUES('Rajendar','Kumar');
INSERT INTO EMP(f_name, l_name) VALUES('Ramesh','Kumar');
schema.sql
DROP TABLE EMP IF EXISTS;
CREATE TABLE emp (
id BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1) NOT NULL,
f_name VARCHAR(100) NOT NULL,
l_name VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
);
Below is the controller for my rest services that have two service for greeting and read data from database
import com.raj.hSQLdb.pojo.Employee;
import com.raj.hSQLdb.pojo.Greating;
import com.raj.hSQLdb.service.impl.ProcessEmpDataService;
#RestController
#RequestMapping("/app")
public class Controller{
#Autowired
private ProcessEmpDataService empDataService;
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#GetMapping("/greeting")
public String sayHello(#RequestParam(value="name", defaultValue="Rajendar") String name) {
return new Greating(String.valueOf(counter.incrementAndGet()), String.format(template, name)).toString();
}
#RequestMapping(value = {"/read"}, method = RequestMethod.GET)
public ResponseEntity<?> read(Long id) {
Employee response = empDataService.findOne(id);
return new ResponseEntity<Employee>(response,HttpStatus.OK);
}
}
Entity
package com.raj.hSQLdb.pojo;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="emp")
public class Employee implements Serializable{
private static final long serialVersionUID = 5667869092245806231L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Column(name = "f_name")
private String firstName;
#Column(name = "l_name")
private String lastName;
public Long getId() {
return id;
}
public void setId(Long 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;
}
#Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
** Greating **
package com.raj.hSQLdb.pojo;
public class Greating{
public Greating(String code, String message) {
this.code=code;
this.message=message;
}
protected String code;
private String message;
public String getCode() {
return code;
}
public String getMessage() {
return message;
}
}
Repository
package com.raj.hSQLdb.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.raj.hSQLdb.pojo.Employee;
#Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
}
Service
package com.raj.hSQLdb.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.raj.hSQLdb.pojo.Employee;
import com.raj.hSQLdb.repository.EmployeeRepository;
#Component
public class ProcessEmpDataService {
#Autowired
private EmployeeRepository repository;
public Employee findOne(Long id) {
Employee emp = repository.findOne(id);
return emp;
}
}
main class to run the application
package com.raj.hSQLdb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#SpringBootApplication
#EnableTransactionManagement
public class ServletInitializer {
/**
* #param args
*/
public static void main(String[] args) {
SpringApplication.run(ServletInitializer.class, args);
}
}

Related

Running mvn clean install deletes data in the database

I'm fairly new at maven spring boot.
I'm running mvn clean install then mvn spring-boot:run
I'm then able to go an http post and insert data into the database. I can do an http get and see the data. I can view the data in mysql.
When I re-compile and run mvn clean install again, I'm not sure what's making it delete all the data in my product table in the database.
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 https://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.7.0</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
<groupId>sample.info</groupId>
<artifactId>mainapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mainapp</name>
<description>Spring Boot Project</description>
<properties>
<java.version>18</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<forkCount>0</forkCount>
<reuseForks>true</reuseForks>
<argLine>-Xmx1024m -XX:MaxPermSize=256m</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>
application.properties
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/appdb
spring.datasource.username=root
spring.datasource.password=
server.port = 9095
MainappApplication.java
package sample.info.mainapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
#EnableJpaAuditing
#SpringBootApplication
public class MainappApplication {
public static void main(String[] args) {
SpringApplication.run(MainappApplication.class, args);
}
}
controllers/ProductController.java
package sample.info.mainapp.controllers;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sample.info.mainapp.model.Product;
import sample.info.mainapp.repository.ProductRepository;
#RestController
#RequestMapping("/api")
public class ProductController {
#Autowired
ProductRepository productRepository;
#GetMapping("/products")
public List<Product> getAllProducts() {
final List<Product> productList = new ArrayList<Product>();
Iterable<Product> iterable = productRepository.findAll();
iterable.forEach(productList::add);
return productList;
}
#GetMapping("/products/{id}")
public ResponseEntity<Product> getProductById(#PathVariable(value = "id") Long id) {
Optional<Product> product = productRepository.findById(id);
return product.isPresent() ? new ResponseEntity<Product>(product.get(), HttpStatus.OK)
: new ResponseEntity("No data found", HttpStatus.NOT_FOUND);
}
#PostMapping("/products")
public Product createProduct(#RequestBody Product product) {
return productRepository.save(product);
}
#PutMapping("/products/{id}")
public ResponseEntity<Product> updateProduct(#PathVariable(value = "id") Long id, #RequestBody Product newProduct) {
Optional<Product> product = productRepository.findById(id);
if (product.isPresent()) {
Product prod = product.get();
prod.setDescription(newProduct.getDescription());
prod.setPrice(newProduct.getPrice());
prod.setTitle(newProduct.getTitle());
prod = productRepository.save(prod);
return ResponseEntity.ok().body(prod);
} else {
return ResponseEntity.notFound().build();
}
}
#DeleteMapping("/products/{id}")
public ResponseEntity<Product> deleteProduct(#PathVariable(value = "id") Long id) {
Optional<Product> product = productRepository.findById(id);
if (product.isPresent()) {
productRepository.delete(product.get());
return new ResponseEntity("Product has been deleted successfully.", HttpStatus.OK);
} else {
return ResponseEntity.notFound().build();
}
}
}
model/Product.java
package sample.info.mainapp.model;
import javax.persistence.*;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.Date;
#Entity
#Table(name = "products")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = { "created_at", "updated_at" }, allowGetters = true)
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "title")
private String title;
#Column(name = "description")
private String description;
#Column(name = "price")
private float price;
#Column(nullable = false, updatable = false)
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
private Date created_at;
#Column(nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#LastModifiedDate
private Date updated_at;
public Product() {
}
public Product(Long id, String title, String description, float price) {
this.id = id;
this.title = title;
this.description = description;
this.price = price;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Date getCreated_at() {
return created_at;
}
public Date getUpdated_at() {
return updated_at;
}
}
repository/ProductRepository.java
package sample.info.mainapp.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import sample.info.mainapp.model.Product;
#Repository
public interface ProductRepository extends CrudRepository <Product, Long> {
}
spring.jpa.hibernate.ddl-auto = create -– Hibernate first drops existing tables, then creates new tables. Click here for more details.
Remove / comment this property from application.properties and try.

Error 404 Not Found. Why is my RestController not recognized from Spring Boot Application?

I have the following problem. I have a simple Spring Boot Application that is supposed to process the debts of users. The service does compile, but neither a PostRequest to insert a new record nor a GetRequest to display the debt of a user works. When the service is started, the application automatically creates the appropriate table for the entity. Therefore I assume that the database connection will not be the problem. It looks like my service does not recognize the RestController. With Postman I keep getting the error code "404 Not Found".
Does anyone have any idea what I am doing wrong?
My Entity
package Entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
#Entity
#Table(name= "debts")
#EnableAutoConfiguration
public class DebtsEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name = "user_id")
private String userId;
#Column(name = "invoice_id")
private int invoiceId ;
#Column(name = "creditor")
private String creditor;
#Column(name = "amount")
private double amount;
#Column(name = "deadline")
private String deadline;
#Column(name = "installment")
private double installment;
public DebtsEntity(){
}
public DebtsEntity(int id, String userId, int invoiceId, String creditor, double amount, String deadline,
double installment) {
super();
this.id = id;
this.userId = userId;
this.invoiceId = invoiceId;
this.creditor = creditor;
this.amount = amount;
this.deadline = deadline;
this.installment = installment;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public int getInvoiceId() {
return invoiceId;
}
public void setInvoiceId(int invoiceId) {
this.invoiceId = invoiceId;
}
public String getCreditor() {
return creditor;
}
public void setCreditor(String creditor) {
this.creditor = creditor;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public String getDeadline() {
return deadline;
}
public void setDeadline(String deadline) {
this.deadline = deadline;
}
public double getInstallment() {
return installment;
}
public void setInstallment(double installment) {
this.installment = installment;
}
#Override
public String toString() {
return "debtsEntity [id=" + id + ", userId=" + userId + ", invoiceId=" + invoiceId + ", creditor=" + creditor
+ ", amount=" + amount + ", deadline=" + deadline + ", installment=" + installment + "]";
}
}
My RestController
package Controller;
import java.net.URI;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import DAO.DebtsDAO;
import Entity.DebtsEntity;
#RestController
public class DebtsController {
#Autowired
DebtsDAO debtsDAO;
#GetMapping("/{userId}/debts")
public List<DebtsEntity> retrieveDebtsByUserId(#PathVariable String userId)
{
List<DebtsEntity> debts = debtsDAO.findByUserId(userId);
return debts;
}
#PostMapping("/debts")
public ResponseEntity<Object> createInvoice(#RequestBody DebtsEntity debtsEntity)
{
DebtsEntity savedUser =debtsDAO.save(debtsEntity);
URI location= ServletUriComponentsBuilder.fromCurrentRequest()
.path("path/{id}")
.buildAndExpand(savedUser.getId()).toUri();
return ResponseEntity.created(location).build();
}
}
My DAO
package DAO;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import Entity.DebtsEntity;
#Component
public interface DebtsDAO extends JpaRepository<DebtsEntity, Integer>{
List<DebtsEntity> findByUserId(String user_id);
}
My application.properties
## Database konfiguration
spring.datasource.url=jdbc:postgresql://localhost:5432/Test
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.hibernate.ddl-auto=create
# define if Database Queries should be written in logfile
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.default_schema=public
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL81Dialect
server.port=8000
spring.application.name=Debts
My dependencies
<?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 https://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.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>LifeOps</groupId>
<artifactId>Service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Service</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
UPDATE 1
Get-Request
URL: http://localhost:8000/1000/depts
PostRequest
URL: http://localhost:8000/depts
RequestBody:
{
"id":1000,
"user_id": "ABC1234",
"invoice_id":100001,
"creator": "A12L",
"amount": 123012.56,
"deadline": "20.10.12",
"installment": 50.00
}
package Service;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
#EntityScan(basePackages = "entity")
#SpringBootApplication
public class ServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class, args);
}
}
UPDATE 2
Class package
DebtsApplication service.debts
DebtsController service.debts.controller
DebtsEntity service.debts.entity
DebtsDAO service.debts.dao
I would suggest you add a base package (something like "com.doncarlito") and put ServiceApplication in it.
package com.doncarlito;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
#EntityScan(basePackages = "entity")
#SpringBootApplication
public class ServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class, args);
}
}
Then move all the other existent packages to be sub-packages of this one:
com.doncarlito.entity
com.doncarlito.dao
com.doncarlito.controller
com.doncarlito.service
The reason being that #SpringBootApplication encapsulates #Configuration, #EnableAutoConfiguration, and #ComponentScan annotations with their default attributes. The default value for #ComponentScan means that all the sub-packages on the package the #ComponentScan is used are scanned. That is why it is usually a good practice to include the main class in the base package of the project.
You are running your app from x.y.z.ApplicationService but your components are in different pacage like x.y.a.YourComponent which will NOT be picked up by the spring.
By default, spring scans package (and descendants) of your #SpringApplication class. In reference to the above it would be x.y.z.*.....
To solve your problem (alternatives)
Move your ApplicationService next to DebtsApplication so it will be "on top" of all required components (#RestController for example)
Add #ComponentScan(basePackgages={'service.debts'})
to ApplicationService so you will "manually" show spring where to look for components.
There are other ways, but you should be fine with those 2

Why hibernate doesn't create tables automatically?

I am trying to do a project in Angular but I noticed that the table is not created automatically. I put the structure of the project and the related code to do this.
As you can see in mysql, the users_database database is created with the statement "create database", but the employee table is not created.
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 https://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.4.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>net.guides.springboot2</groupId>
<artifactId>springboot2-jpa-crud-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Student_Angular-1</name>
<description>Rest API for a Simple Employee Management Application</description>
<properties>
<java.version>11</java.version>
</properties>
<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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
spring.datasource.url = jdbc:mysql://localhost:3306/users_database?useSSL=false
spring.datasource.username = root
spring.datasource.password = root
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
server.servlet.context-path=/springboot-crud-rest
Employee.java
package net.guides.springboot2.springboot2jpacrudexample.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "employees")
public class Employee {
private long id;
private String firstName;
private String lastName;
private String emailId;
public Employee() {
}
public Employee(String firstName, String lastName, String emailId) {
this.firstName = firstName;
this.lastName = lastName;
this.emailId = emailId;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Column(name = "first_name", nullable = false)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "last_name", nullable = false)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "email_address", nullable = false)
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
#Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", emailId=" + emailId
+ "]";
}
}
EmployeeRepository.java
package net.guides.springboot2.springboot2jpacrudexample.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.guides.springboot2.springboot2jpacrudexample.model.Employee;
#Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
}
EmployeeController.java
package net.guides.springboot2.springboot2jpacrudexample.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import net.guides.springboot2.springboot2jpacrudexample.exception.ResourceNotFoundException;
import net.guides.springboot2.springboot2jpacrudexample.model.Employee;
import net.guides.springboot2.springboot2jpacrudexample.repository.EmployeeRepository;
#RestController #CrossOrigin(origins = "http://localhost:4200")
#RequestMapping("/api/v1")
public class EmployeeController {
#Autowired
private EmployeeRepository employeeRepository;
#GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employeeRepository.findAll();
}
#GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(#PathVariable(value = "id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
return ResponseEntity.ok().body(employee);
}
#PostMapping("/employees")
public Employee createEmployee(#Valid #RequestBody Employee employee) {
return employeeRepository.save(employee);
}
#PutMapping("/employees/{id}")
public ResponseEntity<Employee> updateEmployee(#PathVariable(value = "id") Long employeeId,
#Valid #RequestBody Employee employeeDetails) throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
employee.setEmailId(employeeDetails.getEmailId());
employee.setLastName(employeeDetails.getLastName());
employee.setFirstName(employeeDetails.getFirstName());
final Employee updatedEmployee = employeeRepository.save(employee);
return ResponseEntity.ok(updatedEmployee);
}
#DeleteMapping("/employees/{id}")
public Map<String, Boolean> deleteEmployee(#PathVariable(value = "id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
employeeRepository.delete(employee);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
}
Try changing your value of hibernate.hbm2ddl.auto to create instead of update
you know it worked for me removing the useSSL=false
spring.datasource.url = jdbc:mysql://localhost:3306/users_database?
spring.datasource.username = root
spring.datasource.password = root
You also need to add the following driver-class-name, platform and generate-dll properties to auto-generate ddl.
Add these properties also.
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.generate-ddl=true

no natively generated identity value

i am new to springframework technology and i am struggling to solve the following error.
the project starts successfully, i get the following error when the postman is executed
can anyone hel me solving the issue.
i guess i have pasted the important classes, i can post the whole code if needed
usercontroller
package com.appsdeveloper.blog.app.ws.controller;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.appsdeveloper.blog.app.ws.service.UserService;
import com.appsdeveloper.blog.app.ws.shared.dto.UserDto;
import com.appsdeveloper.blog.app.ws.ui.model.request.UserDetailsRequestModel;
import com.appsdeveloper.blog.app.ws.ui.model.response.UserRest;
#RestController
#RequestMapping("users")//http://localhost:8586/users
public class UserController{
#Autowired(required=true)//the bracket added from the internet
UserService userService;
//#Autowired
//private UserRepository userRepository;
#PostMapping
public UserRest createUser(#RequestBody UserDetailsRequestModel userDetails){
UserRest returnValue = new UserRest();
UserDto userDto = new UserDto();
BeanUtils.copyProperties(userDetails, userDto);
UserDto createdUser = userService.createUser(userDto);
BeanUtils.copyProperties(createdUser, returnValue);
return returnValue;
}
#DeleteMapping
public String deleteUser(){
return "delete user was called";
}
#GetMapping
public String getUser(){
return "get User was called";
}
#PutMapping
public String updateUser(){
return "update user was called";
}
}
UserEntity
package com.appsdeveloper.blog.app.ws.io.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="users", schema = "photo_app" )//name of table created to store information
public class UserEntity implements Serializable {
private static final long serialVersionUID = 7401188933477397731L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="Id")
private long id;
#Column(name= "userId", nullable = false)
private String userId;
#Column(name = "firstName", nullable = false, length = 50)//the length is important to avoid default size 0f 250 varchar
private String firstName;
#Column(name = "lastName", nullable = false, length = 50)
private String lastname;
#Column(name = "email", length = 50)
private String email;
#Column(name = "password", nullable = false)
private String encryptedPassword;
//#Column(name = "emailVerificationToken", nullable = false)
private String emailVerificationToken;
#Column(name = "emailVerificationStatus", nullable=false)
private Boolean emailVerificationStatus = false;
public long getId() {
return id;
}
public String getUserId() {
return userId;
}
public String getFirstName() {
return firstName;
}
public String getLastname() {
return lastname;
}
public String getEmail() {
return email;
}
public String getEncryptedPassword() {
return encryptedPassword;
}
public String getEmailVerificationToken() {
return emailVerificationToken;
}
public Boolean getEmailVerificationStatus() {
return emailVerificationStatus;
}
///////////////////////////////////////////
public void setId(long id) {
this.id = id;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public void setEmail(String email) {
this.email = email;
}
public void setEncryptedPassword(String encryptedPassword) {
this.encryptedPassword = encryptedPassword;
}
public void setEmailVerificationToken(String emailVerificationToken) {
this.emailVerificationToken = emailVerificationToken;
}
public void setEmailVerificationStatus(boolean emailVerificationStatus) {
this.emailVerificationStatus = emailVerificationStatus;
}
}
application.property
spring.datasource.username=root
spring.datasource.password=
spring.datasource.url=jdbc:mysql://localhost:3306/photo_app
server.port=8586
spring.jpa.hibernate.use-new-id-generator-mappings=false
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 https://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.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.appsdeveloperblog-app-ws</groupId>
<artifactId>mobile-app-ws</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mobile-app-ws</name>
<description>Demo project for Spring Boot</description>
<properties><!--</tiles:insertDefinition>-->
<!-- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>-->
<java.version>1.8</java.version>
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
</properties>
<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>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.0.0.Alpha4</version>
<type>pom</type>
</dependency>
<!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jadira.usertype/usertype.core -->
<dependency>
<groupId>org.jadira.usertype</groupId>
<artifactId>usertype.core</artifactId>
<version>7.0.0.CR1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
error code
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: The database returned no natively generated identity value; nested exception is org.hibernate.HibernateException: The database returned no natively generated identity value] with root cause
org.hibernate.HibernateException: The database returned no natively generated identity value
You have to auto-increment your id column in your database.
Something like this: id INT NOT NULL AUTO_INCREMENT

Spring JPA returns empty array from PostgreSQL

I'm new to using Spring MVC and JPA. I have a Postgresql database in which I create two tables: author and userType.
CREATE TABLE UserType (
idUserType INTEGER NOT NULL,
userType VARCHAR NOT NULL,
CONSTRAINT pkusertype PRIMARY KEY (idUserType)
);
CREATE TABLE Author (
idAuthor INTEGER NOT NULL DEFAULT nextval('author_idauthor_seq'),
lastName VARCHAR NOT NULL,
firstName VARCHAR NOT NULL,
CONSTRAINT pk_author PRIMARY KEY (idAuthor)
);
Then I want to map them to my code in Spring and show them. The issue is that even though I do it in the same way, Author is displayed correctly ([some JSON]) while when I want to see userType I receive an empty array ([]). I have no idea why it's happening and would be grateful for help.
Author Model
package com.shareabook.model;
import javax.persistence.*;
#Entity
#Table(name = "author")
public class Author {
#Id
#GeneratedValue
#Column(name = "idauthor")
private Integer id;
#Column(name = "lastname")
private String lastName;
#Column(name = "firstname")
private String firstName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
UserType model
package com.shareabook.model;
import javax.persistence.*;
#Entity
#Table(name = "UserType ")
public class UserType {
#Id
#GeneratedValue
#Column(name = "idusertype")
private Integer id;
#Column(name = "usertype")
private String userType;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
}
AUTHOR CONTROLLER
package com.shareabook.controller;
import com.shareabook.model.Author;
import com.shareabook.repository.AuthorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
#RequestMapping(value = "/rest/author")
public class AuthorController {
#Autowired
AuthorRepository authorRepository;
#GetMapping(value = "/all")
public List<Author> getAll(){
return authorRepository.findAll();
}
}
USERTYPE CONTROLLER
package com.shareabook.controller;
import com.shareabook.model.UserType;
import com.shareabook.repository.UserTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
#RequestMapping(value = "/rest/usertype")
public class UserTypeController {
#Autowired
UserTypeRepository userTypeRepository;
#GetMapping(value = "/all")
private List<UserType> getAll(){
return userTypeRepository.findAll();
}
}
Author Repository
package com.shareabook.repository;
import com.shareabook.model.Author;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AuthorRepository extends JpaRepository<Author, Integer>{
}
UserType repository
package com.shareabook.repository;
import com.shareabook.model.UserType;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserTypeRepository extends JpaRepository<UserType, Integer>{
}
And the main class
package com.shareabook;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#EnableJpaRepositories(basePackages = "com.shareabook.repository")
#SpringBootApplication
public class ShareabookApplication {
public static void main(String[] args) {
SpringApplication.run(ShareabookApplication.class, args);
}
}
My pom.xml file
<?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>
<groupId>com.shareabook</groupId>
<artifactId>shareabook</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>shareabook</name>
<description>Basic project for application Share A Book</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1201-jdbc4</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>1.5.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.16</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Application.properties
spring.datasource.dbcp2.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/shareabookthesis
spring.datasource.username=postgres
spring.datasource.password=wiktoria2
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
Database name in Postgres should be in the small case and Table name should not be in CamelCase.Table name should be usertype instead of UserType.

Categories