skip to Main Content

I am writing Restful API in Spring boot 3 with java 17 and i am unable to create table .Can anyone please help

POM File

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 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.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.userservice</groupId>
    <artifactId>UserService</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>UserService</name>
    <description>user service</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-web</artifactId>
        </dependency>
        
        <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

        <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
    <version>8.0.30</version>
</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>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </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>

Controller Class

package com.userservice.UserService.controller;

import java.util.List;

@RestController
@RequestMapping("/users")

public class mainController {
    
    @Autowired
    private Serviceimpl userService;
    
    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody User user){
    User user1 = userService.saveUser(user);    
    return ResponseEntity.status(HttpStatus.CREATED).body(user1);
    }
    
    @GetMapping("/{userId}")
    public ResponseEntity<User> getSingleUser(@PathVariable String userId){
        User user = userService.getUser(userId);
        return ResponseEntity.ok(user);
    }
    
    @GetMapping("/")
    public ResponseEntity<List<User>> getAllUser(){
        List<User> allUser = userService.getAllUser();
        return ResponseEntity.ok(allUser);
    }

}

DAO Layer

package com.userservice.UserService.repos;


@Repository
public interface userRepo extends JpaRepository<User, String> {

    
    
}

My Entity class

package com.userservice.UserService.Entities;



import jakarta.persistence.*;
import lombok.*;


@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder

@Entity
@Table(name = "microsusers")
public class User {
    
    @Id
    @Column(name="id")
    private String UserId;
    @Column (name="Name",length = 200)
    private String name;
    @Column(name = "Abouts")
    private String about;
    

}

Service Class

package com.userservice.UserService.service;



@Service
public class Serviceimpl implements Services {
    
    @Autowired
    private userRepo userrepo;

    @Override
    public User saveUser(User user) {
        String randomUserId = UUID.randomUUID().toString();
        user.setUserId(randomUserId);
        return userrepo.save(user);
    }
 
    @Override
    public List<User> getAllUser() {
        return userrepo.findAll();
    }

    @Override
    public User getUser(String userId) {
        return userrepo.findById(userId)
    }

    @Override
    public void DeleteUser(String userId) {
        // TODO Auto-generated method stub
        
    }
    
    

}

Service interface

package com.userservice.UserService.service;


public interface Services {

    
    User saveUser(User user);

    List<User> getAllUser();
    
    User getUser(String userId);
    
    void DeleteUser (String userId) ;
}

application.yml file

server:
  port: 8081
  

spring:
  datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/TrialDB
    username: root
    password: pewpewpew

    

    
  jpa:
    generate-ddl: true
    hibernate:
      ddl-auto: create
    show-sql: true   

                  

OUTPUT


  .   ____          _            __ _ _
 /\ / ___'_ __ _ _(_)_ __  __ _    
( ( )___ | '_ | '_| | '_ / _` |    
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |___, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v3.0.3)

2023-03-05T18:30:56.514+05:30  INFO 1412 --- [           main] c.u.UserService.UserServiceApplication   : Starting UserServiceApplication using Java 17.0.6 with PID 1412 (D:ALL CODESMicroserviceUserServicetargetclasses started by Bhavya in D:ALL CODESMicroserviceUserService)
2023-03-05T18:30:56.517+05:30  INFO 1412 --- [           main] c.u.UserService.UserServiceApplication   : No active profile set, falling back to 1 default profile: "default"
2023-03-05T18:30:56.974+05:30  INFO 1412 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode
2023-03-05T18:30:56.975+05:30  INFO 1412 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JDBC repositories in DEFAULT mode.
2023-03-05T18:30:56.987+05:30  INFO 1412 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 9 ms. Found 0 JDBC repository interfaces.
2023-03-05T18:30:56.994+05:30  INFO 1412 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode
2023-03-05T18:30:56.995+05:30  INFO 1412 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2023-03-05T18:30:56.999+05:30  INFO 1412 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 0 ms. Found 0 JPA repository interfaces.
2023-03-05T18:30:57.408+05:30  INFO 1412 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8081 (http)
2023-03-05T18:30:57.418+05:30  INFO 1412 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-03-05T18:30:57.419+05:30  INFO 1412 --- [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.5]
2023-03-05T18:30:57.523+05:30  INFO 1412 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2023-03-05T18:30:57.523+05:30  INFO 1412 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 967 ms
2023-03-05T18:30:57.686+05:30  INFO 1412 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2023-03-05T18:30:57.748+05:30  INFO 1412 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 6.1.7.Final
2023-03-05T18:30:57.972+05:30  INFO 1412 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2023-03-05T18:30:58.141+05:30  INFO 1412 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Added connection conn0: url=jdbc:h2:mem:8a12c987-5920-49a8-bed8-3e532880482f user=ROOT
2023-03-05T18:30:58.143+05:30  INFO 1412 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2023-03-05T18:30:58.167+05:30  INFO 1412 --- [           main] SQL dialect                              : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2023-03-05T18:30:58.171+05:30  WARN 1412 --- [           main] org.hibernate.orm.deprecation            : HHH90000026: MySQL8Dialect has been deprecated; use org.hibernate.dialect.MySQLDialect instead
2023-03-05T18:30:58.466+05:30  WARN 1412 --- [           main] org.hibernate.orm.deprecation            : HHH90000021: Encountered deprecated setting [javax.persistence.schema-generation.database.action], use [jakarta.persistence.schema-generation.database.action] instead
2023-03-05T18:30:58.467+05:30  INFO 1412 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2023-03-05T18:30:58.476+05:30  INFO 1412 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2023-03-05T18:30:58.503+05:30  WARN 1412 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2023-03-05T18:30:58.855+05:30  INFO 1412 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8081 (http) with context path ''
2023-03-05T18:30:58.862+05:30  INFO 1412 --- [           main] c.u.UserService.UserServiceApplication   : Started UserServiceApplication in 2.717 seconds (process running for 3.231)

Main Class

package com.userservice.UserService;


@SpringBootApplication
@EnableConfigurationProperties
@EntityScan(basePackages = {"com.userservice.UserService.Entity"})
public class UserServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class, args);
    }

}

I’ve tried adding different dialects too like :-

spring.jpa.properties.javax.persistence.schema-generation.database.action=create
spring.jpa.properties.javax.persistence.schema-generation.create-database-schemas=true
spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata
spring.jpa.properties.javax.persistence.schema-generation.drop-source=metadata
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create
spring.jpa.defer-datasource-initialization=true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL8Dialect

spring.jpa.properties.hibernate.dialect.storage_engine=innodb

Please Help me i am stuck at this point for a really long time and this is working perfectly on spring 2

2

Answers


  1. You’re connecting to some h2 database:

    2023-03-05T18:30:57.972+05:30  INFO 1412 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
    2023-03-05T18:30:58.141+05:30  INFO 1412 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Added connection conn0: url=jdbc:h2:mem:8a12c987-5920-49a8-bed8-3e532880482f user=ROOT
    2023-03-05T18:30:58.143+05:30  INFO 1412 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
    

    Just had a look at one of my Spring 3 apps that uses postgres, but still it shouldn’t talk about H2.

    2023-03-05 13:54:34.651  INFO [           main] HikariDataSource.java:110 : HikariPool-1 - Starting... {}
    2023-03-05 13:54:34.756  INFO [           main] HikariPool.java:565 : HikariPool-1 - Added connection org.postgresql.jdbc.PgConnection@6b64bf61 {}
    2023-03-05 13:54:34.757  INFO [           main] HikariDataSource.java:123 : HikariPool-1 - Start completed. {}
    

    Make sure you don’t have H2 on the classpath or at least only for test. Testcontainers would be a better choice also for tests though.

    Also review your driverClassName. Never seen the one you placed there.

    Login or Signup to reply.
  2. Two things:

    • add scope test to your h2-dependency:

       <dependency>
           <groupId>com.h2database</groupId>
           <artifactId>h2</artifactId>
           <scope>test</scope>
       </dependency>
      
    • remove scope runtimefrom the mysql-connector-dependency:

       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>8.0.30</version>
       </dependency>
      
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search