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..
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
I try to create a website with spring. But when I try to coonect my project with my database and to work with it throw spring I get errors.I run mysql server only. I 100% know that port, password and username are right. What am I doing wrong?
run mysql server
sudo /etc/init.d/mysql start
like this
application.propeties:
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/java_spring_blog
spring.datasource.username=root
spring.datasource.password=root
dependcies:
<?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.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.coursework</groupId>
<artifactId>CourseWork</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>CourseWork</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-thymeleaf</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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</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>
<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>
Model:
package com.coursework.CourseWork.Models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Post {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title, anons, fulltext;
private int views;
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 getAnons() {
return anons;
}
public void setAnons(String anons) {
this.anons = anons;
}
public String getFulltext() {
return fulltext;
}
public void setFulltext(String fulltext) {
this.fulltext = fulltext;
}
public int getViews() {
return views;
}
public void setViews(int views) {
this.views = views;
}
}
When I try to run programm I got an exeption:java.sql.SQLException: Access denied for user 'root'#'localhost'
And another one:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
I think it's because due to thirst one.
It works when I create a new user. Thanks to Ankit
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.
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 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