I am establishing a one to many relationship between two entities "Event" and "Message". Event is the parent and message is the child. Whenever I tried to insert a row of data into "Message" I always get java.sql.SQLIntegrityConstraintViolationException: Column 'msg' cannot be null which I certainly have entered it. When I set msg property to be nullable then the error message becomes java.sql.SQLIntegrityConstraintViolationException: Column 'user_name' cannot be null. It seems mysql did not get any argument from Postman. Been trying to look for answers for whole day but can't find one, please help me out. The following is the code.
Event Entity
package com.example.springsecurityjwt.models;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name ="Event")
public class Event {
#Id
private int eventId;
private int mountainId;
private String event_name;
private String leader;
private Date date;
private int eventType;
private int minNumOfMember;
private int numOfMember;
private String description;
#Column(columnDefinition = "integer default 0")
private int status;
#OneToMany
#JoinColumn(name = "eventId", referencedColumnName = "eventId")
List<Message> messages = new ArrayList<>();
}
Message Entity
package com.example.springsecurityjwt.models;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name ="Message")
public class Message {
#Id
private int messageId;
private int eventId;
private String userName;
private String msg;
private Date date;
}
MessageService
#Service
public class MessageService {
#Autowired
private MessageRepository messageRepository;
public Message addMessage(Message message){
return messageRepository.save(message);
}
}
MessageController
#RestController
#RequestMapping("/message")
public class MessageController {
#Autowired
private MessageService messageService;
#PostMapping("/add")
public Message addMessage(#Validated Message message){
return messageService.addMessage(message);
}
}
Dependencies
<?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.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-security-jwt</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-security</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>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred -->
<version>0.11.2</version>
<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>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Message table in mysql
enter image description here
Error message
Hibernate: insert into message (date, event_id, msg, user_name, message_id) values (?, ?, ?, ?, ?)
2020-06-28 20:25:37.125 WARN 16204 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1048, SQLState: 23000
2020-06-28 20:25:37.125 ERROR 16204 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : Column 'msg' cannot be null
2020-06-28 20:25:37.140 ERROR 16204 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
java.sql.SQLIntegrityConstraintViolationException: Column 'msg' cannot be null
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1092) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1040) ~[mysql-connector-java-8.0.20.jar:8.0.20]
Are you sure you're parsing json correctly? I can see you're using spring, then you'll probably have to use #RequestBody:
#PostMapping("/add")
public Message addMessage(#Validated #RequestBody Message message){
return messageService.addMessage(message);
}
I suggest placing a breakpoint there to see whether Message object is constructed properly.
In my case, I used email for the entity class and used email_id for the dto class. The request sent was from the entity class, which is disconnected from the dto. Hence the error.
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
I am coding for a web app but receive this error in creating fields in the database. It says the table "user" not found.
I am adding the classes and file.
It throws this error
2020-05-05 23:04:20.539 WARN 145848 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of URL [file:/C:/Spring%20pro%20codeengine/sources/target/classes/data.sql]: insert into user values (1,'Slnmak','Codeengine#gmail.com'); nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "user" not found; SQL statement:
insert into user values (1,'Slnmak','Codeengine#gmail.com') [42102-200]
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-05-05 23:04:20.803 ERROR 145848 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of URL [file:/C:/Spring%20pro%20codeengine/sources/target/classes/data.sql]: insert into user values (1,'Slnmak','Codeengine#gmail.com'); nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "user" not found; SQL statement:
insert into user values (1,'Slnmak','Codeengine#gmail.com') [42102-200]
Caused by: org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of URL [file:/C:/Spring%20pro%20codeengine/sources/target/classes/data.sql]: insert into user values (1,'Slnmak','Codeengine#gmail.com'); nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "user" not found; SQL statement:
insert into user values (1,'Slnmak','Codeengine#gmail.com') [42102-200]
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "user" not found; SQL statement:
insert into user values (1,'Slnmak','Codeengine#gmail.com') [42102-200]
I have a Category class as below.
Category.java
package com.example.sources.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
import lombok.NoArgsConstructor;
#Entity
#Data
#NoArgsConstructor
#Table(name="category")
public class Category {
#Id
private Long id;
private String 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;
}
}
User.java
package com.example.sources.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Entity
#NoArgsConstructor
#AllArgsConstructor
#Data
#Table(name="user")
public class User {
#Id
private Long id;
private String name;
private String email;
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
And created a repository Interface as
CategoryRepository.java
package com.example.sources.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.sources.model.Category;
public interface CategoryRepository extends JpaRepository<Category, Long>{
Category findByName(String name);
}
Data.sql
insert into user values (1,'Slnmak','Codeengine#gmail.com')
insert into user values (2,'John','adam#gmail.com')
insert into user values (3,'Adam','john#gmail.com')
insert into category values (1,'Travel')
insert into category values (2,'Auto Loan')
insert into category values (3,'Student Loan')
--insert into expense values (100,'New York trip','2019-06-16T17:00:00.0002' )
--insert into expense values (101,'Ford Mustang Payment','2019-06-15T15:00:00.0002' )
--insert into expense values (102,'Slnmak Trip with family','2019-06-14T15:00:00.0002' )
application.properties
spring.jpa.show-sql=true
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false
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-web</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>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>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Application is not able to create tables automatically. Replace your application.properties file with this :
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.generate-ddl=true
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false
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.
I want to integrate Spring and JPA I'm using spring boot. First I tried to create SessionFactory using EntityManager, but I can't. I've already asked this question here Spring boot inject EntityManagerFactory in configuration class. Those pieces of advice didn't help me and It still doesn't work. So now I decided to try to persist by entityManager, but when I persist my object I get an error.
java.lang.IllegalArgumentException: Unknown entity: kz.training.springrest.entity.User
There is my User class
import lombok.*;
import javax.persistence.*;
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#ToString
#Entity
#Table(name = "users")
public class User {
#Id
#SequenceGenerator(name = "user_id_seq_gen", sequenceName = "user_id_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_id_seq_gen")
private Long id;
#Column
private String username;
#Column
private String password;
}
Service class
package kz.training.springrest.service;
import kz.training.springrest.entity.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
#Service
public class UserService {
#PersistenceContext
private EntityManager entityManager;
#Transactional
public void insertUser(User user) {
entityManager.persist(user);
}
}
Runner
#SpringBootApplication
#ComponentScan(basePackages="kz.training.springrest")
public class SpringrestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringrestApplication.class, args);
}
}
Database configuration just in case) there is nothing yet
#Configuration
#EnableTransactionManagement
public class DatabaseConfiguration {
}
My dependencies
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.2</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
</dependencies>
Properties
spring.datasource.url= jdbc:postgresql://localhost:5432/ring
spring.datasource.username=postgres
spring.datasource.password=root
spring.jpa.show-sql = false
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.hibernate.naming.implicit-strategy = org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl
spring.jpa.properties.hibernate.format_sql=true
#Note: The last two properties on the code snippet above were added to suppress an annoying exception
# that occurs when JPA (Hibernate) tries to verify PostgreSQL CLOB feature.
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL9Dialect
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
Any ideas?
Add #EntityScan for your SpringrestApplication
#SpringBootApplication
#ComponentScan(basePackages="kz.training.springrest")
#EntityScan("kz.training.springrest.entity")
public class SpringrestApplication {
I'm currently working on an application for an university project. For this project, my team and I are using a Vaadin/Spring/Maven configuration. With this we also include a database connected with repositories.
The repositories are build the following way. First a class for objects:
import javax.persistence.*;
import java.util.Set;
#Entity
#Table (name = "component")
public class Component {
#Id #GeneratedValue(strategy = GenerationType.AUTO)
long id;
String name;
float price;
boolean isVegetarian;
#OneToMany(mappedBy = "component", cascade = {CascadeType.PERSIST, CascadeType.REFRESH}, fetch = FetchType.EAGER)
Set<InvoicePosition> Positions;
#ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
ComponentCategory category_id;
String path;
public Component() {
}
public Component(String name, float price, boolean isVegetarian, ComponentCategory category, String path) {
this.name = name;
this.price = price;
this.isVegetarian = isVegetarian;
this.category_id = category;
this.path = path;
}
Then the additional repository:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface ComponentRepository extends JpaRepository<Component, Long>{}
Then there is a repository for component category, in which we should be able to store a list of components:
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name = "componentCategory")
public class ComponentCategory {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String name;
#OneToMany(mappedBy = "category_id", cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
List<Component> components;
public ComponentCategory() { }
public ComponentCategory(String name) {
this.name = name;
components = new ArrayList<>();
}
public void addComponentToCategory(Component component) {
if(!components.contains(component))
{
components.add(component);
component.category_id = this;
}
}
And then the same repository:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface ComponentCategoryRepository extends JpaRepository<ComponentCategory, Long> {}
I am able to create new entries and they are also properly stored in the database. This is all stored in the Application.Java file to start the Vaadin application
ComponentCategory cat1 = new ComponentCategory("examp1");
Component test1 = new Component("example1", 1.25f, true, cat1, "");
Component test2 = new Component("example2", 0.89f, true, cat1, "");
cat1.addComponentToCategory(test1);
cat1.addComponentToCategory(test2);
compcatrep.saveAndFlush(comp); // compcatrep is the ComponentCategoryRepository, which is passed on to the init() function
Now I'm trying to update the entries in the database with the following logic:
Component test11 = new Component("Test", 2.15f, true, compcatrep.getOne((long)4), "");
ComponentCategory comp = compcatrep.getOne((long)4);
comp.addComponentToCategory(test11);
compcatrep.saveAndFlush(comp);
I made sure that there is an entry with the ID (long) 4. It does work and does not show me any error, when I execute the application. Also if I check the length of the stored list in the ComponentCategory after the saveAndFlush():
System.out.println(comp.getComponents().size());
System.out.println(compcatrep.getOne((long)4).getComponents().size());
I do receive different length of the lists. The second Syso does show one less then the first. I tried a lot and did not find the error. Some more information about my issue:
ApplicationProperties in target folder:
spring.datasource.url=jdbc:h2:file:./mensarioDB;DB_CLOSE_ON_EXIT=TRUE
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>de.hs-augsburg.bpap</groupId>
<artifactId>mensario</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mensario</name>
<description>mensario management</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.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>
<vaadin.version>8.1.0</vaadin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-spring-boot-starter</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>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-bom</artifactId>
<version>${vaadin.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>