I have a Spring Boot Project with pom.xml like this
<groupId>com.project</groupId>
<artifactId>prj</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>prj</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.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-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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
The Application class is like this
#SpringBootApplication
public class PrjApplication {
public static void main(String[] args) {
SpringApplication.run(HqApplication.class, args);
}
}
And I have a RestController where I am trying to do some CRUD Operations like this
#RestController("/register")
public class RegisterController {
#Autowired
private UserRepository userRepository;
#GetMapping("/user/{id}")
public User getUser(#Valid #RequestBody Long id){
User user = userRepository.getOne(id);
return user;
}
#PostMapping("/new")
public User saveUser(#Valid #RequestBody String name,#Valid #RequestBody String email,#Valid #RequestBody String password,#Valid #RequestBody String phone){
System.out.println("savginv user");
User user = new User();
user.setEmail(email);
user.setPassword(password);
user.setName(name);
user.setPhone(phone);
userRepository.save(user);
return user;
}
}
I have made an Entity class; User like this
#Entity
#Table(name = "tbl_users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String name, email, password, phone;
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
When I try to save a user by calling the post method using PostMan it gives me 404 not found error.
{
"timestamp": "2018-06-23T06:47:14.086+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/prj/register/new"
}
I am using JPARepository to perform Database operations.
/prj isn't part of your controller. Either use a POST request without it (i.e., /register/new), or add it to your controller's mapping:
#RestController("/prj/register")
public class RegisterController {
// rest of the code (no pun intended)
Related
During the walkthrough I have added the specified model, controller and repo. I have added all the required dependencies through spring boot (I beleive) as well as creating the DB through the MySql shell.
The db is the same as the example as well as the basic root user until I can get this to work then will add another user.
Any help would be appreciated as I have had this same issue every single time I have tried to set up a db.
My model
package com.avorion.dndwiki.Model;
import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id;
#Entity // This tells Hibernate to make a table out of this class public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO) private Integer id;
private String name;
private String email;
public Integer getId() { return id;
}
public void setId(Integer id) { this.id = id;
}
public String getName() { return name;
}
public void setName(String name) { this.name = name;
}
public String getEmail() { return email;
}
public void setEmail(String email) { this.email = email;
} }
My Controller
package com.avorion.dndwiki.Controller;
import com.avorion.dndwiki.Model.User; import com.avorion.dndwiki.Repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody;
#Controller // This means that this class is a Controller #RequestMapping(path="/demo") // This means URL's start with /demo (after Application path) public class MainController {
#Autowired // This means to get the bean called userRepository Which is auto-generated by Spring, we will use it to handle the data private UserRepository userRepository;
#PostMapping(path="/add") // Map ONLY POST Requests public #ResponseBody String addNewUser (#RequestParam String name
, #RequestParam String email) {
// #ResponseBody means the returned String is the response, not a view name
// #RequestParam means it is a parameter from the GET or POST request
User n = new User(); n.setName(name); n.setEmail(email); userRepository.save(n); return "Saved";
}
#GetMapping(path="/all") public #ResponseBody Iterable<User> getAllUsers() { This returns a JSON or XML with the users return userRepository.findAll();
} }
My Repo
package com.avorion.dndwiki.Repository;
import com.avorion.dndwiki.Model.User; import org.springframework.data.repository.CrudRepository;
//This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository CRUD refers Create, Read, Update, Delete
public interface UserRepository extends CrudRepository<User, Integer> {
}
My application properties
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=root#localhost
spring.datasource.password=thisIsntMyActualPassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#spring.jpa.show-sql: true
My Pom(Theres a lot here,im just practicing)
<?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>3.0.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.Avorion</groupId>
<artifactId>DnDWiki</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>DnDWiki</name>
<description>DnDWiki</description>
<properties>
<java.version>17</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-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-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</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>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</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.kafka</groupId>
<artifactId>spring-kafka-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>
I have tried to set up a number of db with diffrent users and naming conventions. I have reset MySql as well as asking other software engineers.
Basically what the title says. No errors show in the console so I have no idea what's wrong. I am using CrudRepository. The task is to make a REST API for a game store. I am trying to access localhost:8080/game URL but 404 keeps happening.
Edit: changed #PostMapping() and #GetMapping() to #PostMapping and #GetMapping
GameStoreApplication.java:
package com.game_store.si2;
#SpringBootApplication
#ComponentScan("com.game_store.si2.repository")
public class GameStoreApplication {
public static void main(String[] args) {
SpringApplication.run(GameStoreApplication.class, args);
}
}
GameController.java:
package com.game_store.si2.controller;
#RestController #RequestMapping("/game")
public class GameController {
#Autowired
private GameRepository repository;
#PostMapping
public ResponseEntity<Game> newGame(#RequestBody Game novoGame) {
if(novoGame.getTitulo() != null) {
repository.save(novoGame);
return new ResponseEntity<>(HttpStatus.CREATED);
}
else {
return new ResponseEntity<Game>(novoGame, HttpStatus.UNPROCESSABLE_ENTITY);
}
}
#GetMapping("/{id}")
public ResponseEntity<Game> findGame(#PathVariable int id){
Optional<Game> gameObtido = repository.findById(id);
if(!gameObtido.isPresent()) {
return new ResponseEntity<Game>(HttpStatus.OK);
}
return new ResponseEntity<Game>(HttpStatus.NOT_FOUND);
}
#GetMapping
public Iterable<Game> listGames(){
return repository.findAll();
}
#DeleteMapping("/{id}")
public ResponseEntity<Game> deleteGame(#PathVariable int id){
Game gameObtido = repository.findById(id).orElse(null);
if(gameObtido != null) {
repository.delete(gameObtido);
return new ResponseEntity<Game>(gameObtido, HttpStatus.NO_CONTENT);
}
return new ResponseEntity<Game>(HttpStatus.NOT_FOUND);
}
#PutMapping("/update/{id}")
public ResponseEntity<Game> updateGame(#PathVariable int id,#RequestBody Game game){
Game existeGame = repository.findById(id).orElse(null);
if(existeGame != null) {
existeGame.setImgUrl(game.getImgUrl());
existeGame.setPreco(game.getPreco());
existeGame.setTitulo(game.getTitulo());
repository.save(existeGame);
return new ResponseEntity<Game>(existeGame, HttpStatus.OK);
}
return new ResponseEntity<Game>(HttpStatus.NOT_FOUND);
}
}
Game.java:
package com.game_store.si2.model;
#Entity #Getter #Setter #NoArgsConstructor
public class Game {
#Id #GeneratedValue(strategy = GenerationType.SEQUENCE)
private int id;
private String titulo;
private String ImgUrl;
private double preco;
private int numVendas;
}
GameRepository.java:
package com.game_store.si2.repository;
#RepositoryRestResource(collectionResourceRel = "game", path = "game")
public interface GameRepository extends CrudRepository<Game, Integer> {
}
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.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.game_store</groupId>
<artifactId>game_store</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>game_store</name>
<description>Projeto de game store de SI2</description>
<properties>
<java.version>1.8</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>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
GET and POST return:
{
"timestamp": "2020-09-10T03:41:47.478+00:00",
"status": 404,
"error": "Not Found",
"message": "",
"path": "/game"
}
You can replace #GetMapping() to #GetMapping and #PostMapping() to #PostMapping
in below method respectively like
#GetMapping
public Iterable<Game> listGames(){
return repository.findAll();
}
#PostMapping
public ResponseEntity<Game> newGame(#RequestBody Game novoGame) {
if(novoGame.getTitulo() != null) {
repository.save(novoGame);
return new ResponseEntity<>(HttpStatus.CREATED);
}
else {
return new ResponseEntity<Game>(novoGame, HttpStatus.UNPROCESSABLE_ENTITY);
}
}
To use default value of GetMapping and PostMapping you can use
#GetMapping
#PostMapping
or
#GetMapping("")
#PostMapping("")
just rename #PostMapping() to #PostMapping
I am not able to run application its show error as follows,
APPLICATION FAILED TO START
Description:
An attempt was made to call a method that does not exist. The attempt was made from the following location:
org.apache.catalina.authenticator.AuthenticatorBase.startInternal(AuthenticatorBase.java:1321)
The following method did not exist:
javax.servlet.ServletContext.getVirtualServerName()Ljava/lang/String;
The method's class, javax.servlet.ServletContext, is available from the following locations:
jar:file:/D:/Comau_Mes/datemes/lib/javax.servlet.jar!/javax/servlet/ServletContext.class
jar:file:/C:/Users/YASH/.m2/repository/javax/servlet/javax.servlet-api/3.1.0/javax.servlet-api-3.1.0.jar!/javax/servlet/ServletContext.class
jar:file:/C:/Users/YASH/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/9.0.35/tomcat-embed-core-9.0.35.jar!/javax/servlet/ServletContext.class
It was loaded from the following location:
file:/D:/Comau_Mes/datemes/lib/javax.servlet.jar
Action:
Correct the classpath of your application so that it contains a single, compatible version of javax.servlet.ServletContext
Process finished with exit code 0
Files as follows,
File-----> Product.java
#Entity
#Table(name="product")
public class Product {
#Id
private String id;
private String name;
private double price;
private int quantity;
private boolean status;
#JsonFormat(pattern ="", shape = JsonFormat.Shape.STRING)
#Column(name = "date_created")
private String dateCreated;
public String getId() {
return id;
}
//netal
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public String getDateCreated() {
return dateCreated;
}
public void setDateCreated(String dateCreated) {
this.dateCreated = dateCreated;
}
}
File --> ProductController
#RestController
#RequestMapping("api/product")
public class ProductController {
#Autowired
private ProductServices productServices;
#RequestMapping(value = "findall", method = RequestMethod.GET,
produces = {MimeTypeUtils.APPLICATION_JSON_VALUE})
public ResponseEntity<Iterable<Product>> findAll(){
try {
return new ResponseEntity<Iterable<Product>>
(productServices.findAll(),HttpStatus.OK);
}catch (Exception e){
return new ResponseEntity<Iterable<Product>>(HttpStatus.BAD_REQUEST);
}
}
}
File --> ProductRepository
#Repository("ProductRepository")
public interface ProductRepository extends CrudRepository<Product,String> {
}
File --> ProductServices
public interface ProductServices {
public Iterable<Product> findAll();
public Product save(Product product);
}
File --> ProductServicesImpl
#Service("productServices")
public class ProductServicesImpl implements ProductServices {
#Autowired
private ProductRepository productRepository;
#Override
public Iterable<Product> findAll() {
return productRepository.findAll();
}
#Override
public Product save(Product product) {
return productRepository.save(product);
}
}
File --> DatemesApplication
#SpringBootApplication
public class DatemesApplication {
public static void main(String[] args) {
SpringApplication.run(DatemesApplication.class, args);
}
}
File --> 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.3.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>datemes</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>datemes</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</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-configuration-processor</artifactId>
<optional>true</optional>
</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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.5.2.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
So I have setup a spring boot project with which I'd like to create some specific queries.
Very simple, I just want to execute a select statement:
public class UserRepositoryCustomImpl implements UserRepositoryCustom {
#PersistenceContext
private EntityManager entityManager;
public User findUserByEmail(String email) {
Query nativeQuery = entityManager.createQuery("select e from User");
nativeQuery.getFirstResult();
return new User();
}
}
In Intellij, when I hover over User it says cannot resolve symbol for User, I've had a google and most of the answers say you need to use the name of the entity, which of course I did:
#Entity(name = "PG_user")
public class User extends AbstractEntity {
#Column
private String email;
#Column
private String password;
public User(){}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Here is my POM also, if this helps:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
<!-- https://mvnrepository.com/artifact/org.modelmapper/modelmapper -->
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>0.3.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.2.2.jre8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.webjars.bower/angular-bootstrap-contextmenu -->
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>angular-bootstrap-contextmenu</artifactId>
<version>0.9.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-crypto -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.0-api -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
</dependencies>
But the name of your entity is PG_user
#Entity(name = "PG_user")
public class User extends AbstractEntity {
The name attribute defines the name of the entity that you must use for querying.
But I assume you want to set the name of the table.
That would be
#Table(name = "PG_user")
#Entity
public class User extends AbstractEntity {
I am try to access data mysql in Spring Boot.when i run application.I got this error
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 java.lang.NoClassDefFoundError: javassist/bytecode/ClassFile
my code is
Controller
#GetMapping(path="/add")
public #ResponseBody String addNewUser (#RequestParam String name
, #RequestParam String email) {
UserPojo n = new UserPojo();
n.setName(name);
n.setEmail(email);
userRepository.save(n);
return "Saved";
}
Service is
#Service("service")
#Transactional
public class UserService {
#Autowired
private User user;
public void addUser(UserPojo pojo) {
UserEntity userEntity = new UserEntity();
userEntity.setCustomerName(pojo.getCustomerName());
userEntity.setEmail(pojo.getEmail());
user.save(userEntity);
}
}
Dao is
public interface User extends CrudRepository<UserEntity, Integer> {
}
Entity is-
package com.example.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;
#Entity
#Table(name = "customer")
public class UserEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column
private String customerName;
#Column
private String email;
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
My Pojo
public class UserPojo {
private String customerName;
private String email;
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
My pom.xml
<?xml version="1.0" encoding="UTF-8"?>
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>com.example</groupId>
<artifactId>Test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Test</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.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-web</artifactId>
</dependency>
<!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Use MySQL Connector-J -->
<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>
application.properties
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
server.port=8085
server.servlet.context-path=/finance
# Database
spring.datasource.url=jdbc:mysql://localhost:3306/test?
autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# Hibernate
hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql: true
hibernate.hbm2ddl.auto: create
I have implemented your project. Everything going fine. I am describing step by step. I wrote my pom.xml like this
<?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>org.avijit</groupId>
<artifactId>bootproject</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Then I wrote my main class and created a bean for jsp page.
#SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new
InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
After this i wrote Controller class like
#Autowired
UserService userService;
#RequestMapping(value="/sample", method= RequestMethod.GET)
public String sample()
{
return "sample";
}
#RequestMapping(value="/sample", method= RequestMethod.POST)
public String dosave(#RequestParam String name, #RequestParam String email)
{
UserPojo n = new UserPojo();
n.setCustomerName(name);
n.setEmail(email);
userService.addUser(n);
return "sample";
}
And edited service class
#Autowired
private User user;
public void addUser(UserPojo pojo) {
UserEntity userEntity = new UserEntity();
userEntity.setCustomerName(pojo.getCustomerName());
userEntity.setEmail(pojo.getEmail());
user.save(userEntity);
}
While copying your code I found that in controller class you made an error n.setName(name); it would be n.setCustomerName(name). And in my property file I wrote like this.
spring.datasource.url =jdbc:mysql://127.0.0.1:3306/InternDatabase
spring.datasource.username = root
spring.datasource.password = 123456
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto = update
Check updated code and let us know.