When i query ` the sql bellow the error keep showing
search = session.createQuery("FROM QLKH_DTO a WHERE a.Fullname LIKE :temp", QLKH_DTO.class)
.setParameter("temp",temp)
.list();
However if it just like this then it does work
search = session.createQuery("FROM QLKH_DTO", QLKH_DTO.class)
.list();
Here my entity class QLKH_DTO
package DTO;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
#Entity
#Table(name = "customers", catalog = "market")
public class QLKH_DTO implements java.io.Serializable {
private Integer CustomerID;
private String Password;
private String Fullname;
private String Address;
private String City;
public QLKH_DTO(){}
public QLKH_DTO(String Password,String Fullname, String Address, String City) {
this.Password = Password;
this.Fullname = Fullname;
this.Address = Address;
this.City = City;
}
#Id
#GeneratedValue(strategy =GenerationType.IDENTITY)
#Column(name = "CustomerID")
public Integer getCustomerID() {
return CustomerID;
}
public void setCustomerID(Integer CustomerID) {
this.CustomerID = CustomerID;
}
#Column(name = "Password")
public String getPassword() {
return Password;
}
public void setPassword(String Password) {
this.Password = Password;
}
#Column(name = "Fullname")
public String getFullname() {
return Fullname;
}
public void setFullname(String Fullname) {
this.Fullname = Fullname;
}
#Column(name = "Address", length = 20)
public String getAddress() {
return Address;
}
public void setAddress(String Address) {
this.Address = Address;
}
#Column(name = "City", length = 20)
public String getCity() {
return City;
}
public void setCity(String City) {
this.City = City;
}
}
The HibernateUtil class
package utils;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
public static SessionFactory buildSessionFactory() {
try {
ServiceRegistry serviceRegistry;
serviceRegistry = new StandardServiceRegistryBuilder()
.configure()
.build();
Metadata metadata = new MetadataSources(serviceRegistry)
.getMetadataBuilder().build();
return metadata.getSessionFactoryBuilder().build();
} catch (Throwable ex) {
}
return sessionFactory;
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
;
The test class
package GUI.QLKH;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import DTO.QLKH_DTO;
import java.util.List;
import utils.HibernateUtil;
public class QLKH {
private static SessionFactory factory;
Session session=null;
// Transaction txn = null;
public static void main(String[] args) {
factory = HibernateUtil.getSessionFactory();
QLKH Customer = new QLKH();
System.out.println("search customers:");
Customer.search();
}
public void search(){
String temp="John";
session = factory.openSession();
session.beginTransaction();
List<QLKH_DTO> search;
search = session.createQuery("FROM QLKH_DTO a WHERE a.Fullname LIKE :temp", QLKH_DTO.class)
.setParameter("temp",temp)
.list();
session.getTransaction().commit();
for (QLKH_DTO customer : search) {
System.out.print("Password: " + customer.getPassword());
System.out.print("Fullname: " + customer.getFullname());
System.out.println("Address: " + customer.getAddress());
System.out.println("City: " + customer.getCity());
}
}
}
The sql
CREATE TABLE `Customers` (
`CustomerID` int(10) NOT NULL auto_increment,
`Password` varchar(20) NOT NULL,
`Fullname` varchar(40) NOT NULL,
`Address` varchar(50) DEFAULT NULL,
`City` varchar(20) DEFAULT NULL,
PRIMARY KEY (CustomerID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `Customers`
--
INSERT INTO `Customers` (`CustomerID`, `Password`, `Fullname`, `Address`, `City`) VALUES
(1, 'Abcd1234', 'John Smith', '30 Broadway', 'London'),
(2, 'Abcd1234', 'Jonny English', '99 River View', 'Reading'),
(3, 'Abcd1234', 'Elizabeth', '23 Buckinghamshire', 'York'),
(4, 'Abcd1234', 'Beatrix', '66 Royal Crescent', 'Bath');
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.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name = "hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- Assume students is the database name -->
<property name = "hibernate.connection.url">
jdbc:mysql://localhost:3306/market
</property>
<property name = "hibernate.connection.username">
root
</property>
<property name = "hibernate.connection.password">
</property>
<mapping class="DTO.QLKH_DTO" />
</session-factory>
</hibernate-configuration>
And the error log
cd C:\Users\MyPC\Documents\NetBeansProjects\QLKH; "JAVA_HOME=C:\\Program Files\\Java\\jdk-14.0.1" cmd /c "\"C:\\Program Files\\NetBeans-15\\netbeans\\java\\maven\\bin\\mvn.cmd\" -Dexec.vmArgs= \"-Dexec.args=${exec.vmArgs} -classpath %classpath ${exec.mainClass} ${exec.appArgs}\" \"-Dexec.executable=C:\\Program Files\\Java\\jdk-14.0.1\\bin\\java.exe\" -Dexec.mainClass=GUI.QLKH.QLKH -Dexec.classpathScope=runtime -Dexec.appArgs= \"-Dmaven.ext.class.path=C:\\Program Files\\NetBeans-15\\netbeans\\java\\maven-nblib\\netbeans-eventspy.jar\" -Dfile.encoding=UTF-8 org.codehaus.mojo:exec-maven-plugin:3.0.0:exec"
Running NetBeans Compile On Save execution. Phase execution is skipped and output directories of dependency projects (with Compile on Save turned on) will be used instead of their jar artifacts.
Scanning for projects...
------------------------------< GUI:QLKH >------------------------------
Building QLKH 1.0
--------------------------------[ jar ]---------------------------------
--- exec-maven-plugin:3.0.0:exec (default-cli) # QLKH ---
Nov 22, 2022 9:55:29 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 6.1.5.Final
Nov 22, 2022 9:55:31 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using built-in connection pool (not intended for production use)
Nov 22, 2022 9:55:31 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: Loaded JDBC driver class: com.mysql.jdbc.Driver
Nov 22, 2022 9:55:31 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001012: Connecting with JDBC URL [jdbc:mysql://localhost:3306/market]
Nov 22, 2022 9:55:31 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=root}
Nov 22, 2022 9:55:31 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Nov 22, 2022 9:55:31 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH10001115: Connection pool size: 20 (min=1)
Nov 22, 2022 9:55:32 AM org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl logSelectedDialect
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Nov 22, 2022 9:55:35 AM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
search customers:
Exception in thread "main" java.lang.IllegalArgumentException: org.hibernate.query.sqm.InterpretationException: Error interpreting query [FROM QLKH_DTO a WHERE a.Fullname LIKE :temp]; this may indicate a semantic (user query) problem or a bug in the parser [FROM QLKH_DTO a WHERE a.Fullname LIKE :temp]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:141)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:175)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:182)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:761)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:127)
at GUI.QLKH.QLKH.search(QLKH.java:28)
at GUI.QLKH.QLKH.main(QLKH.java:21)
Caused by: org.hibernate.query.sqm.InterpretationException: Error interpreting query [FROM QLKH_DTO a WHERE a.Fullname LIKE :temp]; this may indicate a semantic (user query) problem or a bug in the parser [FROM QLKH_DTO a WHERE a.Fullname LIKE :temp]
at org.hibernate.query.hql.internal.StandardHqlTranslator.translate(StandardHqlTranslator.java:97)
at org.hibernate.internal.AbstractSharedSessionContract.lambda$createQuery$2(AbstractSharedSessionContract.java:748)
at org.hibernate.query.internal.QueryInterpretationCacheStandardImpl.createHqlInterpretation(QueryInterpretationCacheStandardImpl.java:141)
at org.hibernate.query.internal.QueryInterpretationCacheStandardImpl.resolveHqlInterpretation(QueryInterpretationCacheStandardImpl.java:128)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:745)
... 3 more
Caused by: java.lang.IllegalArgumentException: org.hibernate.query.SemanticException: Could not resolve attribute 'Fullname' of 'DTO.QLKH_DTO'
at org.hibernate.query.sqm.SqmPathSource.getSubPathSource(SqmPathSource.java:61)
at org.hibernate.query.sqm.tree.domain.AbstractSqmPath.get(AbstractSqmPath.java:160)
at org.hibernate.query.sqm.tree.domain.AbstractSqmFrom.resolvePathPart(AbstractSqmFrom.java:192)
at org.hibernate.query.hql.internal.DomainPathPart.resolvePathPart(DomainPathPart.java:42)
at org.hibernate.query.hql.internal.BasicDotIdentifierConsumer.consumeIdentifier(BasicDotIdentifierConsumer.java:91)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitSimplePath(SemanticQueryBuilder.java:4808)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitIndexedPathAccessFragment(SemanticQueryBuilder.java:4755)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitGeneralPathFragment(SemanticQueryBuilder.java:4724)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitGeneralPathExpression(SemanticQueryBuilder.java:1423)
at org.hibernate.grammars.hql.HqlParser$GeneralPathExpressionContext.accept(HqlParser.java:6963)
at org.antlr.v4.runtime.tree.AbstractParseTreeVisitor.visitChildren(AbstractParseTreeVisitor.java:46)
at org.hibernate.grammars.hql.HqlParserBaseVisitor.visitBarePrimaryExpression(HqlParserBaseVisitor.java:671)
at org.hibernate.grammars.hql.HqlParser$BarePrimaryExpressionContext.accept(HqlParser.java:6437)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitLikePredicate(SemanticQueryBuilder.java:2217)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitLikePredicate(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$LikePredicateContext.accept(HqlParser.java:5442)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitWhereClause(SemanticQueryBuilder.java:1949)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitWhereClause(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$WhereClauseContext.accept(HqlParser.java:5290)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitQuery(SemanticQueryBuilder.java:857)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitQuerySpecExpression(SemanticQueryBuilder.java:629)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitQuerySpecExpression(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$QuerySpecExpressionContext.accept(HqlParser.java:1218)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitSimpleQueryGroup(SemanticQueryBuilder.java:623)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitSimpleQueryGroup(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$SimpleQueryGroupContext.accept(HqlParser.java:1131)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitSelectStatement(SemanticQueryBuilder.java:399)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitStatement(SemanticQueryBuilder.java:358)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.buildSemanticModel(SemanticQueryBuilder.java:285)
at org.hibernate.query.hql.internal.StandardHqlTranslator.translate(StandardHqlTranslator.java:81)
... 7 more
Caused by: org.hibernate.query.SemanticException: Could not resolve attribute 'Fullname' of 'DTO.QLKH_DTO'
... 37 more
Command execution failed.
org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1)
at org.apache.commons.exec.DefaultExecutor.executeInternal (DefaultExecutor.java:404)
at org.apache.commons.exec.DefaultExecutor.execute (DefaultExecutor.java:166)
at org.codehaus.mojo.exec.ExecMojo.executeCommandLine (ExecMojo.java:982)
at org.codehaus.mojo.exec.ExecMojo.executeCommandLine (ExecMojo.java:929)
at org.codehaus.mojo.exec.ExecMojo.execute (ExecMojo.java:457)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
at org.apache.maven.lifecycle.internal.MojoExecutor.doExecute2 (MojoExecutor.java:370)
at org.apache.maven.lifecycle.internal.MojoExecutor.doExecute (MojoExecutor.java:351)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:171)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:163)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:294)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
at org.apache.maven.cli.MavenCli.execute (MavenCli.java:960)
at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:293)
at org.apache.maven.cli.MavenCli.main (MavenCli.java:196)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:564)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------
Total time: 12.026 s
Finished at: 2022-11-22T09:55:37+07:00
------------------------------------------------------------------------
Failed to execute goal org.codehaus.mojo:exec-maven-plugin:3.0.0:exec (default-cli) on project QLKH: Command execution failed.: Process exited with an error: 1 (Exit value: 1) -> [Help 1]
To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.
For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
`
I don't know what wrong,i have try another propety like City,Password and it could not reslove the propety too.Eventhough make the propety name and name in database the same to avoid error
I solved the problem,it because I tagged the #column in the wrong place
#Table(name = "customers", catalog = "market")
public class QLKH_DTO implements java.io.Serializable {
#Id
#GeneratedValue(strategy =GenerationType.IDENTITY)
#Column(name = "CustomerID")
private Integer CustomerID;
#Column(name = "Password")
private String Password;
#Column(name = "Fullname")
private String Fullname;
#Column(name = "Address")
private String Address;
#Column(name = "City")
private String City;
public QLKH_DTO(){}
public QLKH_DTO(String Password,String Fullname, String Address, String City) {
this.Password = Password;
this.Fullname = Fullname;
this.Address = Address;
this.City = City;
}
public Integer getCustomerID() {
return this.CustomerID;
}
public void setCustomerID(Integer CustomerID) {
this.CustomerID = CustomerID;
}
public String getPassword() {
return this.Password;
}
public void setPassword(String Password) {
this.Password = Password;
}
public String getFullname() {
return this.Fullname;
}
public void setFullname(String Fullname) {
this.Fullname = Fullname;
}
public String getAddress() {
return this.Address;
}
public void setAddress(String Address) {
this.Address = Address;
}
public String getCity() {
return this.City;
}
public void setCity(String City) {
this.City = City;
}
}
Related
I am trying to connect to a database that I created with java in eclipse using hibernate. It is supposed to connect to the payroll database and insert records into the student table but I am getting this error! I inserted the jdbc connect and the other required jar files. I am not sure why it's not working. Please help.
Error:
Jul 14, 2022 2:34:10 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 5.5.3.Final
Jul 14, 2022 2:34:11 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
Jul 14, 2022 2:34:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Jul 14, 2022 2:34:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/payroll]
Jul 14, 2022 2:34:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Jul 14, 2022 2:34:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jul 14, 2022 2:34:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 3 (min=1)
Jul 14, 2022 2:34:11 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
Jul 14, 2022 2:34:11 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#304b9f1a] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate:
select
student0_.id as id1_0_,
student0_.email as email2_0_,
student0_.first_name as first_na3_0_,
student0_.last_name as last_nam4_0_
from
student student0_
Hibernate:
select
student0_.id as id1_0_0_,
student0_.email as email2_0_0_,
student0_.first_name as first_na3_0_0_,
student0_.last_name as last_nam4_0_0_
from
student student0_
where
student0_.id=?
Exception in thread "main" java.lang.IllegalStateException: org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl#5eb97ced is closed
at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.errorIfClosed(AbstractLogicalConnectionImplementor.java:37)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:137)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:276)
at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.rollback(AbstractLogicalConnectionImplementor.java:121)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.rollback(JdbcResourceLocalTransactionCoordinatorImpl.java:304)
at org.hibernate.engine.transaction.internal.TransactionImpl.rollback(TransactionImpl.java:142)
at models.Student.get(Student.java:131)
at Driver.main(Driver.java:24)
Driver Class(driver.java)
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.*;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import models.Student;
public class Driver {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu =new Student();//1,"Simone","Charles","#Home");
//stu.create();
List<Student> students=stu.readAll();
for(Student s: students) {
System.out.println(s.getFirstName());
}
Student s1=stu.get(4);
System.out.println(s1.getFirstName());
//sstu.delete(2);
//getCurrentSessionFromConfig();
}
public static Session getCurrentSessionFromConfig() {
// SessionFactory in Hibernate 5 example
Configuration config = new Configuration();
config.configure();
// local SessionFactory bean created
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
return session;
}
public static Session getCurrentSessionX() {
// Hibernate 5.4 SessionFactory example without XML
Map<String, String> settings = new HashMap<>();
settings.put("connection.driver_class", "com.mysql.jdbc.Driver");
settings.put("dialect", "org.hibernate.dialect.MySQL8Dialect");
settings.put("hibernate.connection.url",
"jdbc:mysql://localhost/hibernate_examples");
settings.put("hibernate.connection.username", "root");
settings.put("hibernate.connection.password", "");
settings.put("hibernate.current_session_context_class", "thread");
settings.put("hibernate.show_sql", "true");
settings.put("hibernate.format_sql", "true");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(settings).build();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
// metadataSources.addAnnotatedClass(Player.class);
Metadata metadata = metadataSources.buildMetadata();
// here we build the SessionFactory (Hibernate 5.4)
SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();
Session session = sessionFactory.getCurrentSession();
return session;
}
}
Hibernate xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- Version 8 MySQL hiberante-cfg.xml example for Hibernate 5 -->
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- property name="connection.driver_class">com.mysql.jdbc.Driver</property -->
<property name="connection.url">jdbc:mysql://localhost/payroll</property>
<property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.pool_size">3</property>
<!--property name="dialect">org.hibernate.dialect.MySQLDialect</property-->
<property name="current_session_context_class">thread</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- mapping class="com.mcnz.jpa.examples.Player" / -->
<mapping class="models.Student" />
</session-factory>
</hibernate-configuration>
SessionBuilder File
package factories;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import models.Student;
public class SessionFactoryBuilder {
private static SessionFactory sessionFactory = null;
public static SessionFactory getSessionFactory () {
if(sessionFactory==null) {
try {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
sessionFactory = cfg.buildSessionFactory();
// session =sessionFactory.openSession();
/* sessionFactory =new
Configuration().configure("hibernate.cfg.xml").addAnnotatedClass
(Student.class).buildSessionFactory();
*/
}catch(RuntimeException e) {System.out.println(e.toString());}
}
return sessionFactory;
}
public static void closeSessionFactory () {
if(sessionFactory!=null) {
sessionFactory.close();
}
}
}
Student Class
package models;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
import org.hibernate.Session;
import org.hibernate.Transaction;
import factories.SessionFactoryBuilder;
#Entity
#Table(name="student")
public class Student {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
int id;
#Column(name="first_name")
String firstName;
#Column(name="last_name")
String lastName;
#Column(name="email")
String email;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(int id, String firstName, String lastName, String email) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void create() {
Session session =SessionFactoryBuilder.getSessionFactory().getCurrentSession();
Transaction transaction= session.beginTransaction();
//Student stu=(Student) session.get(Student.class, this.id);
//stu.setFirstName(firstName);
//stu.setLastName(lastName);
session.save(this);
transaction.commit();
session.close();
}
public List<Student> readAll(){
List<Student> studentList=new ArrayList<>();
Session session =SessionFactoryBuilder.getSessionFactory().getCurrentSession();
Transaction transaction= session.beginTransaction();
studentList=(List<Student>) session.createQuery("From Student").getResultList();
transaction.commit();
session.close();
return studentList;
}
public void delete(int id) {
Session session =SessionFactoryBuilder.getSessionFactory()
.getCurrentSession();
Transaction transaction= session.beginTransaction();
//Student stu=(Student) session.get(Student.class, this.id);
//session.delete(stu);
// Delete a persistent object
Student student = session.get(Student.class, id);
if (student != null) {
session.delete(student);
System.out.println("student deleted");
}
// Delete a transient object
/* Student student2 = new Student();
student2.setId(2);
session.delete(student2);
System.out.println("Student 2 is deleted");
*/
transaction.commit();
session.close();
}
public void update() {
Session session =SessionFactoryBuilder.getSessionFactory()
.getCurrentSession();
Transaction transaction= session.beginTransaction();
//Student stu=(Student) session.get(Student.class, this.id);
session.update(this);
transaction.commit();
session.close();
}
public Student get(int id) {
Student stu=null;
Transaction transaction=null;
try(Session session =SessionFactoryBuilder.getSessionFactory()
.getCurrentSession()){
transaction= session.beginTransaction();
stu=(Student) session.get(Student.class, id);
session.delete(stu);
transaction.commit();
}catch(Exception e) {
if(transaction!=null) {
transaction.rollback();
}
e.printStackTrace();
}
return stu;
}
}
I'm beginner in JPA and hibernate and I'm just trying to fetch some data from my DB via hibernate but I failed and I got this error :
Apr 29, 2019 5:14:28 AM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing qPersistenceUnitInfo [name: NewPersistenceUnit]
Apr 29, 2019 5:14:29 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.2.Final}
Apr 29, 2019 5:14:29 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
Apr 29, 2019 5:14:30 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Apr 29, 2019 5:14:30 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/shopping]
Apr 29, 2019 5:14:30 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Apr 29, 2019 5:14:30 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Apr 29, 2019 5:14:30 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Apr 29, 2019 5:14:32 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
Apr 29, 2019 5:14:33 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#35e478f] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Apr 29, 2019 5:14:33 AM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Hibernate:
select
itemclass0_.id as id1_0_0_,
itemclass0_.author as author2_0_0_,
itemclass0_.available_amount as availabl3_0_0_,
itemclass0_.bought as bought4_0_0_,
itemclass0_.imageURL as imageURL5_0_0_,
itemclass0_.name as name6_0_0_,
itemclass0_.price as price7_0_0_,
itemclass0_.publish_time as publish_8_0_0_
from
item itemclass0_
where
itemclass0_.id=?
Apr 29, 2019 5:14:33 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: S1009
Apr 29, 2019 5:14:33 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: MONTH
Apr 29, 2019 5:14:33 AM org.hibernate.event.internal.DefaultLoadEventListener doOnLoad
INFO: HHH000327: Error performing load command : org.hibernate.exception.GenericJDBCException: Could not read entity state from ResultSet : EntityKey[entities.ItemClass#58]
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not read entity state from ResultSet : EntityKey[entities.ItemClass#58]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3581)
at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3519)
at Test.main(Test.java:17)
Caused by: org.hibernate.exception.GenericJDBCException: Could not read entity state from ResultSet : EntityKey[entities.ItemClass#58]
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.loader.plan.exec.process.internal.EntityReferenceInitializerImpl.loadFromResultSet(EntityReferenceInitializerImpl.java:320)
at org.hibernate.loader.plan.exec.process.internal.EntityReferenceInitializerImpl.hydrateEntityState(EntityReferenceInitializerImpl.java:233)
at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.readRow(AbstractRowReader.java:103)
at org.hibernate.loader.plan.exec.internal.EntityLoadQueryDetails$EntityLoaderRowReader.readRow(EntityLoadQueryDetails.java:254)
at org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:122)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:122)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:86)
at org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.load(AbstractLoadPlanBasedEntityLoader.java:197)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4279)
at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:482)
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:452)
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:203)
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:262)
at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:105)
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1287)
at org.hibernate.internal.SessionImpl.access$2100(SessionImpl.java:212)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.doLoad(SessionImpl.java:2930)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.lambda$load$1(SessionImpl.java:2911)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.perform(SessionImpl.java:2867)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2911)
at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3552)
... 2 more
Caused by: java.sql.SQLException: MONTH
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:85)
at com.mysql.cj.jdbc.result.ResultSetImpl.getDate(ResultSetImpl.java:847)
at com.mysql.cj.jdbc.result.ResultSetImpl.getDate(ResultSetImpl.java:860)
at org.hibernate.type.descriptor.sql.DateTypeDescriptor$2.doExtract(DateTypeDescriptor.java:76)
at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:257)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:253)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:243)
at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:329)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:3014)
at org.hibernate.loader.plan.exec.process.internal.EntityReferenceInitializerImpl.loadFromResultSet(EntityReferenceInitializerImpl.java:305)
... 23 more
Caused by: com.mysql.cj.exceptions.WrongArgumentException: MONTH
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105)
at com.mysql.cj.result.SqlDateValueFactory.createFromDate(SqlDateValueFactory.java:80)
at com.mysql.cj.result.SqlDateValueFactory.createFromDate(SqlDateValueFactory.java:46)
at com.mysql.cj.result.BaseDecoratingValueFactory.createFromDate(BaseDecoratingValueFactory.java:53)
at com.mysql.cj.result.BaseDecoratingValueFactory.createFromDate(BaseDecoratingValueFactory.java:53)
at com.mysql.cj.protocol.a.MysqlTextValueDecoder.decodeDate(MysqlTextValueDecoder.java:72)
at com.mysql.cj.protocol.result.AbstractResultsetRow.decodeAndCreateReturnValue(AbstractResultsetRow.java:90)
at com.mysql.cj.protocol.result.AbstractResultsetRow.getValueFromBytes(AbstractResultsetRow.java:250)
at com.mysql.cj.protocol.a.result.ByteArrayRow.getValue(ByteArrayRow.java:91)
at com.mysql.cj.jdbc.result.ResultSetImpl.getNonStringValueFromRow(ResultSetImpl.java:656)
at com.mysql.cj.jdbc.result.ResultSetImpl.getDateOrTimestampValueFromRow(ResultSetImpl.java:679)
... 33 more
Caused by: java.lang.IllegalArgumentException: MONTH
at java.util.GregorianCalendar.computeTime(GregorianCalendar.java:2648)
at java.util.Calendar.updateTime(Calendar.java:3393)
at java.util.Calendar.getTimeInMillis(Calendar.java:1782)
at com.mysql.cj.result.SqlDateValueFactory.createFromDate(SqlDateValueFactory.java:77)
... 42 more
Process finished with exit code 1
and Also type of publish_time column is date.
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="NewPersistenceUnit">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>entities.ItemClass</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/shopping"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value="****"/>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
This is my Entity Class
ItemClass.java
package entities;
import javax.persistence.*;
import java.sql.Date;
import java.util.Objects;
#Entity
#Table(name = "item", schema = "shopping", catalog = "")
public class ItemClass {
private int id;
private String name;
private Integer price;
private String imageUrl;
private Integer availableAmount;
private Integer bought;
#Temporal(TemporalType.TIMESTAMP)
private Date publishTime;
private String author;
#Id
#Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "name", nullable = false, length = 45)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "price", nullable = true)
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
#Basic
#Column(name = "imageURL", nullable = true, length = 45)
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
#Basic
#Column(name = "available_amount", nullable = true)
public Integer getAvailableAmount() {
return availableAmount;
}
public void setAvailableAmount(Integer availableAmount) {
this.availableAmount = availableAmount;
}
#Basic
#Column(name = "bought", nullable = true)
public Integer getBought() {
return bought;
}
public void setBought(Integer bought) {
this.bought = bought;
}
#Basic
#Column(name = "publish_time", nullable = true)
public Date getPublishTime() {
return publishTime;
}
public void setPublishTime(Date publishTime) {
this.publishTime = publishTime;
}
#Basic
#Column(name = "author", nullable = false, length = 45)
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ItemClass itemClass = (ItemClass) o;
return id == itemClass.id &&
Objects.equals(name, itemClass.name) &&
Objects.equals(price, itemClass.price) &&
Objects.equals(imageUrl, itemClass.imageUrl) &&
Objects.equals(availableAmount, itemClass.availableAmount) &&
Objects.equals(bought, itemClass.bought) &&
Objects.equals(publishTime, itemClass.publishTime) &&
Objects.equals(author, itemClass.author);
}
#Override
public int hashCode() {
return Objects.hash(id, name, price, imageUrl, availableAmount, bought, publishTime, author);
}
}
Test.java
import entities.ItemClass;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Test {
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("NewPersistenceUnit");
EntityManager entityManager = entityManagerFactory.createEntityManager();
ItemClass item = entityManager.find(ItemClass.class,58);
System.out.println(item.getAuthor());
}
}
I reviewed another questions that were similar to my title but It doesn't help.
can anyone plz help me to solve this issue ?
UPDATE
These are my rows with publish_time columns:
My Table
This is likely a data issue (in the database table).
A mysql table could contain datetime / timestamp entries like 2019-00-00. While such dates are valid in mysql (depending on the server version and mode), they will cause an exception when the mysql driver tries to parse them into Java dates.
Double check that the rows you are trying to retrieve have valid dates in the publish_time column.
ps. if you have all zero dates (0000-00-00 00:00:00) then you can use the zeroDateTimeBehavior property in the connection string to handle them more gracefully without changing the database values.
the system that I'm implementing is composed of:
Eclipse Neon 4.6 + maven (integreted) + Hibernate 5.2.2 + Mysql (i use MySql Workbench 6.3)
algorithm:
I tried to create this java application on eclipse:
a student entity and an address entity (the some address can be used for many students)
info:
I created only a htmanytoone schemas on mysql, and I want hibernate it to take care of creation and management of the entities on.
I hope there are no problems of continuity (I modified the code several times )
My project on eclipse:
Package Explorer
Student.java:
package withMaven.hibernateMaven1;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "student")
public class Student {
private long studentId;
private String studentName;
private Address studentAddress;
public Student() {
}
public Student(String studentName, Address studentAddress) {
this.studentName = studentName;
this.studentAddress = studentAddress;
}
#Id
#GeneratedValue
#Column(name = "student_id")
public long getStudentId() {
return this.studentId;
}
public void setStudentId(long studentId) {
this.studentId = studentId;
}
#Column(name = "student_name")//, nullable = false, length = 100)
public String getStudentName() {
return this.studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
#ManyToOne(cascade = CascadeType.ALL)
public Address getStudentAddress() {
return this.studentAddress;
}
public void setStudentAddress(Address studentAddress) {
this.studentAddress = studentAddress;
}
}
Address.java:
package withMaven.hibernateMaven1;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "address")
public class Address {
private long addressId;
private String street;
private String city;
private String state;
private String zipcode;
public Address() {
}
public Address(String street, String city, String state, String zipcode) {
this.street = street;
this.city = city;
this.state = state;
this.zipcode = zipcode;
}
#Id
#GeneratedValue
#Column(name = "adderess_id")
public long getAddressId() {
return this.addressId;
}
public void setAddressId(long addressId) {
this.addressId = addressId;
}
//#Column(name = "address_street", nullable = false, length=250)
#Column(name = "address_street")
public String getStreet() {
return this.street;
}
public void setStreet(String street) {
this.street = street;
}
//#Column(name = "address_city", nullable = false, length=50)
#Column(name = "address_city")
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
//#Column(name = "address_state", nullable = false, length=50)
#Column(name = "address_state")
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
#Column(name = "address_zipcode")//, nullable = false, length=10)
public String getZipcode() {
return this.zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
}
play.java: (the test main)
package withMaven.hibernateMaven1;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class play {
public static void main(String[] args) {
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session=factory.getCurrentSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Address address = new Address("OMR Road", "Chennai", "TN", "600097");
Student student1 = new Student("Eswar", address);
Student student2 = new Student("Joe", address);
session.save(student1);
session.save(student2);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
hibernate.cfx.xml:
<?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.connection.driver_class"> org.hsqldb.jdbcDriver</property>
<property name="hibernate.connection.url"> jdbc:hsqldb:hsql://3306/htmanytoone?useSSL=false</property>
<property name="hibernate.connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="Student" />
<mapping class="Address" />
</session-factory>
</hibernate-configuration>
the pom.xml: (I use maven because it is recommended, but I have no experience with it)
<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>withMaven</groupId>
<artifactId>prova1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>proviamo maven</name>
<description>primo utilizzo con maven</description>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.2.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.31</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.3.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
and now the console when i run play.java:
Sep 07, 2016 10:12:09 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.2.Final}
Sep 07, 2016 10:12:09 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Sep 07, 2016 10:12:09 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Sep 07, 2016 10:12:09 AM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
Sep 07, 2016 10:12:09 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Sep 07, 2016 10:12:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Sep 07, 2016 10:12:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.hsqldb.jdbcDriver] at URL [jdbc:hsqldb:hsql://3306/htmanytoone?useSSL=false]
Sep 07, 2016 10:12:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Sep 07, 2016 10:12:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Sep 07, 2016 10:12:09 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Exception in thread "main" org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:267)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:231)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:240)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at withMaven.hibernateMaven1.play.main(play.java:13)
Caused by: org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:115)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:101)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:123)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:41)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:58)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.addConnections(PooledConnections.java:123)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:42)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:20)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections$Builder.build(PooledConnections.java:161)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:109)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:72)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:240)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:257)
... 14 more
Caused by: java.sql.SQLTransientConnectionException: java.net.SocketException: Network is unreachable: connect
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCConnection.<init>(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.getConnection(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.connect(Unknown Source)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:38)
... 29 more
Caused by: org.hsqldb.HsqlException: java.net.SocketException: Network is unreachable: connect
at org.hsqldb.ClientConnection.openConnection(Unknown Source)
at org.hsqldb.ClientConnection.initConnection(Unknown Source)
at org.hsqldb.ClientConnection.<init>(Unknown Source)
... 33 more
Caused by: java.net.SocketException: Network is unreachable: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at org.hsqldb.server.HsqlSocketFactory.createSocket(Unknown Source)
... 36 more
If you want to use mysql, you have to Change this lines:
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/htmanytoone?useSSL=false</property>
Can't understand what i'm doing wrong.
Have an Exception in thread "AWT-EventQueue-0" java.lang.ExceptionInInitializerError
I thought it`s a problem with sessionFactory but can't understand how resolve it.
HibernateUtil.java
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import java.util.List;
import java.util.Date;
import java.util.Iterator;
public class HibernateUtil {
private static SessionFactory sessionFactory;
public HibernateUtil(){ }
static{
try{
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}catch(Throwable e) {
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
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.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- Assume test is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost/storage
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root
</property>
<mapping class="main.java.table.Brand"/>
<mapping class="main.java.table.HardDrive"/>
</session-factory>
</hibernate-configuration>
Goods.java
package main.java.table;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "goods")
public class Goods {
#Id #GeneratedValue
#Column(name = "idGoods")
private int idGoods;
#Column(name = "price")
private double price;
#Column(name = "quantity")
private int quantity;
public int getIdGoods() {
return idGoods;
}
public void setIdGoods(int idGoods) {
this.idGoods = idGoods;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
CheckInDatabase.java
package main.java.cheking;
import java.util.Iterator;
import java.util.List;
import main.java.table.Brand;
import main.java.table.HardDrive;
import main.java.util.HibernateUtil;
import org.hibernate.Session;
/*
* Класс проверяет повторы в таблицах и если их нет создает и возвращает запись
*/
public class CheckInDatabase {
private static Session session = null;
public static List list = null;
public static List<Brand> listOut = null;
//List <E> list = null;
CheckInDatabase(){}
public static List isNameInDataBase(String name, String table) {
try{
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
list = session.createQuery("FROM " + table + " WHERE name like '" + name + "' ").list();
} catch(Exception e){
e.printStackTrace();
} finally {
if ((session != null) && (session.isOpen()))
session.close();
}
return list;
}
public static Brand isBrandInDataBase(String name){
Brand brand = new Brand();
try{
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
listOut = session.createQuery("FROM Brand WHERE nameBrand like '" + name + "' ").list();
} catch(Exception e){
e.printStackTrace();
} finally {
if ((session != null) && (session.isOpen()))
session.close();
}
if (listOut.isEmpty()){
brand.nameBrand = name; //если бренда в базе нет, создаем
Session session = null;
try{
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(brand);
System.out.println("Brand created");
session.getTransaction().commit();
} catch(Exception e){
e.printStackTrace();
} finally {
if ((session != null) && (session.isOpen()))
session.close();
}
return brand;
}
else{
for (Iterator iterator =
CheckInDatabase.listOut.iterator(); iterator.hasNext();){
brand = (Brand) iterator.next();
System.out.print("Id: " + brand.getIdBrand()+ " ");
System.out.print("Name: " + brand.getNameBrand()+ " ");
System.out.println("\n");
}
return brand;
}
}
}
HardDrive.java
package main.java.table;
import java.sql.SQLException;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import main.java.cheking.CheckInDatabase;
#Entity
#Table(name = "harddrives")
public class HardDrive {
#Id #GeneratedValue
#Column(name = "idHardDrive")
private int idHardDrive;
#Column(name = "name")
private String name;
#Column(name = "formFactor")
private double formFactor;
#Column(name = "capacity")
private int capacity;
#Column(name = "interface")
private String interFace;
#Column(name = "bufferSize")
private String bufferSize;
#ManyToOne
#JoinColumn (name = "idBrand")
private Brand brand;
#ManyToOne
#JoinColumn (name = "idGoods")
private Goods goods;
public HardDrive(){}
public HardDrive(String name, double formFactor, int capacity, String interFace, String bufferSize, String brand) {
List nameList = null;
nameList = CheckInDatabase.isNameInDataBase(name, "HardDrive");
if (nameList.isEmpty()){
this.name = name;
this.formFactor = formFactor;
this.capacity = capacity;
this.interFace = interFace;
this.bufferSize = bufferSize;
Brand brand2 = new Brand();
this.brand = brand2.setNameBrand(brand);
System.out.println("BRAND NAME IN HARDDRIVE = " + this.brand.getNameBrand() );
}
else{
System.out.println("this name is in the table");
}
System.out.println("Can set");
}
public int getIdHardDrives() {
return idHardDrive;
}
public void setIdHardDrives(int idHardDrives) {
this.idHardDrive = idHardDrives;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getFormFactor() {
return formFactor;
}
public void setFormFactor(double formFactor) {
this.formFactor = formFactor;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public String getInterFace() {
return interFace;
}
public void setInterFace(String interFace) {
this.interFace = interFace;
}
public String getBufferSize() {
return bufferSize;
}
public void setBufferSize(String bufferSize) {
this.bufferSize = bufferSize;
}
public void setBrand(Brand brand){
this.brand = brand;
}
public Brand getBrand(){
return brand;
}
public Goods getGoods() {
return goods;
}
public void setGoods(Goods goods) {
this.goods = goods;
}
}
AddHardDrive.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.SQLException;
import javax.swing.JComboBox;
public class AddHardDrive extends JFrame {
private JPanel contentPane;
private JTextField nameTextField;
private JComboBox formFactorComboBox;
private JComboBox capacityComboBox;
private JComboBox interFaceComboBox;
private JComboBox bufferSizeComboBox;
private JComboBox brandComboBox;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddHardDrive frame = new AddHardDrive();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public AddHardDrive() {
String [] formFactor = {"2.5", "3.5"};
String[] capacity = {"250", "320", "500", "750", "1000",
"1250", "1500", "2000", "3000"};
String[] interFaces = {"eSATA", "SATA2", "SATA3","USB 2.0", "USB 3.0"};
String[] bufferSize = {"2 MB", "8 MB", "16 MB","32 MB", "64 MB", "128 MB"};
String[] brands = {"A-DATA","ASUS", "Fujitsu","Hitachi", "IBM", "Samsung",
"Seagate", "Silicon Power","Toshiba", "Transcend", "WD"};
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
nameTextField = new JTextField();
nameTextField.setBounds(213, 8, 211, 20);
contentPane.add(nameTextField);
nameTextField.setColumns(10);
JLabel lblNewLabel = new JLabel("Название :");
lblNewLabel.setBounds(148, 11, 55, 14);
contentPane.add(lblNewLabel);
JLabel lblNewLabel_5 = new JLabel("Форм-фактор :");
lblNewLabel_5.setBounds(127, 36, 76, 14);
contentPane.add(lblNewLabel_5);
JLabel lblNewLabel_1 = new JLabel("Обьем :");
lblNewLabel_1.setBounds(164, 73, 39, 14);
contentPane.add(lblNewLabel_1);
JLabel lblNewLabel_2 = new JLabel("Интерфейс :");
lblNewLabel_2.setBounds(140, 101, 63, 14);
contentPane.add(lblNewLabel_2);
JLabel lblNewLabel_3 = new JLabel("Тип соединения :");
lblNewLabel_3.setBounds(113, 126, 88, 14);
contentPane.add(lblNewLabel_3);
JLabel lblNewLabel_4 = new JLabel("Бренд :");
lblNewLabel_4.setBounds(164, 151, 38, 14);
contentPane.add(lblNewLabel_4);
JButton btnNewButton = new JButton("Добавить");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
HardDrive hardDrive = new HardDrive(nameTextField.getText(),
Double.parseDouble(formFactorComboBox.getSelectedItem().toString()),
Integer.parseInt(capacityComboBox.getSelectedItem().toString()),
interFaceComboBox.getSelectedItem().toString(),bufferSizeComboBox.getSelectedItem().toString(),
brandComboBox.getSelectedItem().toString());
HardDriveDaoImpl hddi = new HardDriveDaoImpl();
hddi.addHardDrive(hardDrive);
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnNewButton.setBounds(213, 179, 211, 71);
contentPane.add(btnNewButton);
interFaceComboBox = new JComboBox(interFaces);
interFaceComboBox.setBounds(213, 98, 211, 20);
contentPane.add(interFaceComboBox);
capacityComboBox = new JComboBox(capacity);
capacityComboBox.setBounds(213, 70, 211, 20);
contentPane.add(capacityComboBox);
bufferSizeComboBox = new JComboBox(bufferSize);
bufferSizeComboBox.setBounds(213, 123, 211, 20);
contentPane.add(bufferSizeComboBox);
brandComboBox = new JComboBox(brands);
brandComboBox.setBounds(213, 148, 211, 20);
contentPane.add(brandComboBox);
formFactorComboBox = new JComboBox(formFactor);
formFactorComboBox.setBounds(213, 39, 211, 20);
contentPane.add(formFactorComboBox);
}
}
Error
мар 11, 2015 11:33:23 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
мар 11, 2015 11:33:23 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.7.Final}
мар 11, 2015 11:33:23 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
мар 11, 2015 11:33:23 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
мар 11, 2015 11:33:23 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
мар 11, 2015 11:33:23 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
мар 11, 2015 11:33:23 AM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
мар 11, 2015 11:33:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
мар 11, 2015 11:33:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/storage]
мар 11, 2015 11:33:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
мар 11, 2015 11:33:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
мар 11, 2015 11:33:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
мар 11, 2015 11:33:23 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
мар 11, 2015 11:33:23 AM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Exception in thread "AWT-EventQueue-0" java.lang.ExceptionInInitializerError
at HibernateUtil.<clinit>(HibernateUtil.java:30)
at CheckInDatabase.isNameInDataBase(CheckInDatabase.java:27)
at HardDrive.<init>(HardDrive.java:47)
at AddHardDrive$2.actionPerformed(AddHardDrive.java:98)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: org.hibernate.AnnotationException: #OneToOne or #ManyToOne on HardDrive.goods references an unknown entity: Goods
at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:109)
at org.hibernate.cfg.Configuration.processEndOfQueue(Configuration.java:1598)
at org.hibernate.cfg.Configuration.processFkSecondPassInOrder(Configuration.java:1521)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1422)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1846)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1930)
at HibernateUtil.<clinit>(HibernateUtil.java:28)
... 39 more
The error messages says, that Goods are not mapped. You need to add goods to your hibernate.cfg.xml
<mapping class="main.java.table.Brand"/>
<mapping class="main.java.table.HardDrive"/>
<mapping class="main.java.table.Goods"/>
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);
}
...
}