to generate a table with list using hbm file - java

I am new to Hibernate and trying to make an insertion of ArrayList<String> in DB using .hbm mapping file.
I want no annotations to use.
I made a search on how to insert ArrayList<String> and found working code from here.
I was expecting that a new table containing entries of ArrayList<String> will be created on insert of POJO named ClassTime
here is ClassTime.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Jun 20, 2015 2:47:36 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.img.yogesh.Gym.ClassTime" table="CLASS_TIME">
<id name="idclass_time" type="java.lang.Integer">
<column name="IDCLASS_TIME" />
<generator class="increment" />
</id>
<property name="class_name" type="java.lang.String">
<column name="CLASS_NAME" />
</property>
<property name="repeat_boolean" type="java.lang.String">
<column name="REPEAT_BOOLEAN" />
</property>
<property name="repeat_weeks" type="java.lang.String">
<column name="REPEAT_WEEKS" />
</property>
<property name="instructor_name" type="java.lang.String">
<column name="INSTRUCTOR_NAME" />
</property>
<property name="start_on_date" type="java.util.Date">
<column name="START_ON_DATE" />
</property>
<property name="start_time_date" type="java.util.Date">
<column name="START_TIME_DATE" />
</property>
<property name="end_on_date" type="java.util.Date">
<column name="END_ON_DATE" />
</property>
<property name="end_time_date" type="java.util.Date">
<column name="END_TIME_DATE" />
</property>
<list name="repeat_days_list" table="repeat_days_list" >
<key >
<column name="repeat_id" />
</key>
<list-index column="day"></list-index>
<element type="java.lang.String">
<column name="REPEAT_DAYS_LIST" />
</element>
</list>
<property name="repeat_days_list_string" type="java.lang.String">
<column name="REPEAT_DAYS_LIST_STRING" />
</property>
</class>
</hibernate-mapping>
and java code to save data into database
session.persist(addClassTime);
transaction.commit();
and my stack trace while running the code is
Caused by: java.sql.BatchUpdateException: Table 'gym.repeat_days_list' doesn't exist
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2024)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1449)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 40 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'gym.repeat_days_list' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3597)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3529)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1990)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2151)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2625)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415)
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1976)
... 43 more
here is the hibernate.cfg.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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/gym</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="question.hbm.xml"/>
</session-factory>
</hibernate-configuration>
hoping to get an answer soon.

We can do this also with adding
<property name="hbm2ddl.auto">update</property>
in .cfg.xml file.

You need to tell Hibernate to create the table if it does not already exist. So add this line directly underneath <hibernate-mapping> in your ClassTime.hbm.xml:
<property name="hbm2ddl.auto" value="create"/>

Related

Hibernate - org.hibernate.hql.internal.ast.QuerySyntaxException: Client is not mapped

I'm new to hibernate and I'm trying to solve some problems i cannot understand too well...
For example, I have this query
Query query = session.createQuery("from Client where clientId = "+clientId+")");
List result = query.list();
My Client.hbm.xml is
<class name="it.besmart.models.Client" table="client" catalog="SMARTPARK">
<id name="idClient" type="int">
<column name="id_client" />
<generator class="identity" />
</id>
<property name="nomeClient" type="string">
<column name="nome_client" length="65535" not-null="true" />
</property>
<property name="numPosti" type="int">
<column name="num_posti" not-null="true" />
</property>
<property name="numLuci" type="int">
<column name="num_luci" not-null="true" />
</property>
<property name="inizioPosti" type="int">
<column name="inizio_posti" not-null="true" />
</property>
<property name="inizioLuci" type="int">
<column name="inizio_luci" not-null="true" />
</property>
</class>
</hibernate-mapping>
The table on the DB is called client and the column is client_id
The mapping in hibernate.cfg.xml is
<hibernate-configuration>
<session-factory name="parkserver">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">passwprd</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.3.67:3306/SMARTPARK</property>
<property name="hibernate.connection.username">parkuser</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping class="it.besmart.models.Client" resource="Client.hbm.xml"/>
<mapping class="it.besmart.models.Illuminazione" resource="Illuminazione.hbm.xml"/>
<mapping class="it.besmart.models.MappaPosti" resource="MappaPosti.hbm.xml"/>
<mapping class="it.besmart.models.Occupazione" resource="Occupazione.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I'm having no problems in another query in the application, but when i try to executer the SELECT query i got this exception
org.hibernate.hql.internal.ast.QuerySyntaxException: Client is not mapped [from Client where clientId = 1)]
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:218)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:142)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:76)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:150)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:298)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1836)
at it.besmart.parkserver.SocketClientHandler.run(SocketClientHandler.java:83)
at java.lang.Thread.run(Thread.java:744)
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Client is not mapped
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:171)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:76)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:321)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3678)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3567)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:708)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:564)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:301)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:249)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:262)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:190)
I don't know why Client is not mapped, it's correctly in the cfg file...
Thanks in advance
Try to add the full name of the class in the query:
Query query = session.createQuery("from it.besmart.models.Client where clientId = :c");
query.setString("c", clientId)
List result = query.list();
I also changed to late binding here which is preferable but has nothing to do with your problem.
As Maurice Perry pointed out in comment below:
- You can also specify the default package in the mapping file: <hibernate-mapping package="it.besmart.models">

Hibernate: Can't insert data into table

I'm not able to insert data into all my tables, select works with no problems. The user used has the permissions to insert data, i also tried inserting data manually.
All configuration files like hibernate.cfg, hibernate.reveng and hbm.xml are generated by NetBeans.
Event.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Apr 20, 2015 10:05:17 AM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="at.ac.univie.salome.domain.Event" table="event" catalog="salomeapp" optimistic-lock="version">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<property name="title" type="string">
<column name="title" not-null="true" />
</property>
<property name="desc" type="string">
<column name="desc" length="1024" />
</property>
<set name="partitions" table="partition" inverse="true" lazy="true" fetch="select">
<key>
<column name="event_id" not-null="true" />
</key>
<one-to-many class="at.ac.univie.salome.domain.Partition" />
</set>
</class>
</hibernate-mapping>
hibernate.cfg.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.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/salomeapp?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">******</property>
<property name="hibernate.connection.password">******</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="at/ac/univie/salome/domain/Partition.hbm.xml"/>
<mapping resource="at/ac/univie/salome/domain/Chunk.hbm.xml"/>
<mapping resource="at/ac/univie/salome/domain/Event.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Exception:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'desc) values ('Test', 'test')' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2794)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:187)
... 102 more
Im using Netbeans, Glassfish 4, Hibernate 4.3 and MySQL 5.6.23.
I think you're trying to use a reserved column name in your entity.
Try to change your column name.
Take a look at : http://developer.mimer.se/validator/sql-reserved-words.tml to see which words are reserved

Hibernate seems to create wrong SQL Query from HQL Query

I'm trying to extend my database program with a function to execute any hql query. I'm almost done with it but I get an error on the following process.
select p.reviews, p.title from Product p
This hql query is converted in an sql query as following:
Hibernate: select . as col_0_0_, product0_.title as col_1_0_, reviews1_.account_number as account_1_2_, reviews1_.product_id as product_2_2_, reviews1_.points as points3_2_, reviews1_.review as review4_2_ from dbprak12.view_product_meta product0_ inner join dbprak12.view_customer_evaluates reviews1_ on product0_.product_id=reviews1_.product_id
As you can obviously see, there will be thrown an error with sql state code 42601. Because " . as col_0_0_..." isn't correct syntax. But I don't understand why hibernate creates this sql query.
I use the following two xml mappings:
Product.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="media.definitions.Product" table="dbprak12.view_product_meta">
<id name="asin" column="product_id">
<generator class="native" />
</id>
<property name="title" column="title" />
<property name="avgRating" column="rating" />
<property name="salesRank" column="sales_rank" />
<property name="picUrl" column="picture" />
<set name="reviews" cascade="all" inverse="true" lazy="true">
<key column="product_id" />
<one-to-many class="media.definitions.Review" />
</set>
<set name="categories" table="dbprak12.view_product_in_category" inverse="false" lazy="true" fetch="select" cascade="all">
<key column="product_id" />
<many-to-many column="category_id" class="media.definitions.Category" />
</set>
<joined-subclass name="media.definitions.Book" table="dbprak12.view_book">
<key column="product_id" />
<property name="isbn" column="isbn" />
<property name="publishers" column="publisher" />
<property name="pubDate" column="publication" />
<property name="pages" column="pages" />
</joined-subclass>
<joined-subclass name="media.definitions.DVD" table="dbprak12.view_dvd">
<key column="product_id" />
<property name="format" column="fformat" />
<property name="regionCode" column="region_code" />
<property name="runningTime" column="running_time" />
</joined-subclass>
<joined-subclass name="media.definitions.Music" table="dbprak12.view_cd">
<key column="product_id" />
<property name="labels" column="label" />
<property name="releaseDate" column="release_date" />
</joined-subclass>
</class>
</hibernate-mapping>
Review.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="media.definitions.Review" table="dbprak12.view_customer_evaluates">
<composite-id>
<key-property name="accountNumber" column="account_number" />
<key-many-to-one name="product" class="media.definitions.Product" lazy="false">
<column name="product_id"></column>
</key-many-to-one>
</composite-id>
<property name="rating" column="points" />
<property name="content" column="review" />
</class>
</hibernate-mapping>
Edit: My Hibernate configuration file:
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>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="Product.hbm.xml"/>
<mapping resource="Category.hbm.xml"/>
<mapping resource="Review.hbm.xml"/>
<mapping resource="Person.hbm.xml"/>
<mapping resource="Offer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
db2Module.properties
#
# Database module to load
#
middleware.module:media.mediadbimpl.DB2Module
#
# Database properties
#
db.jdbc.dialect:org.hibernate.dialect.DB2Dialect
db.jdbc.driver:com.ibm.db2.jcc.DB2Driver
db.jdbc.url:jdbc:db2://anyurl.de:50001/datasource
db.user:dbuser
db.password:.dbpass.
NOTE: this is not a researched answer, so it may be incorrect.
I think your error might be here:
<column name="product_id"></column>
I think this should be
<column name="product_id" />
Having body content (even 0 characters) in a tag is different than not having body content.
(comparable to "" and null for string)
the documentation says you can use nested column elements inside the key
<key-many-to-one name="product" class="media.definitions.Product" lazy="false">
<column name="product_id" />
</key-many-to-one>
but you don't seem to use it, so you could simply do:
<key-many-to-one name="product" class="media.definitions.Product" lazy="false" column="product_id" />
the subtag is usually used for nonstandard columns.
anyways give it a shot

Hibernate mapping when cfg file and entity file are in different folders

I've got project with this structure:
When I'm trying to access dtb via hibernate, I get this exception:
Initial SessionFactory creation failed.org.hibernate.MappingException: entity class not found: user/DBUser
V 02, 2013 9:17:10 ODP. org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [mvc-dispatcher] in context with path [/fit] threw exception [Handler processing failed; nested exception is java.lang.ExceptionInInitializerError] with root cause
java.lang.ClassNotFoundException: user/DBUser
Could you please show me, how should the path in my config files look like? I've tried several combinations, but I can't figure out, how to write it.
DBUser.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="DontKnowWhatShallBeHere/DBUser" table="DBUSER">
<id name="userId" type="int">
<column name="USER_ID" precision="5" scale="0" />
<generator class="assigned" />
</id>
<property name="username" type="string">
<column name="USERNAME" length="20" not-null="true" />
</property>
<property name="createdBy" type="string">
<column name="CREATED_BY" length="20" not-null="true" />
</property>
<property name="createdDate" type="date">
<column name="CREATED_DATE" length="7" not-null="true" />
</property>
</class>
</hibernate-mapping>
hibernate.cfg.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.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3049/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="DontKnowWhatShallBeHere/DBUser.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
Everything looks alright. Can you try this and see :
<class name="user.DBUser" table="DBUSER">

Unable to use inheritence in Hibernate

Please have a look at the following
<?xml version="1.0"?>
<!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.att_marks.students.Attendance_Btech">
<id name="id" type="integer" column="id" >
<generator class="increment"/>
</id>
<property name="year">
<column name="Year" />
</property>
<property name="semister">
<column name="Semister"/>
</property>
<property name="section">
<column name="Section"/>
</property>
<property name="period">
<column name="Period"/>
</property>
<property name="subjectCode">
<column name="Subject_Code"/>
</property>
<property name="date">
<column name="Date"/>
</property>
<property name="status">
<column name="Status"/>
</property>
<union-subclass name="com.att_marks.students.Attendance_Btech_ECE" table="attendance_btech_ece">
</union-subclass>
</class>
</hibernate-mapping>
I have tables named attendance_btech_ece, attendance_btech_cse, attendance_btech_it, and so on. All these tables use the same schema as mentioned above for the Attendance_Btech class. I thought this should work but it isn't.
If the Attendance_Btech_ECE is subclass of Attendance_Btech then should work.

Categories

Resources