hibernate annotation- extending base class - values are not being set - strange error
Posted
by
gt_ebuddy
on Stack Overflow
See other posts from Stack Overflow
or by gt_ebuddy
Published on 2012-06-16T15:58:59Z
Indexed on
2012/06/17
3:17 UTC
Read the original article
Hit count: 187
I was following Hibernate: Use a Base Class to Map Common Fields and openjpa inheritance tutorial to put common columns like ID, lastModifiedDate etc in base table.
My annotated mappings are as follow :
BaseTable :
@MappedSuperclass
public abstract class BaseTable {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "lastmodifieddate")
private Date lastModifiedDate;
...
Person table -
@Entity
@Table(name = "Person ")
public class Person extends BaseTable implements Serializable{
...
Create statement generated :
create table Person (id integer not null auto_increment, lastmodifieddate datetime, name varchar(255), primary key (id)) ;
After I save a Person object to db,
Person p = new Person();
p.setName("Test");
p.setLastModifiedDate(new Date());
..
getSession().save(p);
I am setting the date field but, it is saving the record with generated ID and LastModifiedDate = null, and Name="Test".
Insert Statement :
insert into Person (lastmodifieddate, name) values (?, ?)
binding parameter [1] as [TIMESTAMP] - <null>
binding parameter [2] as [VARCHAR] - Test
Read by ID query : When I do hibernate query (get By ID) as below, It reads person by given ID.
Criteria c = getSession().createCriteria(Person.class);
c.add(Restrictions.eq("id", id));
Person person= c.list().get(0);
//person has generated ID, LastModifiedDate is null
select query select person0_.id as id8_, person0_.lastmodifieddate as lastmodi8_, person0_.name as person8_ from Person person0_
- Found [1] as column [id8_]
- Found [null] as column [lastmodi8_]
- Found [Test] as column [person8_]
ReadAll query : //read all Query query = getSession().createQuery("from " + Person.class.getName()); List allPersons=query.list();
Corresponding SQL for read all
select query select person0_.id as id8_, person0_.lastmodifieddate as lastmodi8_, person0_.name as person8_ from Person person0_
- Found [1] as column [id8_]
- Found [null] as column [lastmodi8_]
- Found [Test] as column [person8_]
- Found [2] as column [id8_]
- Found [null] as column [lastmodi8_]
- Found [Test2] as column [person8_]
But when I print out the list in console, its being more weird. it is selecting List of Person object with
- ID fields = all 0 (why all 0 ?)
- LastModifiedDate = null
- Name fields have valid values
I don't know whats wrong here. Could you please look at it?
FYI,
My Hibernate-core version : 4.1.2, MySQL Connector version : 5.1.9 .
In summary, There are two issues here
- Why I am getting All ID Fields =0 when using read all?
- Why the LastModifiedDate is not being inserted?
© Stack Overflow or respective owner