I am using Spring Boot and the #NotNull is not working. When the name value is not provided the function runs fine.
#Entity
public class Employee implements Serializable{
#Id
//#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
//#Id
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#NotNull // not working
private String name;
private String phone;
}
the controller is
#Controller
public class URLController {
#Autowired
EmployeeServiceImpl empService;
#GetMapping({"/", "/index"})
public String index1(Model model){
model.addAttribute("employee",new Employee());
return "index";
}
#PostMapping("/result")
public String result(#Valid #ModelAttribute Employee employee){
System.out.print(employee.getName());
empService.save(employee);
return "result";
}
}
pom.xml
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>com.springs</groupId>
<artifactId>springs</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springs</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
i am using the model attribute to get the employee object. the pom.xml file contains the hibernate validator dependency.
you must add #Valid annotaion in mapping part in your code for example
void addEmployee(#Valid Employee emp);
using this import "import javax.validation.Valid;"
Another note if you want to validate List you must make a wrapper list
Like
public class ValidList<E> implements List<E> {
#Valid
private List<E> list;}
And override all methods in it
Try modifying method like below to check details about errors.
#PostMapping("/result")
public String result(#Valid #ModelAttribute("employee") Employee employee, BindingResult bindingResult){
List<FieldError> errors = bindingResult.getFieldErrors();
for (FieldError error : errors ) {
System.out.println (error.getObjectName() + " - " +error.getDefaultMessage());
}
System.out.print(employee.getName());
empService.save(employee);
return "result";
}
If no error in bindingResult then refer notnull-constraint-not-working to troubleshoot further.
Related
I am newbie coder and I am trying to create a Spring boot API using MongoDB. This is the schema template of the database.
{
"id":"string",
"user_name":"string"
"product":[
{
"product_id":"string",
"prod_name":"string",
"price":"double",
"quantity":"number",
}],
"total":"double"
}
This is my entity class User.java
#Getter
#Setter
#NoArgsConstructor
#Document(collection="user")
public class User {
#Id
private String id;
#Indexed(unique=true)
private String user_name;
private Product product;
private double total;
}
This is another entity class Product.java
#Getter
#Setter
#Document(collection="product")
public class Product {
#Id
private String prod_id;
#Indexed(unique=true)
private String prod_name;
private double price;
private int quantity;
}
This is my UserRepository.java interface
#Repository
public interface UserRepository extends MongoRepository<User,String> {
}
This is my UserService.java interface
public interface UserService {
void saveUser(User user);
}
This is my UserServiceImpl.java class
#Service
public class UserServiceImpl implements UserService {
#Autowired
UserRepository userRepo;
#Override
public void saveUser(User user) {
userRepo.save(user);
}
}
This is my UserController.java class
#RestController
#RequestMapping("/usercart")
public class UserController {
#Autowired
private UserService userService;
#Autowired
private UserRepository userRepository;
#GetMapping("/")
public List<User> getCartInfo()
{
return userRepository.findAll();
}
#PostMapping("/order")
public ResponseEntity<?> add(#RequestBody User user)
{
userService.saveUser(user);
return new ResponseEntity<>(HttpStatus.OK);
}
}
This is my 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.6.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.demo</groupId>
<artifactId>cartDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>cartDemo</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-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</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.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
This is my application.properties file
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=UserCart
When I try to use post method like
Body -
{ "id":"1222",
"user_name":"shivam",
"product":[{
"prod_id":"w121", "prod_name":"wheel",
"price":10,
"quantity":1 }],
"total":10 }.
My MongoDB object looks like - _id:ObjectId("e6789")
total :0, _class:"com.trial.spring.api.user.User"
I don't see your property file here, but most likely you are missing below properties in your application.properties file:
spring.data.mongodb.uri=mongodb://<username>:<pwd>#<host>/datatbase_name
This is my first program on REST API using jersey. My rest API is giving me an Error code 500 when I try to get the response back in XML but it is working fine for JSON.
Can someone tell me what I am doing wrong?
There is no error shown in the console.
public class MyResource {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getIt() {
return "Got it!";
}
#GET
#Produces(MediaType.APPLICATION_XML)
#Path("/cust")
public Customer getCust() {
Customer cus= new Customer();
cus.setName("john");
cus.setId(1);
cus.setAddress("india");
return cus;
}
#GET
#Path("/test/order")
#Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public Order getOrder() {
List<Order> o =new ArrayList<Order>();
Order ord=new Order();
ord.setCost(0);
ord.setProductID(0);
ord.setQuantity(0);
ord.setShippingAddress("abcd");
o.add(ord);
return ord;
}
}
My customer class
package in.octalian.mobileservice.model;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Customer {
private int id;
private String name ;
private String address;
public Customer() {}
public Customer(int id,String name,String address) {
this.id=id;
this.name=name;
this.address=address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
my 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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>in.octalian</groupId>
<artifactId>mobileservice</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>mobileservice</name>
<build>
<finalName>mobileservice</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<inherited>true</inherited>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
<!-- uncomment this to get JSON support -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-binding</artifactId>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
<properties>
<jersey.version>2.27</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
XML response that I attach to give more information to you.
The issue is that you are trying to access a URI /cus but your code have a declaration as #Path("/cust"). So you should be using /cust.
Secondly, you could run your server(apache-tomcat for me) in debug mode to get debugging information if no logs are getting logged in the console for some error
Also, you need to add the header "Accept" in the request with the expected result format type. If not specified the first one will be considered as it appears first.
I'm trying to generate table using JPA. but i can't create it. There is no error in the code, but it seems that there is configuration error. but i can't find it, i tried many configurations but nothing happen.
Thanks a lot.
This is application.property:
spring.datasource.url=jdbc:mysql://localhost:3306/springapp
spring.datasource.username= root
spring.datasource.password= me
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create
this is my class:
#Entity
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
private String phone;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Customer(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}
public Customer() {
super();
}
}
This is the application:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
And this is the controller:
#RestController
#RequestMapping("/customer")
public class CustomerController {
#Autowired
CustomerRepository customerRepository;
#RequestMapping("/findall")
#ResponseBody
public List<Customer> findAll() {
return customerRepository.findAll();
}
}
Pom.xml
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>GStock-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>GStock-3</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</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>
Try to add #EntityScan
#EntityScan("<package with entities>")
#SpringBootApplication
public class Application { ... }
With the current information I have a couple of suggestions / Questions that might help you allong:
Does the "springapp" database exist with the correct user (root) and password (me) assigned to it in MySQL
Has MySQL been started?
I see no #Repository definition in your code e.g.
#Repository
public interface CustomerRepository extends JpaRepository{}
execute following on your mysql:
mysql> create database db_example; -- Create the new database
mysql> create user 'springuser'#'localhost' identified by 'ThePassword'; -- Creates the user
mysql> grant all on db_example.* to 'springuser'#'localhost'; -- Gives all the privileges to the new user on the newly created database
and add into application.xml:
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
OR
you can go through this link
I am writing a web app with Spring Boot, Hibernate and PostgreSQL. I want to learn how to save things in DB, but now I can`t resolve my problem. I am getting an error caused by my controller by line:
silniaRepository.save(silniaDB);
error is just:
java.lang.NullPointerException
there is my pom:
<name>silnia</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</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.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>8.1.5.v20120716</version>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
part of my controller:
#Controller
public class SilniaController {
#Autowired
public SilniaService silniaService;
public SilniaRepository silniaRepository;
public SilniaDB silniaDB;
#RequestMapping("/db")
#ResponseBody
public String testMethod() {
StringBuilder response = new StringBuilder();
SilniaDB silniaDB = new SilniaDB()
.setNumber1(23);
silniaRepository.save(silniaDB);
for (SilniaDB i : silniaRepository.findAll()) {
response.append(i).append("<br>");
}
return response.toString();
}
my DB model:
#Entity
public class SilniaDB {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column
private int number;
public int getNumber() {
return number;
}
public void setNumber (int number){this.number=number;}
public SilniaDB setNumber1(int number) {
this.number = number;
return this;
}
public SilniaDB withNumber(final int number) {
this.number = number;
return this;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public String toString() {
return "TaskEntity{" +
"id=" + id +
"number=" + number +
'}';
}
}
and typical repository interface:
#Repository
public interface SilniaRepository extends CrudRepository<SilniaDB, Long> {
public SilniaDB findByNumber(Integer number);
}
I really spent a lot of time on that issue. Thanks in advance for every comment or answer.
Your repository is simply not being injected.
You have to put #Autowired for each of the dependencies individauly.
#Autowired
private SilniaService silniaService;
#Autowired
private SilniaRepository silniaRepository;
also make those fields as private..
I am trying to generate schema tables based on entities. The application starts correctly, the SQL is generated but there is no result - none of tables are created. What's wrong? I have used the same settings in plain Spring MVC + Hibernate JPA without Spring Boot and everything was working correctly.
Here is my 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.agileplayers</groupId>
<artifactId>applicationname</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>ApplicationName</name>
<description>Application Name</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<!--<scope>runtime</scope>-->
<version>9.4-1201-jdbc41</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:postgresql://localhost:5432/postgres
spring.datasource.driverClassName = org.postgresql.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQL82Dialect
spring.datasource.schema=schemaName
spring.datasource.username=userName
spring.datasource.password=userPassword
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
BaseEntity.java:
package com.agileplayers.applicationname.core.domain;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.util.Date;
#MappedSuperclass
public class BaseEntity {
#Id
#GeneratedValue
private int id;
private Date createdOn;
public String description;
public BaseEntity() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
example of Entity which extends BaseEntity - Entry.java:
package com.agileplayers.applicationname.core.domain;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import java.util.Date;
#Entity
public class Entry extends BaseEntity{
private String type;
#ManyToOne
private Account account;
public Entry() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
}
I have fixed the issue. Instead of spring.datasource.schema=schemaName there should be spring.jpa.properties.hibernate.default_schema=schemaName.
The set of necessary properties required for generating tables in my case is the following:
spring.datasource.url = jdbc:postgresql://localhost:5432/postgres
spring.jpa.properties.hibernate.default_schema = schemaName
spring.datasource.username = userName
spring.datasource.password = userPassword
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.show-sql = true