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
Related
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"/>
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">
I have two database tables, User and PageComment. Using Hibernate, I'm trying to store a Set of PageComment objects in the User comment (comments made to that user), by using one-to-many relationship in the hbm XML files.
The problem is, I seem to be able to retrieve the set from a User object, but as soon as I try to access any of the objects stored within the set, or even access on of the methods included in the set class (i.e. size()), the JVM throws "org.hibernate.exception.GenericJDBCException: could not initialize a collection". I'm at a loss on this one.
HBM For User Table:
<?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="User" table="user">
<id name="username" column="Username" type="string">
<generator class="assigned"></generator>
</id>
<property name="password" column="Password" type="string"></property>
<property name="firstname" column="Firstname" type="string"></property>
<property name="surname" column="Surname" type="string"></property>
<property name="email" column="Email" type="string"></property>
<property name="admin" column="Admin" type="integer"></property>
<set name="commentsMadeTo" inverse="true">
<key column="userMadeTo"/>
<one-to-many class="PageComment"/>
</set>
</class>
</hibernate-mapping>
HBM For PageComment:
<?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="PageComment" table="PageComment">
<composite-id>
<key-property name="userMadeBy" column="UserMadeBy" type="string" />
<key-property name="userMadeTo" column="UserMadeTo" type="string" />
<key-property name="time" column="Time" type="integer" />
<generator class="assigned"></generator>
</composite-id>
<property name="commentText" column="CommentText" type="string"></property>
<many-to-one name="userMadeTo" column="Username" not-null="true" class="User" />
</class>
</hibernate-mapping>
I'm trying to test the mapping with this method:
Session session = sessionFactory.openSession();
User theUser = (User)session.createQuery("FROM User WHERE Username='Samat'").uniqueResult();
System.out.println("Trying to print out all comments made to 'Samat'");
Set<PageComment> theComments = theUser.getCommentsMadeTo();
for(PageComment p: theComments){
System.out.println(p.getAllData());
}
I spot that there are some problems in the relationship mapping
HBM For User Table:
<set name="commentsMadeTo" inverse="true">
<key column="XXXXXXXX"/>
<one-to-many class="PageComment"/>
</set>
HBM For PageComment:
<many-to-one name="userMadeTo" column="XXXXXXX" not-null="true" class="User" />
The value XXXXX represents the column name on the "many" side (i.e PageComment table in your case) that associates to its "One" side. It should have the same value in both mapping hbm.
Try to change the hbm for user table to:
<set name="commentsMadeTo" inverse="true">
<key column="Username"/>
<one-to-many class="PageComment"/>
</set>
I am trying to make hibernate load my whole tree with no success.
I have a schema like this
A Category can have many attribute and an attribute can have many options
Category
--->Attribute1
--->AttributeOption1
--->AttributeOption3
--->Attribute2
--->AttributeOption1
--->AttributeOption1
but when I am using hibernate, it is not loading the whole tree:
my mapping file are:
Attribute Mapping FIle:
<?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 Dec 16, 2010 5:25:09 AM by Hibernate Tools 3.4.0.Beta1 -->
<hibernate-mapping>
<class name="com.BiddingSystem.Models.Attribute" table="ATTRIBUTE">
<id name="AttributeId" type="long">
<column name="ATTRIBUTEID" />
<generator class="native" />
</id>
<property name="AttributeName" type="java.lang.String">
<column name="ATTRIBUTENAME" />
</property>
<set name="Options" table="ATTRIBUTEOPTION" inverse="false" cascade="all" lazy="true">
<key>
<column name="ATTRIBUTEID" />
</key>
<one-to-many class="com.BiddingSystem.Models.AttributeOption" />
</set>
</class>
</hibernate-mapping>
Attribute Option Mapping File:
<?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 Dec 16, 2010 5:25:09 AM by Hibernate Tools 3.4.0.Beta1 -->
<hibernate-mapping>
<class name="com.BiddingSystem.Models.AttributeOption" table="ATTRIBUTEOPTION">
<id name="AttributeOptionId" type="long">
<column name="ATTRIBUTEOPTIONID" />
<generator class="native" />
</id>
<property name="Option" type="java.lang.String">
<column name="OPTION" />
</property>
<property name="SQLValue" type="java.lang.String">
<column name="SQLVALUE" />
</property>
</class>
</hibernate-mapping>
Category Mapping File:
<?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 Dec 16, 2010 8:37:02 AM by Hibernate Tools 3.4.0.Beta1 -->
<hibernate-mapping>
<class name="com.BiddingSystem.Models.Category" table="CATEGORY">
<id name="CategoryId" type="long">
<column name="CATEGORYID" />
<generator class="native" />
</id>
<property name="CategoryName" type="java.lang.String">
<column name="CATEGORYNAME" />
</property>
<many-to-one name="ParentCategory" class="com.BiddingSystem.Models.Category">
<column name="PARENT_CATEGORY_ID" />
</many-to-one>
<set name="SubCategory" lazy="true" cascade="all-delete-orphan" inverse="true">
<key>
<column name="PARENT_CATEGORY_ID" />
</key>
<one-to-many class="com.BiddingSystem.Models.Category" />
</set>
<set name="AllAttributes" table="ATTRIBUTE" inverse="false" lazy="true" cascade="all">
<key>
<column name="CATEGORYID" />
</key>
<one-to-many class="com.BiddingSystem.Models.Attribute" />
</set>
</class>
</hibernate-mapping>
The function that loads the parent category are:
public List <Category> getCategory(long CategoryId)
{
Session session = gileadHibernateUtil.getSessionFactory().openSession();
List <Category> AllCategory= new LinkedList<Category> ();
String SQL="from Category where parent_category_id is NULL";
Query query = session.createQuery(SQL);
return query.list();
}
Make all your associations lazy=false; by default the lazy = true
I believe there is an other mistake:
String SQL="from Category where parent_category_id is NULL";
Query query = session.createQuery(SQL);
org.hibernate.Session.createQuery(String queryString) requires a HQL Query String, but not a SQL query! And from Category where parent_category_id is NULL seems to be a SQL query, because parent_category_id is a column name but not a property / field name.
I'm building a data warehouse and want to use InfiniDB as the storage engine. However, it doesn't allow primary keys or foreign key constraints (or any constraints for that matter).
Hibernate complains "The database returned no natively generated identity value" when I perform an insert.
Each table is relational, and contains a unique integer column that was previously used as the primary key - I want to keep that, but just not have the constraint in the db that the column is the primary key.
I'm assuming the problem is that Hibernate expects the db to return a generated key. Is it possible to override this behaviour so I can set the primary key field's value myself and keep Hibernate happy?
-- edit --
Two of the mappings are as follows:
<?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 1, 2010 2:49:51 PM by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
<class name="com.example.project.Visitor" table="visitor" catalog="orwell">
<id name="id" type="java.lang.Long">
<column name="id" />
<generator class="identity" />
</id>
<property name="firstSeen" type="timestamp">
<column name="first_seen" length="19" />
</property>
<property name="lastSeen" type="timestamp">
<column name="last_seen" length="19" />
</property>
<property name="sessionId" type="string">
<column name="session_id" length="26" unique="true" />
</property>
<property name="userId" type="java.lang.Long">
<column name="user_id" />
</property>
<set name="visits" inverse="true">
<key>
<column name="visitor_id" />
</key>
<one-to-many class="com.example.project.Visit" />
</set>
</class>
</hibernate-mapping>
and:
<?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 1, 2010 2:49:51 PM by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
<class name="com.example.project.Visit" table="visit" catalog="orwell">
<id name="id" type="java.lang.Long">
<column name="id" />
<generator class="identity" />
</id>
<many-to-one name="visitor" class="com.example.project.Visitor" fetch="join" cascade="all">
<column name="visitor_id" />
</many-to-one>
<property name="visitId" type="string">
<column name="visit_id" length="20" unique="true" />
</property>
<property name="startTime" type="timestamp">
<column name="start_time" length="19" />
</property>
<property name="endTime" type="timestamp">
<column name="end_time" length="19" />
</property>
<property name="userAgent" type="string">
<column name="user_agent" length="65535" />
</property>
<set name="pageViews" inverse="true">
<key>
<column name="visit_id" />
</key>
<one-to-many class="com.example.project.PageView" />
</set>
</class>
</hibernate-mapping>
As you noted in a comment, there're many id generators you can use. E.g., you many find 'increment' convenient. Complete overview
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-declaration-id
And hibernate won't care about your db restrictions (both primary keys and foreign keys). In fact, hibernate has no way of knowing about certain db restriction until it's violated. And if restriction doesn't exist, it can never be violated :)
You can remove the <generator class="identity" /> element and set the id manually before saving the object.