问题
I have the following code that attempts to fetch a generated sequence value for the primary key column COUNTRY_ID of the COUNTRY table in my Oracle (10g) database.
Country c=new Country();
c.setCountryName(request.getParameter("txtCountryName"));
c.setCountryCode(request.getParameter("txtCountryCode"));
Zone z=(Zone) session.get(Zone.class, new BigDecimal(request.getParameter("zoneId")));
c.setZone(z);
session.save(c);
session.flush();
//session.refresh(c);
System.out.println(c.getCountryId()); //Attempts to display the sequence value.
session.getTransaction().commit();
This statement System.out.println(c.getCountryId()); in this codes attempts to display the currently generated sequence value after insertion is done.
Sequence generated values in the Oracle table are inserted in multiple of 2 i.e something like this 414, 416, 418, 420... instead of being inserted them in a chain like 414, 415, 416, 417, 418, 419, 420...
Suppose, the currently inserted sequence value in the Oracle table is 426, this statement System.out.println(c.getCountryId()); shows 425 (whereas in the COUNTRY_ID column in the Oracle table, the inserted value is 426).
Presumably, it appears that the sequence is executed twice for some reasons.
In my Hibernate POJO, I have designated the countryId primary key column as follows,
@Id
@Column(name = "COUNTRY_ID")
@SequenceGenerator(name = "CountryIdSequence", sequenceName = "COUNTRY_SEQ")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CountryIdSequence")
private long countryId;
In the Country.hbm.xml mapping file, this column countryId is mapped as follows.
<id name="countryId" type="long">
<column name="COUNTRY_ID" precision="35" scale="0"/>
<generator class="sequence">
<param name="sequence">COUNTRY_SEQ</param>
</generator>
</id>
What am I missing here?
回答1:
I indeed had a trigger against the COUNTRY table which is automatically created by an Oracle GUI tool to associate the sequence with the primary key column COUNTRY_ID.
The sequence was being executed twice once by Hibernate and again by the trigger. I disabled the trigger temporarily and the approach worked as intended.
来源:https://stackoverflow.com/questions/13323165/oracle-sequence-for-a-primary-key-field-doesnt-retrieve-the-currently-inserted