spring boot data jpa mysql could not create database - java

I am new in spring
I will post my code,
that the application.properties
spring.datasource.url=jdbc:mysql://localhost/spring
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.ddl-auto=update
and this my entity
package model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String phone;
private String adresse;
public long getId() {
return id;
}
public void setId(long 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 String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public Person(long id, String name, String phone, String adresse) {
super();
this.id = id;
this.name = name;
this.phone = phone;
this.adresse = adresse;
}
public Person() {
super();
}
}
and this is the repository
package repositry;
import org.springframework.data.jpa.repository.JpaRepository;
import model.Person;
public interface PersonRespositry extends JpaRepository<Person, Long> {
}
and my controller
package contoller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import model.Person;
import repositry.PersonRespositry;
#RestController
public class PersonController {
PersonRespositry rp;
#Autowired
public PersonController(PersonRespositry rp) {
// TODO Auto-generated constructor stub
this.rp=rp;
}
#RequestMapping("/find")
public Person find(long id){
return rp.findOne(id);
}
#RequestMapping("/findall")
public List<Person> findall(){
return rp.findAll();
}
#RequestMapping(value="/hello")
public String Demo(){
return "Hello world !!";
}
#RequestMapping(value="/create", method=RequestMethod.GET)
public String create(){
Person p=new Person();
p.setName("med");
p.setPhone("233888");
p.setAdresse("rue ");
rp.save(p);
return " success";
}
}
This is the architect of the project:
When I run the application the database does not generate and only the
localhost:8080 is running.

Your problem is the location of the Application.java.
#ComponentScanlooks for Spring beans inside the package of the class annotated with (#SpringBootApplication contains #ComponentScan) and in subpackages of this package.
I already provided an example to a very similar setup.
Please have a look here: https://stackoverflow.com/a/27983870/2576531
Furthermore the hint of Robert Moskal is correct. The database itself has to exist already. Only the tables will be created automatically.

If you want the data to be created you need to use create or create-drop. If you are using something like mysql you'll need to have created at least the database. The tables will be created for you.
I be very careful about doing this against a production database instance.

Otherwise for me it dosen't work with #componentScan but it works now with #EntityScan(basePackages = { "com.jwt.entites" }) in the main class to scan entity classes ..

This is not the answer but this is a sample. I think this will help you
//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.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wisdom.spring.myjdbc</groupId>
<artifactId>spring_boot_jpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring_boot_jpa</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-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>
<scope>runtime</scope>
</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>
//application Config
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/wisdom
spring.datasource.username=root
spring.datasource.password=8855
spring.jpa.generate-ddl=true
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
server.port = 8585
package com.wisdom.spring.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import com.wisdom.spring.model.students;
import com.wisdom.spring.repo.students_repo;
#RestController
#RequestMapping("/students")
public class studentController {
#Autowired
students_repo STDRepo;
#GetMapping(value = "/a")
public String a() {
return "hello";
}
#GetMapping(value = "/save")
public List<students> getStudents(){
System.out.println("Data returned");
return STDRepo.findAll();
}
#PostMapping(value = "/savestd")
public void saveBurger(students student) {
STDRepo.save(student);
}
}
package com.wisdom.spring.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class students {
#Id
#Column
private int s_id;
#Column
private String name;
#Column
private String address;
public students() {
}
public students(int s_id, String name, String address) {
this.s_id = s_id;
this.name = name;
this.address = address;
}
public int getS_id() {
return s_id;
}
public void setS_id(int s_id) {
this.s_id = s_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;
}
}
package com.wisdom.spring.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import com.wisdom.spring.model.students;
public interface students_repo extends JpaRepository<students,String> {
}
package com.wisdom.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootJpaApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootJpaApplication.class, args);
}
}

Related

.User is a not managed type

I am getting an error when I am running my application
Caused by: java.lang.IllegalArgumentException: Not a managed type: class org.springframework.security.core.userdetails.User
at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:583) ~[hibernate-core-5.6.11.Final.jar:5.6.11.Final]
at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:85) ~[hibernate-core-5.6.11.Final.jar:5.6.11.Final]
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:75) ~[spring-data-jpa-2.7.3.jar:2.7.3]
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:66) ~[spring-data-jpa-2.7.3.jar:2.7.3]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:233) ~[spring-data-jpa-2.7.3.jar:2.7.3]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:182) ~[spring-data-jpa-2.7.3.jar:2.7.3]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:165) ~[spring-data-jpa-2.7.3.jar:2.7.3]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:76) ~[spring-data-jpa-2.7.3.jar:2.7.3]
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:325) ~[spring-data-commons-2.7.3.jar:2.7.3]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:323) ~[spring-data-commons-2.7.3.jar:2.7.3]
at org.springframework.data.util.Lazy.getNullable(Lazy.java:231) ~[spring-data-commons-2.7.3.jar:2.7.3]
at org.springframework.data.util.Lazy.get(Lazy.java:115) ~[spring-data-commons-2.7.3.jar:2.7.3]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:329) ~[spring-data-commons-2.7.3.jar:2.7.3]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:144) ~[spring-data-jpa-2.7.3.jar:2.7.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.23.jar:5.3.23]
Application structure
Structure
pom.xml
<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.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>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</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>
RestartApplication.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class RestartApplication {
public static void main(String[] args) {
SpringApplication.run(RestartApplication.class, args);
}
}
MvcConfig
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class RestartApplication {
public static void main(String[] args) {
SpringApplication.run(RestartApplication.class, args);
}
}
WebSecurityConfig
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import javax.sql.DataSource;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private DataSource dataSource;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.csrf().disable();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.dataSource(dataSource)
.passwordEncoder(NoOpPasswordEncoder.getInstance())
.usersByUsernameQuery("select username, password, active from user where username=?")
.authoritiesByUsernameQuery("select u.username, ur.roles from usr u inner join userRole ur on u.id = ur.userId where u.username=?");
}
}
AuthenticationController (it displays welcome page)
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Map;
#Controller
public class AuthenticationController {
#GetMapping("/")
public String authentication(Map<String, Object> model) {
return "authentication";
}
}
BlogController
import com.Vova.Restart.Models.Post;
import com.Vova.Restart.repo.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.RequestParam;
import java.util.ArrayList;
import java.util.Optional;
#Controller
public class BlogController {
#Autowired
private PostRepository postRepository;
#GetMapping("/blog")
public String blogMain(Model model) {
Iterable<Post> posts = postRepository.findAll();
model.addAttribute("posts", posts);
return "blog";
}
#GetMapping("/blog/add")
public String blogAdd(Model model) {
return "blogAdd";
}
#PostMapping("/blog/add")
public String blogPostAdd(#RequestParam String title, #RequestParam String anons, #RequestParam String full_text, Model model) {
Post post = new Post(title, anons, full_text);
postRepository.save(post);
return "redirect:/blog";
}
#GetMapping("/blog/{id}")
public String blogDetails(#PathVariable(value = "id") long postId, Model model) {
if(!postRepository.existsById(postId)) {
return "redirect:/blog";
}
Optional<Post> post = postRepository.findById(postId);
ArrayList<Post> res = new ArrayList<>();
post.ifPresent(res::add);
model.addAttribute("post", res);
return "blogDetails";
}
#GetMapping("/blog/{id}/edit")
public String blogEdit(#PathVariable(value = "id") long postId, Model model) {
if(!postRepository.existsById(postId)) {
return "redirect:/blog";
}
Optional<Post> post = postRepository.findById(postId);
ArrayList<Post> res = new ArrayList<>();
post.ifPresent(res::add);
model.addAttribute("post", res);
return "blogEdit";
}
#PostMapping("/blog/{id}/edit")
public String blogPostUpdate(#PathVariable(value = "id") long postId, #RequestParam String title, #RequestParam String anons, #RequestParam String full_text, Model model) {
Post post = postRepository.findById(postId).orElseThrow();
post.setTitle(title);
post.setAnons(anons);
post.setFull_text(full_text);
postRepository.save(post);
return "redirect:/blog";
}
#PostMapping("/blog/{id}/remove")
public String blogPostDelete(#PathVariable(value = "id") long postId, Model model) {
Post post = postRepository.findById(postId).orElseThrow();
postRepository.delete(post);
return "redirect:/blog";
}
}
MainController
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class MainController {
#GetMapping("/home")
public String home(Model model) {
model.addAttribute("title", "Главная страница");
return "home";
}
#GetMapping("/about")
public String about(Model model) {
model.addAttribute("title", "О нас");
return "about";
}
}
RegistrationController
import com.Vova.Restart.Models.Role;
import com.Vova.Restart.repo.UserRepo;
import com.Vova.Restart.Models.User;
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 java.util.Collections;
import java.util.Map;
#Controller
public class RegistrationController {
#Autowired
private UserRepo userRepo;
#GetMapping("/registration")
public String registration() {
return "registration";
}
#PostMapping("/registration")
public String addUser (User user, Map<String, Object> model) {
User userFromDb = userRepo.findByUsername(user.getUsername());
if (userFromDb != null) {
model.put("message", "User exists!");
return "registration";
}
user.setActive(true);
user.setRole(Collections.singleton(Role.USER));
return "redirect:/login";
}
}
Post
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, full_text;
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 getFull_text() {
return full_text;
}
public void setFull_text(String full_text) {
this.full_text = full_text;
}
public int getViews() {
return views;
}
public void setViews(int views) {
this.views = views;
}
public Post() {
}
public Post(String title, String anons, String full_text) {
this.title = title;
this.anons = anons;
this.full_text = full_text;
}
}
Role
public enum Role {
USER;
}
User
import javax.persistence.*;
import java.util.Set;
#Entity
#Table(name = "User")
public class User
{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String username, password;
private boolean active;
#ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
#CollectionTable(name = "userRole", joinColumns = #JoinColumn(name = "userId"))
#Enumerated(EnumType.STRING)
private Set<Role> roles;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public void setRole(Set<Object> singleton) {
}
}
PostRepository
import com.Vova.Restart.Models.Post;
import org.springframework.data.repository.CrudRepository;
public interface PostRepository extends CrudRepository<Post, Long> {
}
UserRepo
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.security.core.userdetails.User;
public interface UserRepo extends JpaRepository<User, Long> {
com.Vova.Restart.Models.User findByUsername(String username);
}
I tried to fix it using #EnableJpaRepositories and #EntityScan but this does not help.
In my MySQL all tables was added automaticly.
My Java version is 17
Thanks
Import is wrong. Please import your User class entity instead of spring's user class.
org.springframework.security.core.userdetails.User
Note: Always follow coding standards. The package should be all lowercase to prevent unwanted errors.

Issue with Spring Boot Validation with version 2.5.5

I am fairly new to Spring Boot and it's various libraries. I am particularly trying Validation. I have added Validation annotations to UserDto class. When I send createUser request with invalid email, I get success. None of the validations work.
I have tried using Hibernate-Validator dependancy as well.
See below the code.
The UserDto class:
import javax.validation.constraints.Email;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
public class UserDto {
#NotNull
#Min(value=5)
#Max(value=10)
private String name;
#NotNull
#Min(value=3)
#Max(value=50)
private String password;
#Email
private String email;
public UserDto(String name, String password, String email) {
super();
this.name = name;
this.password = password;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
The UserCotroller:
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.user.test.dto.UserDto;
#RestController
#RequestMapping("/users")
public class UserController {
#PostMapping
public ResponseEntity<String> createUser(#Valid #RequestBody UserDto userDto, Errors errors){
System.out.println(userDto.toString());
System.out.println(errors.toString());
String response = "success";
return ResponseEntity.ok(response);
}
}
Driver Class:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
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.5.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.user</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>test</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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</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>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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Here is the Postman Request, which gives "success".
{
"name": "Username",
"password":"username#123",
"email":"username"
}
I could find two issues in your code:
The #Min/#Max annotations are for numeric values, to set the range of numeric values (not the number of strings); so these do not work for Strings. Please remove them and find alternatives (e.g. #Size).
You need to map the userDto object to the model in your controller with the #ModelAttribute annotation.
Controller (further edited to accommodate different responses)
#PostMapping
public ResponseEntity<String> createUser(#ModelAttribute #Valid #RequestBody UserDto userDto,Errors errors){
System.out.println(userDto.toString());
System.out.println(errors.toString());
if (errors.hasErrors()) {
return ResponseEntity.badRequest().body("Errors exist");
}
return ResponseEntity.ok("Success");
}
}
UserDto
public class UserDto {
#NotNull
#Size(min=5, max= 10)
private String name;
#NotNull
#Size(min=3, max= 50)
private String password;
#Email
private String email;
// rest of the code
}
Tests for controller
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#SpringBootTest
#ExtendWith(MockitoExtension.class)
class UserControllerTest {
MockMvc mockMvc;
#Autowired
UserController userController;
#BeforeEach
void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
}
#Test
void emailInvalid() throws Exception {
mockMvc.perform(post("/users").param("name", "uname")
.param( "password", "LongPasswordHere")
.param( "email", "email")).andExpect(status().isBadRequest())
.andExpect(content().string(containsString("Errors exist")));
}
#Test
void emailValid() throws Exception {
mockMvc.perform(post("/users").param("name", "uname")
.param( "password", "LongPasswordHere")
.param( "email", "email#gmail.com")).andExpect(status().isOk())
.andExpect(content().string(containsString("Success")));
}
}

Spring Boot - “Error creating bean with name 'entityManagerFactory'” - Start

I have seen a lot of questions but the answers are not satisfying my problem...
I generate my project with Spring initialzr
I tried with the 3 java versions 14, 11, 8.
This is my project structure.
GardenApplication.java. I include all anottations even spring doc says that with #SpringBootApplication is enough. Before this error #Repository couldn't be found and I include #EnableJpaRepositories
package com.garden.garden;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#EnableAutoConfiguration
#ComponentScan({"com.garden.garden.controller", "com.garden.garden.service.impl"})
#EnableJpaRepositories(basePackages = {"com.garden.garden.repository"})
#EntityScan(basePackages = {"com.garden.garden.model"})
public class GardenApplication {
public static void main(String[] args) {
SpringApplication.run(GardenApplication.class, args);
}
}
VegetableController.java
package com.garden.garden.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.garden.garden.model.Vegetable;
import com.garden.garden.service.VegetableService;
#Controller
#RequestMapping
public class VegetableController {
#Autowired
private VegetableService vegetableService;
#GetMapping("/vegetableList")
public String list(Model model) {
List<Vegetable> listVegetables = vegetableService.list();
model.addAttribute("vegetables", listVegetables);
return "index";
}
}
VegetableServiceImpl.java
package com.garden.garden.service.impl;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.garden.garden.model.Vegetable;
import com.garden.garden.repository.VegetableRepository;
import com.garden.garden.service.VegetableService;
#Service
public class VegetableServiceImpl implements VegetableService {
#Autowired
private VegetableRepository vegetableRepository;
#Override
public List<Vegetable> list() {
return (List<Vegetable>) vegetableRepository.findAll();
}
#Override
public Optional<Vegetable> listById(int id) {
// TODO Auto-generated method stub
return null;
}
#Override
public int save(Vegetable vegetable) {
// TODO Auto-generated method stub
return 0;
}
#Override
public void delete(int id) {
// TODO Auto-generated method stub
}
}
VegetableService.java
package com.garden.garden.service;
import java.util.List;
import java.util.Optional;
import com.garden.garden.model.Vegetable;
public interface VegetableService {
public List<Vegetable> list();
public Optional<Vegetable> listById(int id);
public int save(Vegetable vegetable);
public void delete(int id);
}
VegetableRepository.java
package com.garden.garden.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.garden.garden.model.Vegetable;
#Repository
public interface VegetableRepository extends JpaRepository<Vegetable, Integer> {
}
Vegetable.java
package com.garden.garden.model;
import java.math.BigDecimal;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "vegetable")
public class Vegetable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String family;
private int daysOnNursery;
private int daysToGrow;
private int daysHarvesting;
private java.math.BigDecimal plantsPerSquare;
private java.math.BigDecimal price;
private java.math.BigDecimal weight;
public Vegetable(int id, String name, String family, int daysOnNursery, int daysToGrow, int daysHarvesting,
BigDecimal plantsPerSquare, BigDecimal price, BigDecimal weight) {
super();
this.id = id;
this.name = name;
this.family = family;
this.daysOnNursery = daysOnNursery;
this.daysToGrow = daysToGrow;
this.daysHarvesting = daysHarvesting;
this.plantsPerSquare = plantsPerSquare;
this.price = price;
this.weight = weight;
}
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 getFamily() {
return family;
}
public void setFamily(String family) {
this.family = family;
}
public int getDaysOnNursery() {
return daysOnNursery;
}
public void setDaysOnNursery(int daysOnNursery) {
this.daysOnNursery = daysOnNursery;
}
public int getDaysToGrow() {
return daysToGrow;
}
public void setDaysToGrow(int daysToGrow) {
this.daysToGrow = daysToGrow;
}
public int getDaysHarvesting() {
return daysHarvesting;
}
public void setDaysHarvesting(int daysHarvesting) {
this.daysHarvesting = daysHarvesting;
}
public java.math.BigDecimal getPlantsPerSquare() {
return plantsPerSquare;
}
public void setPlantsPerSquare(java.math.BigDecimal plantsPerSquare) {
this.plantsPerSquare = plantsPerSquare;
}
public java.math.BigDecimal getPrice() {
return price;
}
public void setPrice(java.math.BigDecimal price) {
this.price = price;
}
public java.math.BigDecimal getWeight() {
return weight;
}
public void setWeight(java.math.BigDecimal weight) {
this.weight = weight;
}
}
I also try to solve the problem adding this dependency:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
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.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.garden</groupId>
<artifactId>garden</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>garden</name>
<description>Market garden web application</description>
<properties>
<java.version>14</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.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.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</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>
application.properties
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
spring.datasource.url=jdbc:mysql://localhost:3306/garden
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create
Please remove the exclusion of the auto configuration in your application.properties and add an hibernate-dialect, i.e. update your application.properties as follows:
spring.datasource.url=jdbc:mysql://localhost:3306/garden
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
In addition you can simplify GardenApplication to
package com.garden.garden;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#EnableJpaRepositories
#EntityScan
public class GardenApplication {
public static void main(String[] args) {
SpringApplication.run(GardenApplication.class, args);
}
}
and remove tomcat dependency from your pom (it comes in transitively with spring-boot-starter-web).
Besides, having lombok in your dependencies, you can annotate Vegetable with #Data and remove Getters, Setters and the constructor.

Spring Boot & Couchbase Stack Overflow

Hi I have 2 simple classes in a bidirectional relationship which are causing infinite recursion resulting in an eventual stack overflow when serialising into JSON. I am using the Spring Boot 2.2.2 starter project for Couchbase and Spring Web dependencies. My maven pom.xml file is as follows:
<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.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.stevie</groupId>
<artifactId>stack-overflow-error</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>stack-overflow-error</name>
<description>Reproduce Couchbase API Failure</description>
<properties>
<java.version>13</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-couchbase</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-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>
My domain classes are as follows:
Household.java
import org.springframework.data.couchbase.core.mapping.Document;
import com.couchbase.client.java.repository.annotation.Field;
import com.couchbase.client.java.repository.annotation.Id;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
#Document
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "#id")
public final class Household {
#Id
private final String key;
#Field
private String type = "household";
#Field
private final String headSurname;
#Field
private final String headForename;
#Field
private final List<Member> members;
public static Household of(String key, String headSurname, String headForename) {
return new Household(key, headSurname, headForename);
}
Household(String key, String headSurname, String headForename) {
super();
this.key = key;
this.headSurname = headSurname;
this.headForename = headForename;
this.members = new ArrayList<>();
}
public String getKey() {
return key;
}
public String getHeadSurname() {
return headSurname;
}
public String getHeadForename() {
return headForename;
}
#JsonManagedReference
public List<Member> getMembers() {
return members;
}
#Override
public String toString() {
return String.format("Household [key=%s, headSurname=%s, headForename=%s]", key,
headSurname, headForename);
}
}
Member.java
import org.springframework.data.couchbase.core.mapping.Document;
import com.couchbase.client.java.repository.annotation.Field;
import com.couchbase.client.java.repository.annotation.Id;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
#Document
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "#id")
public final class Member {
#Id
private final String key;
#Field
private final String name;
#Field
private final Household household;
public static Member of(String key, String name, Household household) {
return new Member(key, name, household);
}
Member(String key, String name, Household household) {
super();
this.key = key;
this.name = name;
this.household = household;
}
public String getKey() {
return key;
}
public String getName() {
return name;
}
#JsonBackReference
public Household getHousehold() {
return household;
}
#Override
public String toString() {
return String.format(
"Member [key=%s, name=%s]", key, name);
}
}
My unit test (JUnit 5) is
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.couchbase.core.CouchbaseTemplate;
import org.stevie.overflow.StackOverflowErrorApplication;
import org.stevie.overflow.domain.Household;
import org.stevie.overflow.domain.Member;
import com.couchbase.client.java.Bucket;
#SpringBootTest(classes = StackOverflowErrorApplication.class)
class HouseholdRepositoryTest {
#Autowired
private HouseholdRepository repo;
#Autowired
private CouchbaseTemplate template;
#BeforeAll
static void setUpBeforeClass() throws Exception {
}
#AfterAll
static void tearDownAfterClass() throws Exception {
}
#BeforeEach
void setUp() throws Exception {
}
#AfterEach
void tearDown() throws Exception {
}
#Test
void throwsStackOverflowExceptionTest() {
String key = manuallyGenerateKey("household");
Household house = Household.of(key, "BLOGGS", "Joe");
key = manuallyGenerateKey("member");
Member m1 = Member.of(key, "Joe Bloggs", house);
house.getMembers().add(m1);
/** Following code throws Stack overflow exception!!!!! **/
house = repo.save(house);
}
private String manuallyGenerateKey(String prefix) {
Bucket bucket = template.getCouchbaseBucket();
Long nextId = bucket.counter("counter::" + prefix, 1, 100).content();
String key = prefix + "::" + nextId;
return key;
}
}
I want the JSON for the household to contain its member objects and the member to contain its household object. I have tried Jackson annotations such as #JsonManagedReference and #JsonIdentityInfo but Spring appears to ignore them. Thanks.

Error with JPA persistence.xml No Persistence provider for EntityManager

I have 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>net.vyhn</groupId>
<artifactId>jpa</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>jpa Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.core</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.2</version>
</dependency>
</dependencies>
<build>
<finalName>jpa</finalName>
</build>
</project>
Employee.java
package example.com.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
#Entity
public class Employee {
#Id
#GeneratedValue
private Long id;
private String name;
#ManyToOne
private Department department;
public Employee() {
}
public Employee(String name, Department department) {
this.name = name;
this.department = department;
}
public Employee(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
#Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", department="
+ department.getName() + "]";
}
}
Department.java
package example.com.domain;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import java.util.ArrayList;
import java.util.List;
#Entity
public class Department {
#Id
#GeneratedValue
private Long id;
private String name;
#OneToMany(mappedBy = "department", cascade = CascadeType.PERSIST)
private List<Employee> employees = new ArrayList<Employee>();
public Department() {
super();
}
public Department(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
}
JpaTest.java
package example.com.jpa;
import example.com.domain.Department;
import example.com.domain.Employee;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.List;
public class JpaTest {
private EntityManager manager;
public JpaTest(EntityManager manager) {
this.manager = manager;
}
public static void main(String[] args) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("persistenceUnit");
EntityManager manager = factory.createEntityManager();
JpaTest test = new JpaTest(manager);
EntityTransaction tx = manager.getTransaction();
tx.begin();
try {
test.createEmployees();
} catch (Exception e) {
e.printStackTrace();
}
tx.commit();
test.listEmployees();
System.out.println(".. done");
}
private void createEmployees() {
int numOfEmployees = manager.createQuery("Select a From Employee a", Employee.class).getResultList().size();
if (numOfEmployees == 0) {
Department department = new Department("java");
manager.persist(department);
manager.persist(new Employee("Jakab Gipsz", department));
manager.persist(new Employee("Captain Nemo", department));
}
}
private void listEmployees() {
List<Employee> resultList = manager.createQuery("Select a From Employee a", Employee.class).getResultList();
System.out.println("num of employess:" + resultList.size());
for (Employee next : resultList) {
System.out.println("next employee: " + next);
}
}
}
When I run JpaTest.java, has error:
"C:\Program Files\Java\jdk1.8.0_92\bin\java" -Didea.launcher.port=7533 "-Didea.launcher.bin.path=C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2016.1.2\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_92\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\rt.jar;C:\Users\Administrator\IdeaProjects\demo_jpa\target\classes;C:\Users\Administrator\.m2\repository\org\eclipse\persistence\eclipselink\2.6.3\eclipselink-2.6.3.jar;C:\Users\Administrator\.m2\repository\org\eclipse\persistence\javax.persistence\2.1.1\javax.persistence-2.1.1.jar;C:\Users\Administrator\.m2\repository\org\eclipse\persistence\commonj.sdo\2.1.1\commonj.sdo-2.1.1.jar;C:\Users\Administrator\.m2\repository\javax\validation\validation-api\1.1.0.Final\validation-api-1.1.0.Final.jar;C:\Users\Administrator\.m2\repository\org\glassfish\javax.json\1.0.4\javax.json-1.0.4.jar;C:\Users\Administrator\.m2\repository\org\eclipse\persistence\org.eclipse.persistence.core\2.6.3\org.eclipse.persistence.core-2.6.3.jar;C:\Users\Administrator\.m2\repository\org\eclipse\persistence\org.eclipse.persistence.asm\2.6.3\org.eclipse.persistence.asm-2.6.3.jar;C:\Users\Administrator\.m2\repository\org\eclipse\persistence\org.eclipse.persistence.jpa\2.6.3\org.eclipse.persistence.jpa-2.6.3.jar;C:\Users\Administrator\.m2\repository\org\eclipse\persistence\org.eclipse.persistence.antlr\2.6.3\org.eclipse.persistence.antlr-2.6.3.jar;C:\Users\Administrator\.m2\repository\org\eclipse\persistence\org.eclipse.persistence.jpa.jpql\2.6.3\org.eclipse.persistence.jpa.jpql-2.6.3.jar;C:\Users\Administrator\.m2\repository\javax\persistence\persistence-api\1.0.2\persistence-api-1.0.2.jar;C:\Users\Administrator\.m2\repository\mysql\mysql-connector-java\6.0.2\mysql-connector-java-6.0.2.jar;C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2016.1.2\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain example.com.jpa.JpaTest
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named persistenceUnit
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:85)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at example.com.jpa.JpaTest.main(JpaTest.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Help me fix this error, thank you!
You have to put persistence.xml in java/resources folder.
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
I hope this will work

Categories

Resources