New to Spring and Hibernate, trying to apply to a simple project what I'm learning from a video course. I'm trying to run a simple client class to test out my setup, and it's not working. Here is my pom.xml 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.kylewalker</groupId>
<artifactId>wellness</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>wellness</name>
<description>A business magagement tool for a wellness organization offering services such as massage, nutrition counseling, etc.</description>
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>1.8.0.10</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat6-maven-plugin</artifactId>
<version>2.1</version>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7></source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.2</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.12.4</version>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.kylewalker.wellness.Main</mainClass>
</configuration></plugin>
</plugins>
</build>
</project>
Here is my hibernate-application.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:file:database.dat;shutdown=true"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<!-- Transaction Manager for the project -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" autowire="byType"/>
<!-- Templates -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate" autowire="byType"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan">
<list>
<value>com.kylewalker.wellness.domain</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<tx:annotation-driven/>
<context:component-scan base-package="com.kylewalker.wellness"/>
Here is my Customer class:
package com.kylewalker.wellness.domain;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Customer {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private Long customerId;
private String firstName;
private String middleName;
private String lastName;
private Date dateOfBirth;
private String address;
private String phone;
private String email;
// no-arg Constructor
public Customer() {}
// Constructor
public Customer(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Long getCustomerId() {
return customerId;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((customerId == null) ? 0 : customerId.hashCode());
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result
+ ((lastName == null) ? 0 : lastName.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Customer other = (Customer) obj;
if (customerId == null) {
if (other.customerId != null)
return false;
} else if (!customerId.equals(other.customerId))
return false;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
return true;
}
#Override
public String toString() {
return "Customer [customerId=" + customerId + ", firstName="
+ firstName + ", lastName=" + lastName + ", dateOfBirth="
+ dateOfBirth + ", address=" + address + ", phone=" + phone
+ ", email=" + email + "]";
}
}
Here is the implementation of the CustomerService class:
package com.kylewalker.wellness.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.kylewalker.wellness.domain.Customer;
import com.kylewalker.wellness.dataaccess.CustomerDao;
import com.kylewalker.wellness.dataaccess.RecordNotFoundException;
#Transactional
#Service
public class CustomerServiceImpl implements CustomerService {
private CustomerDao dao;
#Autowired
public CustomerServiceImpl(CustomerDao dao) {
this.dao = dao;
}
public void newCustomer(Customer newCustomer) {
dao.create(newCustomer);
}
public void updateCustomer(Customer changedCustomer)
throws CustomerNotFoundException {
// TODO Auto-generated method stub
}
public void deleteCustomer(Customer oldCustomer)
throws CustomerNotFoundException {
try {
dao.delete(oldCustomer);
} catch (RecordNotFoundException e) {
throw new CustomerNotFoundException();
}
}
public Customer findCustomerById(String customerId)
throws CustomerNotFoundException {
// TODO Auto-generated method stub
return null;
}
public List<Customer> findCustomersByName(String lastName, String firstName)
throws CustomerNotFoundException {
try {
return dao.getByName(lastName, firstName);
} catch (RecordNotFoundException e) {
throw new CustomerNotFoundException();
}
}
public List<Customer> getAllCustomers() {
return dao.getAllCustomers();
}
}
Here is the implementation of the CustomerDao:
package com.kylewalker.wellness.dataaccess;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.kylewalker.wellness.domain.Customer;
#Repository
#Transactional
public class CustomerDaoHibernateImpl implements CustomerDao {
#Autowired
private HibernateTemplate template;
public void create(Customer customer) {
template.save(customer);
}
public Customer getById(String customerId) throws RecordNotFoundException {
List<Customer> results = (List<Customer>)template.find("from Customer where customerId=?", customerId);
if (results.isEmpty())
throw new RecordNotFoundException();
return results.get(0);
}
public List<Customer> getByName(String lastName, String firstName)
throws RecordNotFoundException {
return (List<Customer>) template.findByNamedParam("from Customer where lastName=? and firstName=?", lastName, firstName);
}
public void update(Customer customerToUpdate)
throws RecordNotFoundException {
// TODO Auto-generated method stub
}
public void delete(Customer oldCustomer) throws RecordNotFoundException {
Customer foundCustomer = template.get(Customer.class, oldCustomer.getCustomerId());
template.delete(foundCustomer);
}
public List<Customer> getAllCustomers() {
return (List<Customer>)template.find("from Customer");
}
}
Here is the Client.java main class I'm running to test it all. (I was trying to do a JUnit test originally but kept having problems, so I figured I'd try testing it this way):
package com.kylewalker.wellness.client;
import java.util.List;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.kylewalker.wellness.domain.Customer;
import com.kylewalker.wellness.services.CustomerService;
public class Client {
public static void main(String[] args) {
ClassPathXmlApplicationContext container = new ClassPathXmlApplicationContext("hibernate-application.xml");
try {
CustomerService customer = container.getBean(CustomerService.class);
Customer c1 = new Customer("Joe", "Smith", "jsmith#gmail.com");
System.out.println(c1);
System.out.println("The customer last name is " + c1.getLastName());
customer.newCustomer(c1);
List<Customer> allCustomers = customer.getAllCustomers();
for (Customer c : allCustomers) {
System.out.println(c);
}
} finally {
container.close();
}
}
}
And finally here is the error trace I'm getting when I run the Client class :
Apr 18, 2014 5:20:44 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#cf9b31d: startup date [Fri Apr 18 17:20:44 MDT 2014]; root of context hierarchy
Apr 18, 2014 5:20:44 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [hibernate-application.xml]
Apr 18, 2014 5:20:45 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Apr 18, 2014 5:20:45 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.4.Final}
Apr 18, 2014 5:20:45 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Apr 18, 2014 5:20:45 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Apr 18, 2014 5:20:45 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.HSQLDialect
Apr 18, 2014 5:20:45 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Apr 18, 2014 5:20:45 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Apr 18, 2014 5:20:45 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Apr 18, 2014 5:20:46 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: drop table Customer if exists
Hibernate: create table Customer (customerId bigint generated by default as identity (start with 1), address varchar(255), dateOfBirth timestamp, email varchar(255), firstName varchar(255), lastName varchar(255), middleName varchar(255), phone varchar(255), primary key (customerId))
Apr 18, 2014 5:20:46 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Customer [customerId=null, firstName=Joe, lastName=Smith, dateOfBirth=null, address=null, phone=null, email=jsmith#gmail.com]
The customer last name is Smith
Hibernate: insert into Customer (customerId, address, dateOfBirth, email, firstName, lastName, middleName, phone) values (null, ?, ?, ?, ?, ?, ?, ?)
Apr 18, 2014 5:20:46 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: -20, SQLState: IM001
Apr 18, 2014 5:20:46 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: This function is not supported
Apr 18, 2014 5:20:46 PM org.springframework.context.support.ClassPathXmlApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext#cf9b31d: startup date [Fri Apr 18 17:20:44 MDT 2014]; root of context hierarchy
Exception in thread "main" org.springframework.orm.hibernate4.HibernateJdbcException: JDBC exception on Hibernate data access: SQLException for SQL [insert into Customer (customerId, address, dateOfBirth, email, firstName, lastName, middleName, phone) values (null, ?, ?, ?, ?, ?, ?, ?)]; SQL state [IM001]; error code [-20]; could not prepare statement; nested exception is org.hibernate.exception.GenericJDBCException: could not prepare statement
at org.springframework.orm.hibernate4.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:168)
at org.springframework.orm.hibernate4.HibernateTemplate.doExecute(HibernateTemplate.java:343)
at org.springframework.orm.hibernate4.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:308)
at org.springframework.orm.hibernate4.HibernateTemplate.save(HibernateTemplate.java:617)
at com.kylewalker.wellness.dataaccess.CustomerDaoHibernateImpl.create(CustomerDaoHibernateImpl.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy16.create(Unknown Source)
at com.kylewalker.wellness.services.CustomerServiceImpl.newCustomer(CustomerServiceImpl.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy18.newCustomer(Unknown Source)
at com.kylewalker.wellness.client.Client.main(Client.java:19)
Caused by: org.hibernate.exception.GenericJDBCException: could not prepare statement
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:196)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareStatement(StatementPreparerImpl.java:122)
at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:55)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:97)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:488)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:193)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:177)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:212)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at org.springframework.orm.hibernate4.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:621)
at org.springframework.orm.hibernate4.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:617)
at org.springframework.orm.hibernate4.HibernateTemplate.doExecute(HibernateTemplate.java:340)
... 31 more
Caused by: java.sql.SQLException: This function is not supported
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.Util.notSupported(Unknown Source)
at org.hsqldb.jdbc.jdbcConnection.prepareStatement(Unknown Source)
at org.apache.commons.dbcp.DelegatingConnection.prepareStatement(DelegatingConnection.java:508)
at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.prepareStatement(PoolingDataSource.java:400)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$2.doPrepare(StatementPreparerImpl.java:124)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:186)
... 55 more
I ran it again with logging turned on (This is the next morning, in response to a viewer's request):
Apr 19, 2014 6:58:39 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#22a866a9: startup date [Sat Apr 19 06:58:39 MDT 2014]; root of context hierarchy
Apr 19, 2014 6:58:40 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [hibernate-application.xml]
Apr 19, 2014 6:58:43 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Apr 19, 2014 6:58:43 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.4.Final}
Apr 19, 2014 6:58:43 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Apr 19, 2014 6:58:43 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Apr 19, 2014 6:58:43 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.HSQLDialect
Apr 19, 2014 6:58:43 AM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Apr 19, 2014 6:58:44 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Apr 19, 2014 6:58:44 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Apr 19, 2014 6:58:44 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: drop table Customer if exists
Hibernate: create table Customer (customerId bigint generated by default as identity (start with 1), address varchar(255), dateOfBirth timestamp, email varchar(255), firstName varchar(255), lastName varchar(255), middleName varchar(255), phone varchar(255), primary key (customerId))
Apr 19, 2014 6:58:44 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Customer [customerId=null, firstName=Joe, lastName=Smith, dateOfBirth=null, address=null, phone=null, email=jsmith#gmail.com]
The customer last name is Smith
Hibernate: insert into Customer (customerId, address, dateOfBirth, email, firstName, lastName, middleName, phone) values (null, ?, ?, ?, ?, ?, ?, ?)
Apr 19, 2014 6:58:45 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: -20, SQLState: IM001
Apr 19, 2014 6:58:45 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: This function is not supported
Apr 19, 2014 6:58:45 AM org.springframework.context.support.ClassPathXmlApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext#22a866a9: startup date [Sat Apr 19 06:58:39 MDT 2014]; root of context hierarchy
And here is the script generated:
CREATE SCHEMA PUBLIC AUTHORIZATION DBA
CREATE MEMORY TABLE CUSTOMER(CUSTOMERID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL PRIMARY KEY,ADDRESS VARCHAR(255),DATEOFBIRTH TIMESTAMP,EMAIL VARCHAR(255),FIRSTNAME VARCHAR(255),LASTNAME VARCHAR(255),MIDDLENAME VARCHAR(255),PHONE VARCHAR(255))
ALTER TABLE CUSTOMER ALTER COLUMN CUSTOMERID RESTART WITH 1
CREATE USER SA PASSWORD ""
GRANT DBA TO SA
SET WRITE_DELAY 10
I'd try with a newer version of hsqldb. The version you have is quite outdated. As the error is raised from the database (function not supported), but the insert statement causing the issue looks fine, I think an update to the new version will do the trick.
You should use EntityManager instead of HibernateTemplate wich is deprecated from Spring 2.5
#Repository
public class GenericService<T> implements IGenericService<T> {
protected EntityManager em;
public EntityManager getEm() {
return em;
}
#PersistenceContext
public void setEm(EntityManager em) {
this.em = em;
}
#Transactional
#Override
public T create(final T t) throws DefaultException{
return this.em.persist(t);
}
...
}
Related
It is necessary to fill the ObservableList by taking data from the table using hibernate, it turns out to be empty, the table is working, it turns out to be empty, the table works,
session open
class Main
public class Main {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
public static void main(String[] args) {
findAll();
}
#SuppressWarnings({"unchecked", "deprecation"})
public static ObservableList<Task> findAll() {
ObservableList<Task> observableTasks = FXCollections.observableArrayList();
Session session = getSessionFactory().openSession();
observableTasks.addAll(session.createCriteria(Task.class).list());
System.out.println("observableTasks = " + observableTasks.isEmpty()); // true empty
session.close();
return observableTasks;
}
public static SessionFactory getSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
}
file hibernate.cfg.xml hibernate configuration class
<?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:sqlite:C:/Users/den/IdeaProjects/TodoListFx/TodoListFx/db/todolist.db-->
<property name="connection.url">jdbc:sqlite:C:/Users/den/IdeaProjects/TodoListFx/TodoListFx/db/todolist.db</property>
<property name="connection.driver_class">org.sqlite.JDBC</property>
<property name="hibernate.show_sql">true</property>
<property name="dialect">org.example.hibernate.dialect.SQLiteDialect</property>
<property name="hibernate.connection.autocommit">true</property>
<mapping class="org.example.test_hibernate_connect_bd.Task"/>
<mapping resource="TodoTask.hbm.xml"/>
<!-- <property name="connection.username"/> -->
<!-- <property name="connection.password"/> -->
<!-- DB schema will be updated if needed -->
<!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
</session-factory>
</hibernate-configuration>
file TodoTask.hbm.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.example.test_hibernate_connect_bd.Task" table="todo" schema="main">
<id name="id">
<column name="id" sql-type="integer"/>
</id>
<property name="task">
<column name="task" sql-type="text"/>
</property>
<property name="time">
<column name="task_create_time" sql-type="text"/>
</property>
<property name="status">
<column name="status" sql-type="text" not-null="true"/>
</property>
</class>
</hibernate-mapping>
class Task the object itself
logs current launch
сент. 30, 2022 8:40:14 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.11.Final}
сент. 30, 2022 8:40:15 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
сент. 30, 2022 8:40:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
сент. 30, 2022 8:40:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.sqlite.JDBC] at URL [jdbc:sqlite:C:/Users/den/IdeaProjects/TodoListFx/TodoListFx/db/todolist.db]
сент. 30, 2022 8:40:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {autocommit=true}
сент. 30, 2022 8:40:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: true
сент. 30, 2022 8:40:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
сент. 30, 2022 8:40:15 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.example.hibernate.dialect.SQLiteDialect
сент. 30, 2022 8:40:16 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
сент. 30, 2022 8:40:16 PM org.hibernate.internal.SessionImpl createCriteria
WARN: HHH90000022: Hibernate's legacy org.hibernate.Criteria API is deprecated; use the JPA javax.persistence.criteria.CriteriaQuery instead
observableTasks = true
project structure
I fill in the list first, because the ObservableList class inherits from extends List , then it gets the same addAll(....) methods. I fill in my ObservableList , list , which I got from the table.
class Main
package org.example;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.example.objects.Task;
import org.example.utils.HibernateSessionFactoryUtil;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static ObservableList<Task> personList = FXCollections.observableArrayList();
public static List<Task> ist = new ArrayList<>();
public static void main(String[] args) {
findAll();
}
#SuppressWarnings({"unchecked", "deprecation"})
public static ObservableList<Task> findAll() {
ist = HibernateSessionFactoryUtil.getSessionFactory().openSession().createQuery("From Task").list();
personList.addAll(ist);
System.out.println("personList.isEmpty() = " + personList.isEmpty());
return personList;
}
}
class HibernateSessionFactoryUtil -> In this class, I create a configuration and add a class to it, with a JPA configuration
package org.example.utils;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateSessionFactoryUtil {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
public HibernateSessionFactoryUtil() {
}
public static SessionFactory getSessionFactory(){
if(sessionFactory == null){
try{
Configuration configuration = new Configuration().configure();
// here necessary class add
configuration.addAnnotatedClass(org.example.objects.Task.class);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
} catch (Exception e) {
System.out.println("Exception !" + e);
}
}
return sessionFactory;
}
}
class Task In this class I put JPA annotations #Entity, #Id, #Column
package org.example.objects;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javax.persistence.*;
#Entity
#Table(name = "todo", schema = "main", catalog = "")
public class Task {
private SimpleIntegerProperty id = new SimpleIntegerProperty();
private SimpleStringProperty task = new SimpleStringProperty("");
private SimpleStringProperty time = new SimpleStringProperty("");
private SimpleStringProperty status = new SimpleStringProperty("");
public Task() {
}
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#Column(name = "id", nullable = false)
public int getId() {
return id.get();
}
public SimpleIntegerProperty idProperty() {
return id;
}
public void setId(int id) {
this.id.set(id);
}
#Basic
#Column(name = "task", nullable = false, length = -1)
public String getTask() {
return task.get();
}
public SimpleStringProperty taskProperty() {
return task;
}
public void setTask(String task) {
this.task.set(task);
}
#Basic
#Column(name = "task_create_time", nullable = false, length = -1)
public String getTime() {
return time.get();
}
public SimpleStringProperty timeProperty() {
return time;
}
public void setTime(String time) {
this.time.set(time);
}
#Basic
#Column(name = "status", nullable = true, length = -1)
public String getStatus() {
return status.get();
}
public SimpleStringProperty statusProperty() {
return status;
}
public void setStatus(String status) {
this.status.set(status);
}
#Override
public String toString() {
return "Task{" +
"id=" + id +
", task=" + task +
", time=" + time +
", status=" + status +
'}';
}
}
the result I wanted to see is that the list is not empty
окт. 01, 2022 8:33:53 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.11.Final}
окт. 01, 2022 8:33:54 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
окт. 01, 2022 8:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
окт. 01, 2022 8:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.sqlite.JDBC] at URL [jdbc:sqlite:C:/Users/den/IdeaProjects/TestHibernate/db/todolist.db]
окт. 01, 2022 8:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {autocommit=true}
окт. 01, 2022 8:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: true
окт. 01, 2022 8:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
окт. 01, 2022 8:33:55 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.example.hibernate.dialect.SQLiteDialect
окт. 01, 2022 8:33:55 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
****Hibernate:
select task0_.id as id1_0_, task0_.status as status2_0_, task0_.task as task3_0_, task0_.task_create_time as task_cre4_0_ from todo task0_
personList.isEmpty() = false**** <----- here result
I am learning Hibernate as a beginner,I am working with maven + hibernate + oracle11g
I am receiving error when i run the following code
Here is the code which i am working on :
Pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wipro.HibernateDemp</groupId>
<artifactId>HibernateDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>HibernateDemo</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.20.0-GA</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.11.Final</version>
<type>pom</type>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impl -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc6 -->
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.4</version>
</dependency>
</dependencies>
</project>
Department.java
package com.hibernate.bean;
import org.hibernate.Hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Department
{
private int depno;
private String depName;
private int locationid;
private int managerid;
public Department() {
}
public Department(int depno, String depName, int locationid, int managerid) {
super();
this.depno = depno;
this.depName = depName;
this.locationid = locationid;
this.managerid = managerid;
}
public int getDepno() {
return depno;
}
public void setDepno(int depno) {
this.depno = depno;
}
public String getDepName() {
return depName;
}
public void setDepName(String depName) {
this.depName = depName;
}
public int getLocationid() {
return locationid;
}
public void setLocationid(int locationid) {
this.locationid = locationid;
}
public int getManagerid() {
return managerid;
}
public void setManagerid(int managerid) {
this.managerid = managerid;
}
#Override
public String toString() {
return "Department [depno=" + depno + ", depName=" + depName + ", locationid=" + locationid + ", managerid="
+ managerid + "]";
}
}
DepartmentAdmin.java
package com.wipro.services;
import javax.transaction.Transaction;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.hibernate.bean.Department;
public class DepartmentAdmin {
public static void main(String args[]) {
Configuration cfg = new Configuration().configure();
SessionFactory sf = cfg.buildSessionFactory();
Session session =sf.openSession();
org.hibernate.Transaction transaction = session.beginTransaction();
Department deptobj = new Department(280,"CSE", 116,1830);
session.save(deptobj);
transaction.commit();
System.out.println("Record inserted");
System.out.println(deptobj);
session.close();
}
}
department.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.wipro.bean.Department" table="Departments">
<id name="depno" column="DEPARTMENT_ID" type="int">
<generator class="assigned"></generator>
</id>
<property name="depName" column="DEPARTMENT_NAME" type="string"></property>
<property name="locationid" column="LOCATION_ID" type="int"></property>
<property name="managerid" column="MANAGER_ID" type="int"></property>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name="hibernate.connection.username">hr</property>
<property name="hibernate.connection.password">hr</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle8iDialect</property>
<property name="hibernateshow_sql">true</property>
<mapping resource="department.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I am receiving the following when i run the code:
May 28, 2022 11:58:17 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.11.Final}
May 28, 2022 11:58:17 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
May 28, 2022 11:58:17 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
May 28, 2022 11:58:17 AM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
May 28, 2022 11:58:17 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
May 28, 2022 11:58:17 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [oracle.jdbc.OracleDriver] at URL [jdbc:oracle:thin:#localhost:1521:xe]
May 28, 2022 11:58:17 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=hr}
May 28, 2022 11:58:17 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
May 28, 2022 11:58:17 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
May 28, 2022 11:58:18 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle8iDialect
May 28, 2022 11:58:18 AM org.hibernate.search.engine.Version <clinit>
INFO: HSEARCH000034: Hibernate Search 5.8.0.Final
May 28, 2022 11:58:18 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 2291, SQLState: 23000
May 28, 2022 11:58:18 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ORA-02291: integrity constraint (HR.DEPT_MGR_FK) violated - parent key not found
May 28, 2022 11:58:18 AM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
May 28, 2022 11:58:18 AM org.hibernate.internal.ExceptionMapperStandardImpl mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:149)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:164)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1443)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:493)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3207)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2413)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:156)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:231)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
at com.wipro.services.DepartmentAdmin.main(DepartmentAdmin.java:19)
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:178)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3013)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3513)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:589)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1437)
... 9 more
Caused by: java.sql.SQLIntegrityConstraintViolationException: ORA-02291: integrity constraint (HR.DEPT_MGR_FK) violated - parent key not found
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:208)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1046)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1336)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3613)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3694)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1354)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)
... 18 more
Table departments structure:
Name | Null? | Type |
:---------------|:--------:| ------------ :|
DEPARTMENT_ID | NOT NULL | NUMBER(4) |
DEPARTMENT_NAME | NOT NULL |VARCHAR2(30) |
MANAGER_ID | |NUMBER(6) |
LOCATION_ID | | NUMBER(4) |
I have no idea what is happening here...anyhelp is most welcomed...
The problem is that you didn't map the association correctly. Given the name of the table and constraint, I think there's not a manager matching the id you have specified.
A relationship between Department and Manager (assuming a department has only one manager) should look something like:
#Entity
public class Department {
....
#ManyToOne // Assuming a manager can manage multiple departments
Manager manager;
}
#Entity
public class Manager {
// ... id, fields, getters/setters
}
I've used annotations because I find it easier (and probably more common) but you can do the same with XML.
I would suggest to check the Hibernate ORM documentation to figure out how to map associations.
I'm trying to use Hibernate in order to get data from MySQL database. In order to achieve such a goal, I have created:
Hibernate configuration file:
<?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="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/employeesDbAF
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.pool_size">50</property>
<property name="show_sql">true</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.hbm2ddl.auto">validate</property>
<mapping class="employeesapp.Employee"></mapping>
</session-factory>
</hibernate-configuration>
Utility class
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
public static SessionFactory createSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
//sessionFactory = configuration.buildSessionFactory(serviceRegistry);
sessionFactory = configuration.buildSessionFactory();
return sessionFactory;
}
public static void close() {
StandardServiceRegistryBuilder.destroy(serviceRegistry);
}
}
Main class:
public class EmployeesApp extends javax.swing.JFrame {
public static void main(String[] args) {
Session session = HibernateUtil.createSessionFactory().openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Employee emp = (Employee)session.get(Employee.class, 2);
System.out.println(emp);
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
System.out.println(e);
} finally {
HibernateUtil.close();
}
}
EDIT:
4. Employee class:
#Entity
#Table(name="employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="employee_ID")
private int employee_ID;
#Column(name="name")
private String name;
#Column(name="age")
private int age;
#Column(name="address")
private String address;
#Column(name="salary")
private int salary;
public int getEmployee_ID() {return employee_ID;}
public void setEmployee_ID(int employee_ID) {this.employee_ID = employee_ID; }
public String getName() {return name; }
public void setName(String name) {this.name = name; }
public int getAge() {return age;}
public void setAge(int age) {this.age = age; }
public String getAddress() {return address; }
public void setAddress(String address) {this.address = address; }
public int getSalary() {return salary; }
public void setSalary(int salary) {this.salary = salary; }
public Employee(int employee_ID, String name, int age, String address, int salary) {
//this.employee_ID = employee_ID;
this.name = name;
this.age = age;
this.address = address;
this.salary = salary;
}
public Employee(){
}
}
When it comes to run code, I'm not getting row from the database, just some generic SELECT clause (last row).
What am I doing wrong?
run:
Jun 05, 2019 10:53:26 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Jun 05, 2019 10:53:26 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.1.Final}
Jun 05, 2019 10:53:26 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jun 05, 2019 10:53:26 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jun 05, 2019 10:53:26 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Jun 05, 2019 10:53:26 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Jun 05, 2019 10:53:26 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Jun 05, 2019 10:53:26 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Jun 05, 2019 10:53:26 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/employeesDbAF]
Jun 05, 2019 10:53:26 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
Jun 05, 2019 10:53:26 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Jun 05, 2019 10:53:26 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 50 (min=1)
Jun 05, 2019 10:53:27 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Jun 05, 2019 10:53:27 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Jun 05, 2019 10:53:27 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Jun 05, 2019 10:53:27 PM org.hibernate.tool.hbm2ddl.SchemaValidator validate
INFO: HHH000229: Running schema validator
Jun 05, 2019 10:53:27 PM org.hibernate.tool.hbm2ddl.SchemaValidator validate
INFO: HHH000102: Fetching database metadata
Jun 05, 2019 10:53:27 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: employeesDbAF.employee
Jun 05, 2019 10:53:27 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [address, employee_id, name, salary, age]
**Hibernate: select employee0_.employee_ID as employee1_0_0_, employee0_.address as address2_0_0_, employee0_.age as age3_0_0_, employee0_.name as name4_0_0_, employee0_.salary as salary5_0_0_ from employee employee0_ where employee0_.employee_ID=?
employeesapp.Employee#53b7f657**
You have to override public String toString() method in Employee class.
#Override
public String toString() {
return "Employee{" +
"employee_ID=" + employee_ID +
", name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
", salary=" + salary +
'}';
}
System.out.println(emp); method just print to console the toString() method return value
Employee#53b7f657
Internally it will call,
// java.io.PrintStream
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
// java.lang.String
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
And the implementation of that method in Object class is
// java.lang.Object
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
So, if you do not have a 'custom' public String toString() on your class, that's what you will see because of every class is implicitly a subclass of Object.
Excepting Object, which has no superclass, every class has one and
only one direct superclass (single inheritance). In the absence of any
other explicit superclass, every class is implicitly a subclass of
Object.
Source https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
I'm learning Hibernate, and during simple demo application, I encounter problem, I can't overcame. There are only two tables, two entity classes and main app. Project is in maven.
Github: github.com/fangirsan/maruszka.git
Batch.class:
package com.maruszka.entity;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="batch")
public class Batch {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="batch_number")
private int batchNumber;
#Column(name="batch_style")
private String batchStyle;
#Column(name="batch_name")
private String batchName;
#Column(name="batch_creation_date", columnDefinition="DATE")
#Temporal(TemporalType.TIMESTAMP)
private Date batchCreationDate;
#ManyToMany(fetch=FetchType.LAZY,
cascade= {CascadeType.PERSIST, CascadeType.MERGE,
CascadeType.DETACH, CascadeType.REFRESH})
#JoinTable(
name="batch_malt",
joinColumns=#JoinColumn(name="batch_id"),
inverseJoinColumns=#JoinColumn(name="malt_id")
)
private List<Malt> malts;
public Batch() {
}
public Batch(int batchNumber, String batchStyle, String batchName, Date batchCreationDate) {
this.batchNumber = batchNumber;
this.batchStyle = batchStyle;
this.batchName = batchName;
this.batchCreationDate = batchCreationDate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getBatchNumber() {
return batchNumber;
}
public void setBatchNumber(int batchNumber) {
this.batchNumber = batchNumber;
}
public String getBatchStyle() {
return batchStyle;
}
public void setBatchStyle(String batchStyle) {
this.batchStyle = batchStyle;
}
public String getBatchName() {
return batchName;
}
public void setBatchName(String batchName) {
this.batchName = batchName;
}
public Date getBatchCreationDate() {
return batchCreationDate;
}
public void setBatchCreationDate(Date batchCreationDate) {
this.batchCreationDate = batchCreationDate;
}
public List<Malt> getMalts() {
return malts;
}
public void setMalts(List<Malt> malts) {
this.malts = malts;
}
#Override
public String toString() {
return "Batch [id=" + id + ", batchNumber=" + batchNumber + ", batchStyle=" + batchStyle + ", batchName="
+ batchName + ", batchCreationDate=" + batchCreationDate + ", malts=" + malts + "]";
}
// add a convenience method
public void addMalt(Malt theMalt) {
if (malts == null) {
malts = new ArrayList<>();
}
malts.add(theMalt);
}
}
Malt.class
package com.maruszka.entity;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="malt")
public class Malt {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="malt_name")
private String maltName;
#Column(name="malt_manufacturer")
private String maltManufacturer;
#Column(name="filling")
private int filling;
#Column(name="ebc")
private int ebc;
#Column(name="usage")
private String usage;
#ManyToMany(fetch=FetchType.LAZY,
cascade= {CascadeType.PERSIST, CascadeType.MERGE,
CascadeType.DETACH, CascadeType.REFRESH})
#JoinTable(
name="batch_malt",
joinColumns=#JoinColumn(name="malt_id"),
inverseJoinColumns=#JoinColumn(name="batch_id")
)
private List<Batch> batches;
public Malt() {
}
public Malt(String maltName, String maltManufacturer, int filling, int ebc, String usage) {
this.maltName = maltName;
this.maltManufacturer = maltManufacturer;
this.filling = filling;
this.ebc = ebc;
this.usage = usage;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMaltName() {
return maltName;
}
public void setMaltName(String maltName) {
this.maltName = maltName;
}
public String getMaltManufacturer() {
return maltManufacturer;
}
public void setMaltManufacturer(String maltManufacturer) {
this.maltManufacturer = maltManufacturer;
}
public int getFilling() {
return filling;
}
public void setFilling(int filling) {
this.filling = filling;
}
public int getEbc() {
return ebc;
}
public void setEbc(int ebc) {
this.ebc = ebc;
}
public String getUsage() {
return usage;
}
public void setUsage(String usage) {
this.usage = usage;
}
public List<Batch> getBatches() {
return batches;
}
public void setBatches(List<Batch> batches) {
this.batches = batches;
}
#Override
public String toString() {
return "Malt [id=" + id + ", maltName=" + maltName + ", maltManufacturer=" + maltManufacturer + ", filling="
+ filling + ", ebc=" + ebc + ", usage=" + usage + ", batches=" + batches + "]";
}
}
CreateBatchAndMalt.class (main):
package com.maruszka.test;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.maruszka.entity.Malt;
import com.maruszka.entity.Batch;
public class CreateBatchAndMalt {
public static void main(String[] args) {
// create session factory
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Batch.class)
.addAnnotatedClass(Malt.class)
.buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
try {
// start a transaction
session.beginTransaction();
// create a malt
Malt tempMalt = new Malt("Carafa (R) typ I", "Weyerman", 10, 900, "Stout, Porter, Schwarzbier");
// save the malt
System.out.println("\nSaving the malt ...");
session.save(tempMalt);
System.out.println("Saved the malt: " + tempMalt);
// create the batch
Date now = new Date();
Batch tempBatch = new Batch(2, "Mild", "Szatan", now);
// add malt to the batch
tempBatch.addMalt(tempMalt);
// save the batch
System.out.println("\nSaving batch ...");
session.save(tempBatch);
System.out.println("Saved batch: " + tempBatch.getMalts());
// commit transaction
session.getTransaction().commit();
System.out.println("Done!");
}
finally {
// close session
session.close();
factory.close();
}
}
}
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.maruszka</groupId>
<artifactId>maruszka</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>maruszka Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<springframework.version>5.0.2.RELEASE</springframework.version>
<springsecurity.version>5.0.1.RELEASE</springsecurity.version>
<hibernate.version>5.3.1.Final</hibernate.version>
<!-- 5.2.12.Final -->
<mysql.connector.version>5.1.38</mysql.connector.version>
<c3po.version>0.9.5.2</c3po.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- Add support for JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Spring MVC support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Add support for Spring Tags -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<!-- Hibernate Core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.4.Final</version>
</dependency>
<!-- Add MySQL and C3P0 support -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
<!-- dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency-->
</dependencies>
<build>
<!-- TO DO: Add support for Maven WAR Plugin -->
<finalName>maruszka</finalName>
<pluginManagement>
<plugins>
<plugin>
<!-- Add Maven coordinates for: maven-war-plugin -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
hibernate.cfg.xml (in maruszka\src\main\resources\hibernate.cfg.xml):
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/maruszka?serverTimezone=UTC</property>
<!-- &useSSL=false -->
<property name="connection.username">***</property>
<property name="connection.password">***</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">false</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
DB script:
CREATE DATABASE IF NOT EXISTS `maruszka`;
USE `maruszka`;
SET FOREIGN_KEY_CHECKS=0;
-- batch
DROP TABLE IF EXISTS `batch`;
CREATE TABLE `batch` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`batch_number` int(3) NOT NULL,
`batch_style` varchar(45) DEFAULT NULL,
`batch_name` varchar(45) DEFAULT NULL,
`batch_creation_date` DATE,
PRIMARY KEY (`id`),
UNIQUE KEY(`batch_number`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
LOCK TABLE `batch` WRITE;
INSERT INTO `batch` VALUES
(1, 1, 'Stout', 'Happy Stout', '2018-06-06');
UNLOCK TABLES;
-- malt
DROP TABLE IF EXISTS `malt`;
CREATE TABLE `malt` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`malt_name` varchar(45) DEFAULT NULL,
`malt_manufacturer` varchar(45) DEFAULT NULL,
`filling` int(3) DEFAULT NULL,
`ebc` int(3) DEFAULT NULL,
`usage` varchar(254) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY(`malt_name`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
LOCK TABLES `malt` WRITE;
INSERT INTO `malt` VALUES
(1, 'Pale Ale', 'Malteurop', 100, 6, 'All');
UNLOCK TABLES;
-- join table for batch - malt
DROP TABLE IF EXISTS `batch-malt`;
CREATE TABLE `batch-malt` (
`batch_id` int(11) NOT NULL,
`malt_id` int(11) NOT NULL,
PRIMARY KEY (`batch_id`, `malt_id`),
-- fk_[referencing table name]_[referenced table name]_[referencing field name]
CONSTRAINT `FK_BATCH_MALT_ID` FOREIGN KEY (`malt_id`)
REFERENCES `malt` (`id`)
ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_MALT_BATCH_ID` FOREIGN KEY (`batch_id`)
REFERENCES `batch` (`id`)
ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
SET FOREIGN_KEY_CHECKS=1;
When using mysql connector in version 8.0.11:
cze 06, 2018 9:33:53 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.3.1.Final}
cze 06, 2018 9:33:53 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
cze 06, 2018 9:33:53 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.3.Final}
cze 06, 2018 9:33:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
cze 06, 2018 9:33:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/maruszka?serverTimezone=UTC]
cze 06, 2018 9:33:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
cze 06, 2018 9:33:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
cze 06, 2018 9:33:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Wed Jun 06 21:33:53 CEST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
cze 06, 2018 9:33:53 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
cze 06, 2018 9:33:54 PM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 6.0.4.Final
Saving the malt ...
cze 06, 2018 9:33:54 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1064, SQLState: 42000
cze 06, 2018 9:33:54 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'usage) values (900, 10, 'Weyerman', 'Carafa (R) typ I', 'Stout, Porter, Schwarzb' at line 1
cze 06, 2018 9:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/maruszka?serverTimezone=UTC]
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:178)
at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3037)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3628)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:645)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:282)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:317)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:359)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:292)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:200)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:131)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:709)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:701)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:696)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:349)
at com.sun.proxy.$Proxy36.save(Unknown Source)
at com.maruszka.test.CreateBatchAndMalt.main(CreateBatchAndMalt.java:42)
Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'usage) values (900, 10, 'Weyerman', 'Carafa (R) typ I', 'Stout, Porter, Schwarzb' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:118)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:960)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1116)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1066)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1396)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1051)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)
... 28 more
I've double check syntax, but can't figure out wha is causing this:
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'usage) values (900, 10, 'Weyerman', 'Carafa (R) typ I', 'Stout, Porter, Schwarzb' at line 1
Best regards
In your sql table malt you have a column named usage and that name is a reserved word in MySQL so that is why your insert query doesn't work.
The easiest way forward is to change the name to something else, for instance malt_usage
So this will not work:
INSERT INTO malt(filling, ebc, malt_manufacturer, malt_name, usage)
VALUES (900, 10, 'Weyerman', 'Carafa (R) typ I', 'Stout, Porter, Schwarzb')
but this will
INSERT INTO malt(filling, ebc, malt_manufacturer, malt_name, malt_usage)
VALUES (900, 10, 'Weyerman', 'Carafa (R) typ I', 'Stout, Porter, Schwarzb')
In java this is not a problem so there you can keep the name usage if you want
#Column(name="malt_usage")
private String usage;
The literal usage is a keyword in mysql.
https://dev.mysql.com/doc/refman/8.0/en/keywords.html#keywords-8-0-detailed-U
Simplest solution is to simply change the column name to another (non-keyword) term.
Otherwise, try setting
hibernate.auto_quote_keyword=true
I'm trying to set up a small working sample of JPA, however when I run the code I get the follwing error:
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import encje.Klient;
import encje.Zamowienie;
public class SzkolenieJPA {
public static void main(String[] args) {
EntityManagerFactory fabryka = Persistence.createEntityManagerFactory("jpaHibernateTest");
EntityManager menadzer = fabryka.createEntityManager();
Klient przykladowy = menadzer.find(Klient.class, 1);
for(Zamowienie z : przykladowy.getZamowienia())
System.out.println(z.getAdres() + " "+ z.getData() + " "+ przykladowy.getNazwisko());
menadzer.close();
}
}
package encje;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.persistence.*;
#Entity
#Table(name="klient")
public class Klient {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="imie", length=50, nullable=false)
private String imie;
#Column(name="nazwisko", length=50, nullable=false)
private String nazwisko;
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="klient")
private Set<Zamowienie> zamowienia;
public Klient(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getImie() {
return imie;
}
public void setImie(String imie) {
this.imie = imie;
}
public String getNazwisko() {
return nazwisko;
}
public void setNazwisko(String nazwisko) {
this.nazwisko = nazwisko;
}
public Set<Zamowienie> getZamowienia() {
return zamowienia;
}
public void setZamowienia(Set<Zamowienie> zamowienia) {
this.zamowienia = zamowienia;
}
}
package encje;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.*;
import javax.persistence.Table;
#Entity
#Table(name="zamowienie")
public class Zamowienie {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="data")
#Temporal(TemporalType.DATE)
private Date data;
#Column(name="imie", length=50)
private String adres;
#ManyToOne
#JoinColumn(name="klient", nullable=false)
private Klient klient;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public String getAdres() {
return adres;
}
public void setAdres(String adres) {
this.adres = adres;
}
public Klient getKlient() {
return klient;
}
public void setKlient(Klient klient) {
this.klient = klient;
}
}
persistence.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="jpaHibernateTest" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.connection.url" value="jdbc:mysql://localhost/szkolenie" />
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
CREATE TABLE IF NOT EXISTS `klient` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`imie` varchar(50) COLLATE utf8_polish_ci NOT NULL,
`nazwisko` varchar(50) COLLATE utf8_polish_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=4 ;
INSERT INTO `klient` (`id`, `imie`, `nazwisko`) VALUES
(1, 'janek', 'kowalski'),
(2, 'marian', 'nowak'),
(3, 'andrzej', 'nowak');
CREATE TABLE IF NOT EXISTS `zamowienie` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`data` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`adres` text NOT NULL,
`klient` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `klient_zamowienie` (`klient`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
INSERT INTO `zamowienie` (`id`, `data`, `adres`, `klient`) VALUES
(1, '2014-06-13 14:45:54', 'Adres', 1),
(2, '2014-06-14 11:58:43', 'zamowienie mariana nowaka', 2),
(3, '2014-06-02 08:31:22', 'zamowienie andrzeja nowaka', 3),
(4, '2014-06-14 11:59:11', 'zamowienie andrzeja nowaka nr 2', 3);
my errors:
juin 14, 2014 7:51:22 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
juin 14, 2014 7:51:22 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
juin 14, 2014 7:51:22 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
juin 14, 2014 7:51:22 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
name: jpaHibernateTest
...]
juin 14, 2014 7:51:22 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
juin 14, 2014 7:51:22 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
juin 14, 2014 7:51:22 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
juin 14, 2014 7:51:22 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
juin 14, 2014 7:51:22 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
juin 14, 2014 7:51:22 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/szkolenie]
juin 14, 2014 7:51:22 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
juin 14, 2014 7:51:22 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
juin 14, 2014 7:51:22 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
juin 14, 2014 7:51:23 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
juin 14, 2014 7:51:23 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
juin 14, 2014 7:51:23 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
juin 14, 2014 7:51:23 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1054, SQLState: 42S22
juin 14, 2014 7:51:23 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Unknown column 'zamowienia1_.imie' in 'field list'
juin 14, 2014 7:51:23 PM org.hibernate.event.internal.DefaultLoadEventListener onLoad
INFO: HHH000327: Error performing load command : org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1694)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:1141)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:1068)
at SzkolenieJPA.main(SzkolenieJPA.java:15)
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:89)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.getResultSet(AbstractLoadPlanBasedLoader.java:449)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeQueryStatement(AbstractLoadPlanBasedLoader.java:202)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:137)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:102)
at org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.load(AbstractLoadPlanBasedEntityLoader.java:186)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4126)
at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:502)
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:467)
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:212)
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:274)
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:150)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1070)
at org.hibernate.internal.SessionImpl.access$2000(SessionImpl.java:176)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2551)
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:955)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:1110)
... 2 more
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Unknown column 'zamowienia1_.imie' in 'field list'
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3283)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1332)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1467)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:80)
... 18 more
some suggestions or little bit of help please
The problem is with the entity Zamowienie you are mapping the field adres to a column named imie:
#Column(name="imie", length=50)
private String adres;
I think it should be:
#Column(name="adres", length=50)
private String adres;