I've made a Hibernate configuration maven project (built with the maven-shade-plugin) to allow my codebase to use one unified "database class". However, the class does not seem to map (throws a org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped exception at runtime) when called from outside the running project.
When ran within the project, everything works fine. However, Hibernate fails to map the entity when run from outside the project.
CommonDB.java (part of the maven package meta1203-data)
package com.meta1203.microservices;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class CommonDB <C extends BaseEntity> {
private Configuration cfg;
private SessionFactory sf;
private Session session;
private Class<C> c;
public CommonDB(Class<C> anoClass) {
String jdbcUrl = String.format(
"jdbc:mysql://%s/%s",
System.getenv("DB_URL"),
System.getenv("DB_NAME"));
cfg = new Configuration()
.setProperty("hibernate.connection.url", jdbcUrl)
.setProperty("hibernate.connection.username", System.getenv("DB_USERNAME"))
.setProperty("hibernate.connection.password", System.getenv("DB_PASSWORD"))
.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver")
.setProperty("hibernate.connection.pool_size", "1")
.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect")
.setProperty("hibernate.hbm2ddl.auto", "update")
.setProperty("hibernate.show_sql", "true")
.addAnnotatedClass(anoClass.getClass());
c = anoClass;
}
public void open() {
sf = cfg.buildSessionFactory();
session = sf.openSession();
}
public void close() {
session.close();
sf.close();
}
public C findOneBy(String field, String o) {
String query = "select u from " + c.getSimpleName() + " u where u." + field + " = :id";
return session.createQuery(query, c).setParameter("id", o).getSingleResult();
}
// other CRUD functions
}
TestDB.java (part of the maven package meta1203-userservice)
package com.meta1203.microservices.user;
import com.meta1203.microservices.CommonDB;
import com.meta1203.microservices.user.model.User;
public class TestDB {
public static void main(String[] args) {
TestDB tdb = new TestDB();
CommonDB<User> db = new CommonDB<User>(User.class);
db.open();
User hunter = db.findOneBy("username", "hunter");
System.out.println(hunter.getUsername());
System.out.println(db.countBy("username", "hunter"));
db.close();
}
}
User.java (part of the maven package meta1203-userservice)
package com.meta1203.microservices.user.model;
import java.util.Set;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.meta1203.microservices.BaseEntity;
#Entity
#Table(name = "users")
public class User extends BaseEntity {
private String username;
private String textNotificationList;
private String emailNotificationList;
#ElementCollection
private Set<Long> ignoredAlerts;
#ElementCollection
private Set<Long> clients;
// to be parsed with DateTimeFormatter.ISO_OFFSET_DATE_TIME
private String lastItineraryUpdate;
// getters and setters
}
parent's pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.meta1203</groupId>
<artifactId>meta1203-services</artifactId>
<packaging>pom</packaging>
<version>0.0.1</version>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>com.meta1203</groupId>
<artifactId>meta1203-data</artifactId>
<version>0.0.1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.11.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
</dependencies>
<modules>
<module>meta1203-userservice</module>
</modules>
</project>
Sep 07, 2019 2:36:13 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {[WORKING]}
Sep 07, 2019 2:36:13 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Sep 07, 2019 2:36:13 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
Sep 07, 2019 2:36:14 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Sep 07, 2019 2:36:14 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#329dbdbf] 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.
Sep 07, 2019 2:36:14 AM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Exception in thread "main" java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped [select u from User u where u.username = :id]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:729)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:745)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:104)
at com.meta1203.microservices.CommonDB.findOneBy(CommonDB.java:72)
at com.meta1203.microservices.user.TestDB.main(TestDB.java:12)
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped [select u from User u where u.username = :id]
at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79)
at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:219)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:143)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:119)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:611)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:720)
... 4 more
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:169)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:79)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:331)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3695)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3584)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:720)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:576)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:313)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:261)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:271)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:191)
... 10 more
#Entity
#Table(name = "users")
public class User extends BaseEntity {
Your entity is called User but its mapped to a table called users.
Either change the entity to Users or table to user.
That should do it.
Try:
Configuration configuration = new Configuration().configure();
for (Class cls : getEntityClassesFromPackage("com.example.hib.entities")) {
configuration.addAnnotatedClass(cls);
}
Whelp, I found out what was going on. My galaxy brain decided to do addAnnotatedClass(anoClass.getClass()) on a Class object, so I was trying to declare java.lang.Class as a Hibernate Entity... Oh well, I'm just an idiot. Changed it to just addAnnotatedClass(anoClass) and it works just fine.
Related
I am learning Hibernate as a beginner,I am working with maven + hibernate + oracle11g
I am receiving error when i run the following code
Here is the code which i am working on :
Pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wipro.HibernateDemp</groupId>
<artifactId>HibernateDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>HibernateDemo</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.20.0-GA</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.11.Final</version>
<type>pom</type>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impl -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc6 -->
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.4</version>
</dependency>
</dependencies>
</project>
Department.java
package com.hibernate.bean;
import org.hibernate.Hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Department
{
private int depno;
private String depName;
private int locationid;
private int managerid;
public Department() {
}
public Department(int depno, String depName, int locationid, int managerid) {
super();
this.depno = depno;
this.depName = depName;
this.locationid = locationid;
this.managerid = managerid;
}
public int getDepno() {
return depno;
}
public void setDepno(int depno) {
this.depno = depno;
}
public String getDepName() {
return depName;
}
public void setDepName(String depName) {
this.depName = depName;
}
public int getLocationid() {
return locationid;
}
public void setLocationid(int locationid) {
this.locationid = locationid;
}
public int getManagerid() {
return managerid;
}
public void setManagerid(int managerid) {
this.managerid = managerid;
}
#Override
public String toString() {
return "Department [depno=" + depno + ", depName=" + depName + ", locationid=" + locationid + ", managerid="
+ managerid + "]";
}
}
DepartmentAdmin.java
package com.wipro.services;
import javax.transaction.Transaction;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.hibernate.bean.Department;
public class DepartmentAdmin {
public static void main(String args[]) {
Configuration cfg = new Configuration().configure();
SessionFactory sf = cfg.buildSessionFactory();
Session session =sf.openSession();
org.hibernate.Transaction transaction = session.beginTransaction();
Department deptobj = new Department(280,"CSE", 116,1830);
session.save(deptobj);
transaction.commit();
System.out.println("Record inserted");
System.out.println(deptobj);
session.close();
}
}
department.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.wipro.bean.Department" table="Departments">
<id name="depno" column="DEPARTMENT_ID" type="int">
<generator class="assigned"></generator>
</id>
<property name="depName" column="DEPARTMENT_NAME" type="string"></property>
<property name="locationid" column="LOCATION_ID" type="int"></property>
<property name="managerid" column="MANAGER_ID" type="int"></property>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name="hibernate.connection.username">hr</property>
<property name="hibernate.connection.password">hr</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle8iDialect</property>
<property name="hibernateshow_sql">true</property>
<mapping resource="department.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I am receiving the following when i run the code:
May 28, 2022 11:58:17 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.11.Final}
May 28, 2022 11:58:17 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
May 28, 2022 11:58:17 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
May 28, 2022 11:58:17 AM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
May 28, 2022 11:58:17 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
May 28, 2022 11:58:17 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [oracle.jdbc.OracleDriver] at URL [jdbc:oracle:thin:#localhost:1521:xe]
May 28, 2022 11:58:17 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=hr}
May 28, 2022 11:58:17 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
May 28, 2022 11:58:17 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
May 28, 2022 11:58:18 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle8iDialect
May 28, 2022 11:58:18 AM org.hibernate.search.engine.Version <clinit>
INFO: HSEARCH000034: Hibernate Search 5.8.0.Final
May 28, 2022 11:58:18 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 2291, SQLState: 23000
May 28, 2022 11:58:18 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ORA-02291: integrity constraint (HR.DEPT_MGR_FK) violated - parent key not found
May 28, 2022 11:58:18 AM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
May 28, 2022 11:58:18 AM org.hibernate.internal.ExceptionMapperStandardImpl mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:149)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:164)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1443)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:493)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3207)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2413)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:156)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:231)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
at com.wipro.services.DepartmentAdmin.main(DepartmentAdmin.java:19)
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:178)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3013)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3513)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:589)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1437)
... 9 more
Caused by: java.sql.SQLIntegrityConstraintViolationException: ORA-02291: integrity constraint (HR.DEPT_MGR_FK) violated - parent key not found
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:208)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1046)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1336)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3613)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3694)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1354)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)
... 18 more
Table departments structure:
Name | Null? | Type |
:---------------|:--------:| ------------ :|
DEPARTMENT_ID | NOT NULL | NUMBER(4) |
DEPARTMENT_NAME | NOT NULL |VARCHAR2(30) |
MANAGER_ID | |NUMBER(6) |
LOCATION_ID | | NUMBER(4) |
I have no idea what is happening here...anyhelp is most welcomed...
The problem is that you didn't map the association correctly. Given the name of the table and constraint, I think there's not a manager matching the id you have specified.
A relationship between Department and Manager (assuming a department has only one manager) should look something like:
#Entity
public class Department {
....
#ManyToOne // Assuming a manager can manage multiple departments
Manager manager;
}
#Entity
public class Manager {
// ... id, fields, getters/setters
}
I've used annotations because I find it easier (and probably more common) but you can do the same with XML.
I would suggest to check the Hibernate ORM documentation to figure out how to map associations.
I'm learning Hibernate, and during simple demo application, I encounter problem, I can't overcame. There are only two tables, two entity classes and main app. Project is in maven.
Github: github.com/fangirsan/maruszka.git
Batch.class:
package com.maruszka.entity;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="batch")
public class Batch {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="batch_number")
private int batchNumber;
#Column(name="batch_style")
private String batchStyle;
#Column(name="batch_name")
private String batchName;
#Column(name="batch_creation_date", columnDefinition="DATE")
#Temporal(TemporalType.TIMESTAMP)
private Date batchCreationDate;
#ManyToMany(fetch=FetchType.LAZY,
cascade= {CascadeType.PERSIST, CascadeType.MERGE,
CascadeType.DETACH, CascadeType.REFRESH})
#JoinTable(
name="batch_malt",
joinColumns=#JoinColumn(name="batch_id"),
inverseJoinColumns=#JoinColumn(name="malt_id")
)
private List<Malt> malts;
public Batch() {
}
public Batch(int batchNumber, String batchStyle, String batchName, Date batchCreationDate) {
this.batchNumber = batchNumber;
this.batchStyle = batchStyle;
this.batchName = batchName;
this.batchCreationDate = batchCreationDate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getBatchNumber() {
return batchNumber;
}
public void setBatchNumber(int batchNumber) {
this.batchNumber = batchNumber;
}
public String getBatchStyle() {
return batchStyle;
}
public void setBatchStyle(String batchStyle) {
this.batchStyle = batchStyle;
}
public String getBatchName() {
return batchName;
}
public void setBatchName(String batchName) {
this.batchName = batchName;
}
public Date getBatchCreationDate() {
return batchCreationDate;
}
public void setBatchCreationDate(Date batchCreationDate) {
this.batchCreationDate = batchCreationDate;
}
public List<Malt> getMalts() {
return malts;
}
public void setMalts(List<Malt> malts) {
this.malts = malts;
}
#Override
public String toString() {
return "Batch [id=" + id + ", batchNumber=" + batchNumber + ", batchStyle=" + batchStyle + ", batchName="
+ batchName + ", batchCreationDate=" + batchCreationDate + ", malts=" + malts + "]";
}
// add a convenience method
public void addMalt(Malt theMalt) {
if (malts == null) {
malts = new ArrayList<>();
}
malts.add(theMalt);
}
}
Malt.class
package com.maruszka.entity;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="malt")
public class Malt {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="malt_name")
private String maltName;
#Column(name="malt_manufacturer")
private String maltManufacturer;
#Column(name="filling")
private int filling;
#Column(name="ebc")
private int ebc;
#Column(name="usage")
private String usage;
#ManyToMany(fetch=FetchType.LAZY,
cascade= {CascadeType.PERSIST, CascadeType.MERGE,
CascadeType.DETACH, CascadeType.REFRESH})
#JoinTable(
name="batch_malt",
joinColumns=#JoinColumn(name="malt_id"),
inverseJoinColumns=#JoinColumn(name="batch_id")
)
private List<Batch> batches;
public Malt() {
}
public Malt(String maltName, String maltManufacturer, int filling, int ebc, String usage) {
this.maltName = maltName;
this.maltManufacturer = maltManufacturer;
this.filling = filling;
this.ebc = ebc;
this.usage = usage;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMaltName() {
return maltName;
}
public void setMaltName(String maltName) {
this.maltName = maltName;
}
public String getMaltManufacturer() {
return maltManufacturer;
}
public void setMaltManufacturer(String maltManufacturer) {
this.maltManufacturer = maltManufacturer;
}
public int getFilling() {
return filling;
}
public void setFilling(int filling) {
this.filling = filling;
}
public int getEbc() {
return ebc;
}
public void setEbc(int ebc) {
this.ebc = ebc;
}
public String getUsage() {
return usage;
}
public void setUsage(String usage) {
this.usage = usage;
}
public List<Batch> getBatches() {
return batches;
}
public void setBatches(List<Batch> batches) {
this.batches = batches;
}
#Override
public String toString() {
return "Malt [id=" + id + ", maltName=" + maltName + ", maltManufacturer=" + maltManufacturer + ", filling="
+ filling + ", ebc=" + ebc + ", usage=" + usage + ", batches=" + batches + "]";
}
}
CreateBatchAndMalt.class (main):
package com.maruszka.test;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.maruszka.entity.Malt;
import com.maruszka.entity.Batch;
public class CreateBatchAndMalt {
public static void main(String[] args) {
// create session factory
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Batch.class)
.addAnnotatedClass(Malt.class)
.buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
try {
// start a transaction
session.beginTransaction();
// create a malt
Malt tempMalt = new Malt("Carafa (R) typ I", "Weyerman", 10, 900, "Stout, Porter, Schwarzbier");
// save the malt
System.out.println("\nSaving the malt ...");
session.save(tempMalt);
System.out.println("Saved the malt: " + tempMalt);
// create the batch
Date now = new Date();
Batch tempBatch = new Batch(2, "Mild", "Szatan", now);
// add malt to the batch
tempBatch.addMalt(tempMalt);
// save the batch
System.out.println("\nSaving batch ...");
session.save(tempBatch);
System.out.println("Saved batch: " + tempBatch.getMalts());
// commit transaction
session.getTransaction().commit();
System.out.println("Done!");
}
finally {
// close session
session.close();
factory.close();
}
}
}
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.maruszka</groupId>
<artifactId>maruszka</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>maruszka Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<springframework.version>5.0.2.RELEASE</springframework.version>
<springsecurity.version>5.0.1.RELEASE</springsecurity.version>
<hibernate.version>5.3.1.Final</hibernate.version>
<!-- 5.2.12.Final -->
<mysql.connector.version>5.1.38</mysql.connector.version>
<c3po.version>0.9.5.2</c3po.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- Add support for JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Spring MVC support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Add support for Spring Tags -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<!-- Hibernate Core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.4.Final</version>
</dependency>
<!-- Add MySQL and C3P0 support -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
<!-- dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency-->
</dependencies>
<build>
<!-- TO DO: Add support for Maven WAR Plugin -->
<finalName>maruszka</finalName>
<pluginManagement>
<plugins>
<plugin>
<!-- Add Maven coordinates for: maven-war-plugin -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
hibernate.cfg.xml (in maruszka\src\main\resources\hibernate.cfg.xml):
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/maruszka?serverTimezone=UTC</property>
<!-- &useSSL=false -->
<property name="connection.username">***</property>
<property name="connection.password">***</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">false</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
DB script:
CREATE DATABASE IF NOT EXISTS `maruszka`;
USE `maruszka`;
SET FOREIGN_KEY_CHECKS=0;
-- batch
DROP TABLE IF EXISTS `batch`;
CREATE TABLE `batch` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`batch_number` int(3) NOT NULL,
`batch_style` varchar(45) DEFAULT NULL,
`batch_name` varchar(45) DEFAULT NULL,
`batch_creation_date` DATE,
PRIMARY KEY (`id`),
UNIQUE KEY(`batch_number`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
LOCK TABLE `batch` WRITE;
INSERT INTO `batch` VALUES
(1, 1, 'Stout', 'Happy Stout', '2018-06-06');
UNLOCK TABLES;
-- malt
DROP TABLE IF EXISTS `malt`;
CREATE TABLE `malt` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`malt_name` varchar(45) DEFAULT NULL,
`malt_manufacturer` varchar(45) DEFAULT NULL,
`filling` int(3) DEFAULT NULL,
`ebc` int(3) DEFAULT NULL,
`usage` varchar(254) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY(`malt_name`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
LOCK TABLES `malt` WRITE;
INSERT INTO `malt` VALUES
(1, 'Pale Ale', 'Malteurop', 100, 6, 'All');
UNLOCK TABLES;
-- join table for batch - malt
DROP TABLE IF EXISTS `batch-malt`;
CREATE TABLE `batch-malt` (
`batch_id` int(11) NOT NULL,
`malt_id` int(11) NOT NULL,
PRIMARY KEY (`batch_id`, `malt_id`),
-- fk_[referencing table name]_[referenced table name]_[referencing field name]
CONSTRAINT `FK_BATCH_MALT_ID` FOREIGN KEY (`malt_id`)
REFERENCES `malt` (`id`)
ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_MALT_BATCH_ID` FOREIGN KEY (`batch_id`)
REFERENCES `batch` (`id`)
ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
SET FOREIGN_KEY_CHECKS=1;
When using mysql connector in version 8.0.11:
cze 06, 2018 9:33:53 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.3.1.Final}
cze 06, 2018 9:33:53 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
cze 06, 2018 9:33:53 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.3.Final}
cze 06, 2018 9:33:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
cze 06, 2018 9:33:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/maruszka?serverTimezone=UTC]
cze 06, 2018 9:33:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
cze 06, 2018 9:33:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
cze 06, 2018 9:33:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Wed Jun 06 21:33:53 CEST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
cze 06, 2018 9:33:53 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
cze 06, 2018 9:33:54 PM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 6.0.4.Final
Saving the malt ...
cze 06, 2018 9:33:54 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1064, SQLState: 42000
cze 06, 2018 9:33:54 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'usage) values (900, 10, 'Weyerman', 'Carafa (R) typ I', 'Stout, Porter, Schwarzb' at line 1
cze 06, 2018 9:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/maruszka?serverTimezone=UTC]
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:178)
at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3037)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3628)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:645)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:282)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:317)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:359)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:292)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:200)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:131)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:709)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:701)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:696)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:349)
at com.sun.proxy.$Proxy36.save(Unknown Source)
at com.maruszka.test.CreateBatchAndMalt.main(CreateBatchAndMalt.java:42)
Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'usage) values (900, 10, 'Weyerman', 'Carafa (R) typ I', 'Stout, Porter, Schwarzb' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:118)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:960)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1116)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1066)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1396)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1051)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)
... 28 more
I've double check syntax, but can't figure out wha is causing this:
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'usage) values (900, 10, 'Weyerman', 'Carafa (R) typ I', 'Stout, Porter, Schwarzb' at line 1
Best regards
In your sql table malt you have a column named usage and that name is a reserved word in MySQL so that is why your insert query doesn't work.
The easiest way forward is to change the name to something else, for instance malt_usage
So this will not work:
INSERT INTO malt(filling, ebc, malt_manufacturer, malt_name, usage)
VALUES (900, 10, 'Weyerman', 'Carafa (R) typ I', 'Stout, Porter, Schwarzb')
but this will
INSERT INTO malt(filling, ebc, malt_manufacturer, malt_name, malt_usage)
VALUES (900, 10, 'Weyerman', 'Carafa (R) typ I', 'Stout, Porter, Schwarzb')
In java this is not a problem so there you can keep the name usage if you want
#Column(name="malt_usage")
private String usage;
The literal usage is a keyword in mysql.
https://dev.mysql.com/doc/refman/8.0/en/keywords.html#keywords-8-0-detailed-U
Simplest solution is to simply change the column name to another (non-keyword) term.
Otherwise, try setting
hibernate.auto_quote_keyword=true
This question already has answers here:
How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
(43 answers)
Closed 5 years ago.
Edit 5: Solved
The main problem was that I've used JDK 9, where the JAXB APIs are no longer on on the default class path. Here is link where I've found solution.
I used hibernate version 4.3.6 from example tutorial and everything've worked good, but when I update version to 5.2.10 I have problem (I know that code responsible for getSessionFactory is different so I changed it).
My first function:
private static SessionFactory getSessionFactory(){
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
return sessionFactory;
}
And my function in 5.2.10 version:
private static SessionFactory getSessionFactory(){
StandardServiceRegistry registry;
SessionFactory sessionFactory;
registry = new StandardServiceRegistryBuilder().configure().build();
MetadataSources sources = new MetadataSources(registry);
Metadata metadata = sources.getMetadataBuilder().build();
sessionFactory = metadata.getSessionFactoryBuilder().build();
return sessionFactory;
}
Exception:
Exception in thread "main"
org.hibernate.internal.util.config.ConfigurationException: Unable to
perform unmarshalling at line number 0 and column 0 in RESOURCE
hibernate.cfg.xml. Message: null
and 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.PostgreSQL94Dialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://127.0.0.1:5432/postgres</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">123</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">false</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping class="com.example.Item"/>
</session-factory>
</hibernate-configuration>
Where is the problem? I've tried everything.
Edit: pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>pl.example</groupId>
<artifactId>example</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.1.4</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>
</dependencies>
Edit 2
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
StandardServiceRegistry standardRegistry =
new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata metaData =
new MetadataSources(standardRegistry).getMetadataBuilder().build();
sessionFactory = metaData.getSessionFactoryBuilder().build();
} catch (Throwable th) {
System.err.println("Enitial SessionFactory creation failed" + th);
throw new ExceptionInInitializerError(th);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
#Entity
#Table(name = "employee")
public class Employee implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="emp_name")
private String empName;
#Column(name="emp_address")
private String empAddress;
#Column(name="emp_mobile_nos")
private String empMobileNos;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpAddress() {
return empAddress;
}
public void setEmpAddress(String empAddress) {
this.empAddress = empAddress;
}
public String getEmpMobileNos() {
return empMobileNos;
}
public void setEmpMobileNos(String empMobileNos) {
this.empMobileNos = empMobileNos;
}
}
Testing class.
public class Test{
public static void main(String[] args) throws Exception {
SessionFactory sessFact = HibernateUtil.getSessionFactory();
Session session = sessFact.getCurrentSession();
org.hibernate.Transaction tr = session.beginTransaction();
Employee emp = new Employee();
emp.setEmpName("Deepak Kumar");
emp.setEmpMobileNos("000000");
emp.setEmpAddress("Delhi - India");
session.save(emp);
tr.commit();
System.out.println("Successfully inserted");
sessFact.close();
}
}
Edit 3
lis 17, 2017 11:54:50 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.10.Final}
lis 17, 2017 11:54:50 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
lis 17, 2017 11:54:50 PM 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.
Enitial SessionFactory creation failedorg.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 0 and column 0 in RESOURCE hibernate.cfg.xml. Message: null
Exception in thread "main" java.lang.ExceptionInInitializerError
at pl.lostandfound.HibernateUtil.<clinit>(HibernateUtil.java:31)
at pl.lostandfound.Test.main(Test.java:13)
Caused by: org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 0 and column 0 in RESOURCE hibernate.cfg.xml. Message: null
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:133)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:65)
at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:57)
at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:163)
at pl.lostandfound.HibernateUtil.<clinit>(HibernateUtil.java:24)
... 1 more
Caused by: javax.xml.bind.JAXBException
- with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory]
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:241)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:477)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:656)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:599)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:122)
... 5 more
Caused by: java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
at javax.xml.bind.ContextFinder.safeLoadClass(ContextFinder.java:594)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:239)
... 9 more
Edit 4
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Enitial SessionFactory creation failedorg.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml]
Exception in thread "main" java.lang.ExceptionInInitializerError
I would certainly first fix the ClassNotFound Exception (java.lang.ClassNotFoundException:com.sun.xml.internal.bind.v2.ContextFactory). This indicated that a class that needed to be loaded is not present...
Maybe adding the following dependency would fix your problem:
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
Most recent version taken from here: https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impl
If the ClassNotFound exception is still there...I would look more closely what version of JAXB hibernate is using. A very nice way to analyze your dependencies are the following two commands:
mvn clean dependency:analyze
and
mvn clean dependency:tree
For Edit4: check following answers:
ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml] in project root folder
Location of hibernate.cfg.xml in project?
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>
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);
}
...
}