Hibernate's generator class not really working? - java

Asking this question here after hours of frustration with me and my Eclipse. Hoping to find some respite here.
I'm trying to save a pojo object into MySQL database via Hibernate 3.0. Basically my requirement is: I need to assign the id for the object before save and not let Hibernate do it for me.
For this I looked up in the documentation and saw that <generator class="assigned"/> perfectly fits my bill. Consequently I updated by .hbm.xml file with the following for the id:
<id name="id" type="int">
<column name="ID" />
<generator class="assigned" />
</id>
My pojo matches .hbm.xml file to the T.
I'm setting all the parameters including the ID of my pojo and calling Hibernate's saveOrUpdate(object) method.
If it's of any help, the ID column of my database table has "auto-inc" disabled.
Unbelievably, when I look at the database table contents, a row has been inserted with Hibernate's own ID and not what I had set.
How's it possible? Is there anything else affecting the ID? Am I missing on something? What's the work around?
My hibernate.properties looks like below(if it's of any help):
hibernate.connection.driver_class =com.mysql.jdbc.Driver
hibernate.dialect =org.hibernate.dialect.MySQLDialect
hibernate.connection.url =jdbc:mysql://localhost/dbdbdbdbdb
hibernate.connection.username=root
hibernate.connection.password=password
hibernate.connection.pool_size=10
jdbc.batch_size=30
hibernate.show_sql=true
hibernate.current_session_context_class=true
hibernate.hbm2ddl.auto=validate
hibernate.cglib.use_reflection_optimizer=false
hibernate.generate_statistics=true
hibernate.cache.use_query_cache=true
hibernate.cache.region.factory_class=net.sf.ehcache.hibernate.EhCacheRegionFactory

Well, hoax alarm!. It was really an issue with Eclipse-Tomcat integration. I had to clean up Tomcat's directories and republish before the hbm files could take effect.
Tip: If you run ant within Eclipse, be sure to keep refreshing Eclipse workspace every now and then. Learning some things the hard way.

You can write your custom sequence generator class to return ids suitable to your requirement. For more details follow: http://danu-javastuff.blogspot.com/2009/01/custom-id-generator-class-for-hibernate.html

Related

Spring + Hibernate: configuring PK generator?

We use Spring + Hibernate for a Webapp.
This Webapp will be deployed on two unrelated production sites. These two production sites will use the Webapp to generate and use Person data in parallel.
What I need to do, is to make sure that the Persons generated on these two unrelated production sites all have distinct PKs, so that we can merge the Person data from these two sites at any time.
A further constraint imposed to me is that these PKs fit in a Long, so I can't use UUIDs.
What I'm trying to do is to change the current hibernate mapping, that has sequence S_PERSON as generator:
<hibernate-mapping default-cascade="save-update" auto-import="false">
<class name="com.some.domain.Person" abstract="true">
<id name="id">
<column name="PERSON_ID"/>
<generator class="sequence">
<param name="sequence">S_PERSON</param>
</generator>
</id>
...
</hibernate-mapping>
into something configurable, so that PERSON_ID have its PKs generated from different sequences (maybe S_PERSON_1 and S_PERSON_2) depending on the deployment site's Spring configuration files.
Of course,
<generator class="sequence">
<param name="sequence">${sequenceName}</param>
</generator>
doesn't work, so I have to figure out something else... I guess my generator should point to a configurable bean that in turn points to a sequence or another, but I can't figure how to do that...
Any ideas or workaround?
You could use sequences on both production systems, but define them differently:
Production System 1:
CREATE SEQUENCE sequence_name START WITH 1 INCREMENT BY 2;
Production System 2:
CREATE SEQUENCE sequence_name START WITH 2 INCREMENT BY 2;
The first sequence will generate only odd numbers, the second only even numbers.

What is the meaning of "Frozen" attribute?

My model.xml file contain following code fragment. but I don't know why they are used.I used Spring and Hibernate technologies to build the project. hopes some expert explanation about this code fragment and the attributes?
<one-to-one fetch-type="lazy" name="followUp" type="FollowUp" synthetic="true"
nullable="true" access="frozen">
<documentation>Synthetic property of the latest follow ups made for
this Prescription.
</documentation>
</one-to-one>

How to Create DB Context File in hibernate in java like Entity Framework c#

I have been working in .NET using Entity Framework with fluent API.
I created database context with all the relations of entities to map with tables and relations with entities with one to many etc.
I know the annotations way and mapping via XML files.
Following is the code in c#
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.Property(u => u.DisplayName)
.HasColumnName("display_name");
}
}
Can any one tell me how to set a file in hibernate in JAVA to create the Blogs table for entity Blog and set properties for any entity with database rather then creating adding annotations.
Just some suggesions: Hibernate does not have the concept of Context but I usually insert a Context class where I set Hibernate Configuration class (one time for the project) and where I retrieve a session (Configuration.BuildSessionFactory() to get a ISessionFactory one time for the project and then ISessionFactory.OpenSession() or other methods similar to it). A session is the class where you start to build queries and insert/update/delete objects (so the usage is similar to the EF Context - you don't implement a Session like a DbContext -).
Usually you build the mapping using xml files like this
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="FiPlan.Data.Entities" assembly="FiPlan.Engine">
<class name="Account" table="Accounts" >
<id name="Id" column="ID" type="String" length="15" >
<generator class="assigned" />
</id>
<property name="Description" column="Description" type="String" not-null="false" length="50" />
</class>
</hibernate-mapping>
You add this files to the Configuration class (the one where you start to get a session).
Another consideration: there isn't the DbSet concept (every configured class can be accessed via queries).
I know that is not what you are looking for but I hope that this could be an help when you will start to read the Hibernate manual.
In short - I didnt find any way to create mapping or file like context for hibernate like in Entity Framework .NET

Hibernate GUID local generator

I use hibernate to generate ids for my MySQL data-tables:
<class name="XXXX" table="XXXX">
<id name="Id" column="Id" type="string">
<generator class="guid"/>
</id>
....
</class>
it works fine.
however, when i profiling the sql queried, there are 2 sqls for 1 insert:
1).select uuid() and then 2).insert ....
I have 3 questions:
why not hibernate generates the "GUID"s locally?
how much is the overhead for "select uuid()" than "UUID.randomUUID()" for one insert?
can i config a "local" generator in hibernate?
AFAIK the GUID generator is deprecated and you should use the new(er) UUIDGenerator instead. See http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#d0e5294.
But to answer your questions
That is how the GUID generator functions it calls the database and the result is passed into the id field of the object
No idea, measure, however I guess the impact is negligible as the only thing you do additionally is return a simply value
Yes but why as it is already supported by Hibernate (see the documentation)

Trying to specify default value for property in hibernate

I'm getting the following error message from hibernate when attempting to insert a row into a table:
org.hibernate.exception.ConstraintViolationException: Column
'priority' cannot be null
I know that I could put a line into the code to set the value but there are many other instances where the program relies on the default value in the database (db is mysql).
I read somewhere that you can provide a default value in the hbm.xml file but hibernate is not recognizing it. Here's the corresponding section from JobQueue.hbm.xml
<property name="priority" type="integer">
<column name="priority" default="0" />
</property>
I suppose another option would be to modify the JobQueue.java file that gets generated (I'm using eclipse hibernate tools to auto generate the hibernate classes) but for now I'd like to try to get the hbm.xml configuration to work.
I'm using version 4.1.3 of the hibernate libraries and eclipse hibernate tools 3.4.0.x.
default="0" is only relevant for SchemaExport which generates the database schema. other than that hibernate completely ignores this setting. you could try to set not-null="true" for the column.
Unless you are not able to recreate the whole database schema, you can set the default value in the variable initialization.
In your model set the priority to 0 in the initialization.
In your class:
private Integer priority = 0;
I ended up modifying the JobQueue.java POJO to set the default value. To make sure that the Code Generation of hibernate tools wouldn't overwrite this change, I set it up so that the code generation generates the files in a temp folder and then the necessary files are copied over to the permanent source location.

Categories