When I run the project, does not create tables in MySQL.
I tried to change the spring.jpa.hibernate.ddl-auto = update to create-drop and also does not to create.
No error appears in the log.
My class
#NoArgsConstructor
#AllArgsConstructor
#Data
#Entity(name = "tb_user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(length = 75, nullable = false)
private String name;
#Column(length = 75, nullable = false, unique = true)
private String email;
#Column(length = 100, nullable = false)
private String password;
}
My 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-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-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
my application.properties
spring.datasource.url=jdbc:mysql://localhost:3307/db_spring?useTimezone=true&serverTimezone=UTC
spring.datasource.username=sa
spring.datasource.password=1234567
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.data.jpa.repositories.enabled=true
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
Try adding
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
also check you are using #EnableAutoConfiguration and entity classes are in same package or subpackage
Related
I am working on java spring shopping mall project. I want to fix this error.
Below is my code.
java.lang.IllegalStateException: Failed to load ApplicationContext for [WebMergedContextConfiguration#4768b95c testClass = com.maven_shopping.repository.ItemRepositoryTest, locations = [], classes = [com.maven_shopping.MavenShoppingApplication], contextInitializerClasses = [], activeProfiles = [], propertySourceLocations = ["classpath:application-test.properties"], propertySourceProperties = ["org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true"], contextCustomizers = [org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#4e268090, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#5939a379, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer#1f97cf0d, org.springframework.boot.test.autoconfigure.actuate.observability.ObservabilityContextCustomizerFactory$DisableObservabilityContextCustomizer#9da1, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#44821a96, org.springframework.boot.test.context.SpringBootTestAnnotation#9346081e], resourceBasePath = "src/main/webapp", contextLoader = org.springframework.boot.test.context.SpringBootContextLoader, parent = null]
Item.java:
package com.maven_shopping.entity;
import com.maven_shopping.constant.ItemSellStatus;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.time.LocalDateTime;
#Entity
#Table(name = "item")
#Getter
#Setter
#ToString
public class Item {
#Id
#Column(name = "item_id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(nullable = false, length = 50)
private String itemName;
#Column(name = "price", nullable = false)
private int price;
#Column(nullable = false)
private int stockNum;
#Lob
#Column(nullable = false)
private String itemDetail;
#Enumerated(EnumType.STRING)
private ItemSellStatus itemSellStatus;
private LocalDateTime regTime;
private LocalDateTime updateTime;
}
ItemRepositoryTest :
package com.maven_shopping.repository;
import com.maven_shopping.constant.ItemSellStatus;
import com.maven_shopping.entity.Item;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import java.time.LocalDateTime;
import static org.junit.jupiter.api.Assertions.\*;
#SpringBootTest
#TestPropertySource(locations = "classpath:application-test.properties")
class ItemRepositoryTest {
#Autowired
ItemRepository itemRepository;
#Test
#DisplayName("상품 저장 테스트")
public void createItemTest() {
Item item = new Item();
item.setItemName("Test Product");
item.setPrice(10000);
item.setItemDetail("Test Product Detail");
item.setItemSellStatus(ItemSellStatus.SELL);
item.setStockNum(100);
item.setRegTime(LocalDateTime.now());
item.setUpdateTime(LocalDateTime.now());
Item savedItem = itemRepository.save(item);
System.out.println(savedItem.toString());
}
}
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>3.0.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.maven_shopping</groupId>
<artifactId>maven_shopping</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>maven_shopping</name>
<description>maven_shopping project for Spring Boot</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-thymeleaf</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>com.mysql</groupId>
<artifactId>mysql-connector-j</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>
</dependency>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.1.6.Final</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
application.properties:
#port setting
server.port=80
#MySQL connect setting
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost::3306/shop?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=****
#show query console
spring.jpa.properties.hibernate.show_sql=true
#query hibernate formatting
spring.jpa.properties.hibernate.format_sql=true
#question mark parameter
logging.level.org.hibernate.type.descriptor.sql=trace
spring.jpa.hibernate.ddl-auto=create
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
##Thymeleaf cache ????
#spring.thymeleaf.check-template-location=true
#spring.thymeleaf.prefix=classpath:templates/
#spring.thymeleaf.suffix=.html
#spring.thymeleaf.cache=false
spring.datasource.hikari.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.hikari.jdbc-url=jdbc:mysql://localhost:3306/shop
spring.datasource.hikari.username=root
spring.datasource.hikari.password=****
spring.datasource.hikari.pool-name=TestHikariPool
application-test.properties :
# DataSource Setting
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:test
spring.datasource.username=sa
spring.datasource.password=
#h2 Database dialect Setting
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
application.yml
spring:
datasource:
url: jdbc:h2:tcp://localhost/~/jpashop;
// MVCC=TRUE : 여러개의 요청이 들어왔을때, 빠르게 처리할 수 있도록 도와줌
username: sa
password:
driver-class-name: org.h2.Driver
jpa:
hibernate:
ddl-auto: create
#애플리케이션 실행시점에 내가 가진 SQL문을 다 지우고, 다시 생성함
properties:
hibernate:
show_sql: true
# System.out.println을 통해 sql문이 출력됨 -> 로그로 출력하게 해야함!
format_sql: true
logging.level:
org.hibernate.SQL: debug
org.hibernate.type: trace
So this is Error Message :
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: java.lang.IllegalStateException:
Error processing condition on org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.jpaVendorAdapter
Caused by: java.lang.IllegalStateException:
Failed to introspect Class [org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration] from ClassLoader [sun.misc.Launcher$AppClassLoader#42a57993]
Caused by: java.lang.NoClassDefFoundError: org/hibernate/boot/model/naming/PhysicalNamingStrategy
Caused by: java.lang.ClassNotFoundException: org.hibernate.boot.model.naming.PhysicalNamingStrategy
<?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.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example.test1</groupId>
<artifactId>test1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>test1</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>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.3.Final</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.4.Final</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</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>`
#Entity
#Table(name= "ordertransactions")
public class OrderTransaction {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#Column(name="order_name",nullable = false)
private String OrderName;
#OneToMany
#JoinColumn(name = "Customer_Id", referencedColumnName = "id", updatable = true,nullable = false)
private Customer customer;
public OrderTransaction(Long id, String OrderName) {
this.id = id;
this.OrderName = OrderName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getOrderName() {
return OrderName;
}
public void setOrderName(String OrderName) {
this.OrderName = OrderName;
}
}
public interface CustomerRepository extends JpaRepository <Customer, Long> {
#Modifying
#Query(value ="SELECT ordertransactions.id, Customer.name" +
"FROM ordertransactions" +
"INNER JOIN Customer ON orderransactions.id = customer.id;" ,nativeQuery = true)
int deleteCustomer(Customer Customer);
#Query(value="SELECT name, city FROM Customer")
Customer findCustomerByName(#Param("nameCustomer") String name);
}
so i want to join CustomerId in table ordertransaction, i had solved by myself but i dont found the solution.. please help me.
Even though there are already many questions on this topic, non of the answers have helped me so far.
The code of my application.properties:
spring.h2.console.enabled=true
spring.datasource.platform=h2
spring.datasource.url=jdbc:h2:mem:testdb
One example of my entities:
import java.util.Date;
import javax.persistence.*;
import org.springframework.boot.autoconfigure.*;
#Entity
#EnableAutoConfiguration
public class Customer {
#Id
private int customerId;
private String name;
private String street;
private String zip;
private String city;
private Date differenceSince;
private Date lastUpdatedOn;
#OneToOne
private User lastUpdatedBy;
//getters and setters ...
}
The 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>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
I cannot find the issue, but the H2 Console doesn't contain any tables:
Any ideas on what I am missing?
try to set your application.properties as below
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username= (username)
spring.datasource.password=(password)
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
I am creating a Spring Boot application with DB PostgreSQL. My application.properties looks as follow:
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url=jdbc:postgresql://localhost:5432/my-db
spring.datasource.username= myusername
spring.datasource.password= mypassword
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
The dependencies:
<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.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Simple Model:
#Entity
#Table(name = "questions")
#Data
public class Question {
#Id
#GeneratedValue(generator = "question_generator")
#SequenceGenerator(
name = "question_generator",
sequenceName = "question_sequence",
initialValue = 1000
)
private Long id;
#NotBlank
#Size(min = 3, max = 100)
private String title;
#Column(columnDefinition = "text")
private String description;
}
The Repository:
#Repository
public interface QuestionRepository extends JpaRepository<Question, Long> {
}
And the Controller:
#RestController
public class QuestionController {
#Autowired
private QuestionRepository questionRepository;
#GetMapping("/questions")
public Page<Question> getQuestions(Pageable pageable) {
return questionRepository.findAll(pageable);
}
}
When I tried to run the application, it threw an error:
Caused by: org.hibernate.exception.GenericJDBCException: Unable to
open JDBC Connection for DDL execution
Caused by:
org.postgresql.util.PSQLException: This ResultSet is closed.
Can someone give me a tipp what did I make wrong in the configuration? Thank you so much in advanced!
I have searched on StackOverflow for similar problems, and if I remove
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
everything works. However I need the data-jpa.
I have created 2 POJOs:
#Entity
public class Author {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
#ManyToMany
private Set<Book> books = new HashSet<>();
public Author(){}
}
And the second one:
#Entity
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private String isbn;
private String publisher;
#ManyToMany
private Set<Author> authors = new HashSet<>();
public Book(String title, String isbn, String publisher) {
this.title = title;
this.isbn = isbn;
this.publisher = publisher;
}
}
I have added 2 Entities and as I understand, I should no longer get the error At least one JPA metamodel must be present. Why I get this error?
DemoApplication.class
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
My pom.xml dependencies:
<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-thymeleaf</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.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.3.Final</version>
</dependency>
</dependencies>
I am to low in reputation so i can't comment the question.
Can you share your full maven pom.xml please? The solution you are referencing is this answer i guess? In this answer they do not recommend to remove spring-boot-starter-data-jpa but to remove an explicit dependency to an "old" spring-data-jpa.
Make sure to share your pom file, i can only guess right now.
Update:
The dependencies hibernate-core and hibernate-entititymanager are already provided by spring-boot-starter-jpa and you override the managed versions with your custom versions which leads to your error.
Try to remove your explicit hibernate-* dependencies.