I'm trying to run my Java Spring MVC project application, but I get the following error (I have connectted my MySql database to the project):
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
which is caused by:
Caused by: java.sql.SQLException: Cannot add foreign key constraint
The foreign key problem above is about the "OrderItems" Entity in my database, here is its code:
package com.example.WebAppProcess20.Entities;
import javax.persistence.*;
import java.util.Objects;
#Entity
#Table(name = "ordersitems", schema = "theprocess")
#IdClass(OrdersitemsEntityPK.class)
public class OrdersitemsEntity {
private String orderId;
private String productId;
private Integer qunatity;
private OrdersEntity ordersByOrderId;
#Id
#Column(name = "orderId")
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
#Id
#Column(name = "product_id")
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
#Basic
#Column(name = "qunatity")
public Integer getQunatity() {
return qunatity;
}
public void setQunatity(Integer qunatity) {
this.qunatity = qunatity;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OrdersitemsEntity that = (OrdersitemsEntity) o;
return Objects.equals(orderId, that.orderId) &&
Objects.equals(productId, that.productId) &&
Objects.equals(qunatity, that.qunatity);
}
#Override
public int hashCode() {
return Objects.hash(orderId, productId, qunatity);
}
#ManyToOne
#JoinColumn(name = "orderId", referencedColumnName = "orderId", nullable = false, updatable = false, insertable = false)
public OrdersEntity getOrdersByOrderId() {
return ordersByOrderId;
}
public void setOrdersByOrderId(OrdersEntity ordersByOrderId) {
this.ordersByOrderId = ordersByOrderId;
}
}
This Entity specifies the products included in each order, therefore it has two foreign keys - productId and OrderId.
also adding the pom.xml and hibernate.cfg.xml files if necessary:
hibernate.cfg.xml:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost:3306/theprocess?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC</property>
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- DB schema will be updated if needed -->
<property name="hbm2ddl.auto">update</property>
<mapping class="com.example.WebAppProcess20.Entities.ClientsEntity"/>
<mapping class="com.example.WebAppProcess20.Entities.InvoicesEntity"/>
<mapping class="com.example.WebAppProcess20.Entities.OrdersEntity"/>
<mapping class="com.example.WebAppProcess20.Entities.OrdersitemsEntity"/>
<mapping class="com.example.WebAppProcess20.Entities.ProductsEntity"/>
</session-factory>
</hibernate-configuration>
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>com.example</groupId>
<artifactId>WebAppProcess2.0</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>WebAppProcess2.0</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Can you please explain what the problem is?
Thanks!
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 work on spring boot 2.1.1.RELEASE, hibernate 5.3.7.FINAL
Rules are, that user can have no phone (phone is nullable in user) but, phone can't exist without a user (user is not null in phone).
Entities:
#Entity
public class Phone {
#Id
private Long id;
#OneToOne
#MapsId
#JoinColumn(name = "id")
private User user;
public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(final User user) {
this.user = user;
}
}
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private Phone phone;
public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
public Phone getPhone() {
return phone;
}
public void setPhone(final Phone phone) {
this.phone = phone;
}
}
Controller:
#RestController
#RequestMapping
public class UserController {
private final UserService userService;
public UserController(final UserService userService) {
this.userService = userService;
}
#GetMapping("/demo")
public void createUserAndAddPhone() {
final User user = new User();
userService.save(user);
final Phone phone = new Phone();
phone.setUser(user);
user.setPhone(phone);
userService.update(user);
}
}
Repository:
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
}
Serivce:
#Service
public class UserService {
private final UserRepository userRepository;
public UserService(final UserRepository userRepository) {
this.userRepository = userRepository;
}
#Transactional
public void save(final User user) {
userRepository.save(user);
}
#Transactional
public void update(final User user) {
userRepository.save(user);
}
}
Tables:
CREATE TABLE `phone` (
`id` bigint(20) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
)
application yml:
spring:
datasource:
url: jdbc:mysql://localhost:3308/demo?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false&allowPublicKeyRetrieval=true
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
jpa:
database-platform: org.hibernate.dialect.MySQL5Dialect
hibernate:
ddl-auto: validate
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.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>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.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Call GET http://localhost:8080/demo gives me an error:
org.hibernate.id.IdentifierGenerationException: attempted to assign id
from null one-to-one property [com.example.demo.Phone.user]
When I comment out userService.save(user);, it works and generates:
insert into `user`
values ( )
-- Generated identifier: 13, using strategy: org.hibernate.id.ForeignGenerator
insert into `phone` (`id`) values (?)
-- Binding parameter [1] as [BIGINT] - [13]
but if the user is persisted and then updated, it doesn't work (raises the above exception)
Ah, in the end, this is a hibernate bug (HHH-12436).
It is reproducible in a pure hibernate application by the following use case:
Session session = sessionFactory.openSession();
Transaction tr1 = session.beginTransaction();
User user = new User();
session.persist(user);
tr1.commit();
Transaction tr2 = session.beginTransaction();
Phone newPhone = new Phone();
user.setPhone(newPhone);
newPhone.setUser(user);
session.merge(user);
tr2.commit();
session.close();
As you can see from the above link it is fixed in hibernate 5.4 branch.
P.S. I was able to reproduce the problem in the latest 5.3 version (5.3.18.Final)
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'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>
Am using Hibernate 3 / JPA on Java 6. Am trying to fetch a simple row from the database (which is populated).
Created the following JPA Annotated Domain Object:
#Entity
#Table(name = "person", catalog = "mydatabase", uniqueConstraints = {
#UniqueConstraint(columnNames = "person_name") })
public class Person {
private Integer id;
private String personName;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return id;
}
#Column(name = "person_name", unique = true, nullable = false, length = 30)
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.person = person;
}
}
My hibernate.cfg.xml file:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="current_session_context_class">thread</property>
<mapping class="com.myapp.domain.Person"></mapping>
</session-factory>
</hibernate-configuration>
Code snippet from calling class:
session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
org.hibernate.Query query = session.createQuery("SELECT p FROM Person p");
List<Person> persons = query.getResultList();
When I run the calling class, this is the exception I get:
java.lang.ClassCastException: org.hibernate.impl.QueryImpl cannot be cast to javax.persistence.Query
at com.myapp.PersonApp(PersonApp.java:15)
Line 15 where this ClassCastException occurs is here:
org.hibernate.Query query = session.createQuery("SELECT p FROM Person p");
Here are my dependencies:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.8</version>
</dependency>
<dependency>
<groupId>org.codehaus.mojo</groupId>
<artifactId>hibernate3-maven-plugin</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.6-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.2.0.Final</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.0.0</version>
<scope>provided</scope>
</dependency>
What I am I possibly doing wrong? I just want to call a simple select query against a person table.
Thank you for taking the time to read this.