Hibernate/Oracle Sequence not working - java

I am using hibernate and an oracle DB to try and insert a automated ID into a table using a sequence. The sequence defiantly exists on database but hibernate doesn't seem to be able to find it.
Here is all the relevant information:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
org.hibernate.exception.SQLGrammarException: could not get next sequence value
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
....
Caused by: java.sql.SQLSyntaxErrorException: ORA-02289: sequence does not exist
....
... 12 more
I know it says "Caused by: java.sql.SQLSyntaxErrorException: ORA-02289: sequence does not exist" but I can access the sequence on the database:
Table:
CREATE TABLE Property(
id INT,
address VARCHAR2(50),
town VARCHAR2(50),
postCode VARCHAR2(50),
purchasePrice INT
);
Sequence:
create sequence property_seq start with 1 increment by 1 nomaxvalue;
Mapping xml:
<class name="com.rental.model.property.Property" table="PROPERTY">
<meta attribute="class-description"> This class contains the property detail. </meta>
<id name="id" type="integer" column="id">
<generator class="sequence"/>
</id>
<property name="address" column="ADDRESS" type="string" />
<property name="town" column="TOWN" type="string" />
<property name="postCode" column="POSTCODE" type="string" />
<property name="purchasePrice" column="PURCHASEPRICE" type="integer" />
</class>
annotation:
#Id
#SequenceGenerator(name="property_seq", sequenceName="property_seq", allocationSize=1, initialValue=1)
#GeneratedValue (strategy = GenerationType.SEQUENCE, generator="property_seq")
public int getId() {
return id;
}

Why are you using xml AND #Annotation at the same time? Maybe xml definition wins against annotation and Hibernate is retriving default sequence instead of your property_seq.
Try remove xml mapping and check if it works.

Related

org.hibernate.HibernateException: could not determine type of dynamic entity

I am a beginner in Hibernate and I have the below code in one of my projects:
ShortHand o = new ShortHand();
Session sess = noprobs.getSessionFactory().openSession();
sess.getTransaction().setTimeout(noprobs.xActionTimeout);
tx = sess.beginTransaction();
sess.save(o);
For which I get the below error:
ERROR:
org.hibernate.HibernateException: could not determine type of dynamic entity
at org.hibernate.impl.SessionImpl.guessEntityName(SessionImpl.java:1770)
at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1338)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:98)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:172)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519)
at cool.wxhy.tms.xyz.ABCD.persistInDb(ABCD.java:235)
at cool.wxhy.tms.xyz.ABCD.subscribeToAmps(ABCD.java:144)
at cool.wxhy.tms.xyz.ABCD.hot(ABCD.java:102)
at cool.wxhy.service.impl.wxhyBase.start(wxhyBase.java:250)
at cool.wxhy.service.api.hello.startAllServices(hello.java:211)
at cool.wxhy.service.impl.heyhi.main(heyhi.java:43)
I am using the HIbernate 3.2.6 jar
I am using the xml config for the HIbernate and not the annotations one. Can someone please help on the issue.
Hibernate Mapping file:
<hibernate-mapping package="bofa.pioneer.tms.objects">
<class name="ShortHand" table="ShortHand">
<id name="key" column="id" unsaved-value="null" type="string" >
<generator class="assigned" />
</id>
<property name="animal" column="animal" type="string"/>
<property name="dog" column="dog" type="string"/>
Entity
public class ShortHand extends LongHand {
//getters and setters are present in the parent LongHand
}

how to exclude the dirty data which would lead to SQLException by hibernate

Please find the following mapping xml,
<class name="com.fabulous.A" table="f_a">
<id name="id" column="id">
<generator class="assigned" />
</id>
<property name="startTime" column="start_time" />
</class>
I query table f_a by batch as below, the batch size is 100:
"FROM A WHERE id IN (:ids)"
However there is a dirty row in table f_a which would lead to SQLException, and the whole batch will be failed to get.
I have only select privilege and can't delete the dirty data from DB, is there any way from hibernate to exclude the dirty data automatically by hibernate?
Yes, if query by id one by one I can make it from my application but it's inefficient and unavailable.
Could anyone help with this?
The dirty data is timestamp valued "0000:00:00".
Thanks.
Add an option <property name="hibernate.connection.zeroDateTimeBehavior">convertToNull</property>
to your hibernate.cfg.xml:
Or in hibernate.properties:
hibernate.connection.zeroDateTimeBehavior=convertToNull
I fixed it with appending ?zeroDateTimeBehavior=convertToNull on the jdbcUrl.
You may find my jdbcUrl as below
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/testdb?zeroDateTimeBehavior=convertToNull" />

Exception occurs if the position of discriminator tag in hibernate is moved down

I am new to Hibernate. I am trying to map both my super-class and sub-class to a single table.
<class name="Employee" table="EmpWithManager">
<id name="id" column="ID">
<generator class="native"></generator>
</id>
<discriminator column="EMP_TYPE" type="string"></discriminator>
<property name="firstName" column="FIRST_NAME"></property>
<property name="lastName" column="LAST_NAME"></property>
<property name="salary" column="SALARY"></property>
<subclass name="Manager" extends="Employee">
<property name="managerId" column="MAN_ID"></property>
<property name="noOfEmployees" column="NUMBER_EMP"></property>
</subclass>
</class>
This works fine but if change the position of the discriminator tag as follows:
<class name="Employee" table="EmpWithManager">
<id name="id" column="ID">
<generator class="native"></generator>
</id>
<property name="firstName" column="FIRST_NAME"></property>
<discriminator column="EMP_TYPE" type="string"></discriminator>
<property name="lastName" column="LAST_NAME"></property>
<property name="salary" column="SALARY"></property>
<subclass name="Manager" extends="Employee">
<property name="managerId" column="MAN_ID"></property>
<property name="noOfEmployees" column="NUMBER_EMP"></property>
</subclass>
</class>
This re-ordering gives me the below exception:
Caused by: org.xml.sax.SAXParseException: The content of element type "class" must match "(meta*,subselect?,cache?,synchronize*,comment?,tuplizer*,(id|composite-id),discriminator?,natural-id?,(version|timestamp)?,(property|many-to-one|one-to-one|component|dynamic-component|properties|any|map|set|list|bag|idbag|array|primitive-array)*,((join*,subclass*)|joined-subclass*|union-subclass*),loader?,sql-insert?,sql-update?,sql-delete?,filter*,fetch-profile*,resultset*,(query|sql-query)*)".
Please anybody tell me why this is happening and whether the position of discriminator should be in the beginning?
If you look at the http://hibernate.org/dtd/ entry for hibernate-mapping-3.0.dtd it defines the class element as follows. Order is important as this is a DTD. Note that discriminator? comes after (id|composite-id) and before the long entry with property. This ordering requirement is not explicitly mentioned in the (current) hibernate documentation.
<!ELEMENT class (
meta*,
subselect?,
cache?,
synchronize*,
comment?,
tuplizer*,
(id|composite-id),
discriminator?,
natural-id?,
(version|timestamp)?,
(property|many-to-one|one-to-one|component|dynamic-component|properties|any|map|set|list|bag|idbag|array|primitive-array)*,
((join*,subclass*)|joined-subclass*|union-subclass*),
loader?,sql-insert?,sql-update?,sql-delete?,
filter*,
fetch-profile*,
resultset*,
(query|sql-query)*
)>
According to the hibernate document type definitions (DTD) listed here, the position of the discriminator tag must be after the id tag. Essentially the structure of the xml document in this situation is pre-defined, and you must follow the pre-defined format, and that is why you see an error after moving the discriminator tag.
From the JBoss docs:
5.1.8 - Discriminator:
The <discriminator> element is required for polymorphic persistence using the table-per-class-hierarchy mapping strategy and declares a discriminator column of the table. The discriminator column contains marker values that tell the persistence layer what subclass to instantiate for a particular row. A restricted set of types may be used: string, character, integer, byte, short, boolean, yes_no, true_false.
I'd imagine that you must define how properties will be discriminated against before you define them and that is the reasoning for the structure within the DTD.

Creating unique Index for table in hibernate with one column being a foreign key

well I am not that advanced in hibernate and I tried to search a lot, found lots of similar questions but none really applying my case. I have a table TABLE1 which has an index "id" and another table which has as index (TABLE1_ID and NUMBER). Only TABLE1_ID is a foreign key while number doesn't reference anything specific
TABLE 1 has the following hibernate mapping
<class name="com.test.basic.BASICTABLE1"
entity-name="com.test.TABLE1" table="TABLE1"
dynamic-update="true" optimistic-lock="version">
<id name="id" type="long">
<column name="id" />
<generator class="native">
<param name="sequence">${table1_id.generator.sequence}</param>
</generator>
</id>
<version name="versionNumber" column="verno" generated="always"
access="field" />
<property name="column1" column="column1" type="string" length="19"
not-null="true" access="field" />
</class>
I am not sure what should be the mapping for the other table. I did it the following way
<class name="com.test.basic.BASICTABLE2"
entity-name="com.test.TABLE2" table="table2"
dynamic-update="true" optimistic-lock="version">
<composite-id name="id" class="com.test.basic.TABLE1TABLE2Id" >
<key-property name="TABLE1_ID" column="TABLE1_ID" type="long" />
<key-property name="NUMBER" column="NUMBER" type="short"/>
</composite-id>
</class>
Please note that I created the class TABLE1TABLE2Id after I read somewhere that there should be some intermediate mapping.
I'm sure there's something wrong with TABLE2 mapping (I am not so advanced with hibernate) but when trying to install the app, I am getting the following error
Foreign key (TABLE1 [id]) must have same number of columns as the referenced primary key (TABLE2 [TABLE1_ID, NUMBER])
I appreciate anybody's help thanks :)
Identity copy (foreign generator)
Finally, you can ask Hibernate to copy the identifier from another
associated entity. In the Hibernate jargon, it is known as a foreign
generator but the JPA mapping reads better and is encouraged.
The primary key from one entity might be as foreign key be primary key for another table.
#Entity
class MedicalHistory implements Serializable {
#Id Integer id;
#MapsId #OneToOne
#JoinColumn(name = "patient_id")
Person patient;
}
#Entity
class Person {
#Id #GeneratedValue Integer id;
}

JPA xml mapping not finding fields

I have the following class:
package lt.vic.valdos.domain.valda;
public class Valda implements java.io.Serializable {
private long id;
private Long valdosKodas;
public long getId() {
return id;
}
public Long getValdosKodas() {
return valdosKodas;
}
}
and the following orm.xml:
<?xml version="1.0"?>
<entity-mappings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.eclipse.org/eclipselink/xsds/persistence/orm http://www.eclipse.org/eclipselink/xsds/eclipselink_orm_2_1.xsd"
version="2.1">
<entity class="lt.vic.valdos.domain.valda.Valda">
<table name="VALDOS" schema="VLD" />
<attributes>
<id name="id" />
<basic name="id">
<column name="vld_id" />
<return-insert return-only="true" />
</basic>
<basic name="valdosKodas">
<column name="valdos_kodas" />
</basic>
</attributes>
</entity>
</entity-mappings>
When I deploy this in glassfish, i get the following error:
Exception [EclipseLink-7215] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Could not load the field named [id] on the class [class lt.vic.valdos.domain.valda.Valda]. Ensure there is a corresponding field with that name defined on the class.
The class is in a jar that is included into a web application as a maven dependency. The orm.xml is in /WEB-INF/classes/META-INF of the web application.
What am I doing wrong?
Figured this one out myself. For some reason EclipseLink requires a setter on a class. Once I add private setters everything seems fine. Why the setters are needed (mapping accessors should default to FIELD) remains a mystery but it is not that important for me. Adding access="FIELD" to all entity attributes also fixes the problem without the setters.
You should be specifying the id as generated using the IDENTITY strategy:
<id name="id">
<column name="vld_id"/>
<generated-value strategy="IDENTITY"/>
</id>
This strategy will automatically read the database provided id back into the new object upon successful commit. The EclipseLink returning statement functionality is only applicable to basic mappings because id is already covered by Identity ID generation.
I think you have to add the column description for the id column to your id element, instead of using an extra basic element. As in <id name="id"> <column name="vld_id" /> ... </id>, without an extra <basic name="id"> ....
From my own experience (some time ago now), it's probably easier to use annotations to define your mappings.

Categories

Resources