Hibernate won't create table even though it shows in the sql - java

Hibernate won't create a specific table called "Product", even though it shows the create table command in the sql.
Category table gets created just fine...
These are classes ;
** BaseObject.java **
#MappedSuperclass
public class BaseObject implements Serializable
{
public static final long serialVersionUID = 1L;
#Id
#GeneratedValue
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
Category.java
#Entity
public class Category extends BaseObject {
private String name;
#OneToMany(fetch=FetchType.LAZY,mappedBy="category",orphanRemoval=true)
private List<Product> products;
#OneToOne(optional=true)
private Category parent;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public Category getParent() {
return parent;
}
public void setParent(Category parent) {
this.parent = parent;
}
}
Product.java
#Entity
public class Product extends BaseObject{
#ManyToOne
private Category category;
private String jargonCode;
private int order;
private String dataTableJson;
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public String getDataTableJson() {
return dataTableJson;
}
public void setDataTableJson(String dataTableJson) {
this.dataTableJson = dataTableJson;
}
public String getJargonCode() {
return jargonCode;
}
public void setJargonCode(String jargonCode) {
this.jargonCode = jargonCode;
}
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
}
Spring Conf
<jee:jndi-lookup id="dataSource" jndi-name="${jdni.dataSource}"
expected-type="javax.sql.DataSource" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.dataCollector.pojo.Category</value>
<value>com.dataCollector.pojo.Product</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.showSql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.action}</prop>
</props>
</property>
</bean>
The product won't get created. The strange thing is, it puts the create table command in the sql...
Hibernate: alter table Category drop foreign key FK_p6elut499cl32in8b8j8sy2n4
Hibernate: alter table Product drop foreign key FK_b7afq93qsn7aoydaftixggf14
Hibernate: drop table if exists Category
Hibernate: drop table if exists Product
Hibernate: create table Category (id bigint not null auto_increment, name varchar(255), parent_id bigint, primary key (id))
Hibernate: create table Product (id bigint not null auto_increment, dataTableJson varchar(255), jargonCode varchar(255), order integer not null, category_id bigint, primary key (id))
Hibernate: alter table Category add constraint FK_p6elut499cl32in8b8j8sy2n4 foreign key (parent_id) references Category (id)
Hibernate: alter table Product add constraint FK_b7afq93qsn7aoydaftixggf14 foreign key (category_id) references Category (id)
I really don't understand why.. I use MySQL server.
And I've tried setting hibernate.hbm2ddl.auto to both create and create-drop. But nothing. Can anyone help me ?

Try to change the 'order' column name, is a reserved word, formally the sql is correct by I had a similar issue calling a column 'user' instead of 'userId'

Related

Optional one to one relationship - hibernate

This is about as simple as it gets - A company (Company table) can have a PIA agreement (PIA table) but isn't required to have one. I have tried the entire day searching all over stack overflow and google with different wording and still cannot find a solution that works for SELECT, INSERT, AND UPDATE. I found some half-decent documentation on one-to-one vs many-to-one in Hibernate, but the examples are very vague. https://docs.jboss.org/hibernate/core/3.3/reference/en-US/html/mapping.html search this text "5.1.13. One-to-one"
create_company.sql
CREATE TABLE company (
id SMALLINT AUTO_INCREMENT,
name varchar(60) default NULL,
PRIMARY KEY (id)
);
create_pia.sql
CREATE TABLE pia (
company_id smallint,
agreement_number varchar(50),
PRIMARY KEY (company_id),
CONSTRAINT pia_ibfk_1 FOREIGN KEY (company_id) REFERENCES company (id)
);
Note: It seems cascade="all" was needed to get UPDATE to work.
When I use this:
<one-to-one name="pia" class="something.something.Pia" cascade="all"/>
SELECT and UPDATE both work, but INSERT Fails with this error:
java.sql.SQLException: Cannot add or update a child row: a foreign key constraint fails (`iti101088_15112`.`pia`, CONSTRAINT `pia_ibfk_1` FOREIGN KEY (`company_id`) REFERENCES `company` (`id`))
When I use this:
<many-to-one name="pia" class="something.something.Pia" cascade="all"/>
I get this when fetching the company:
Caused by: java.sql.SQLException: Unknown column 'company0_.pia' in 'field list'
When I use this:
<many-to-one name="pia" class="something.something.Pia" cascade="all" property-ref="companyId"/>
I get the same error when fetching the company:
Caused by: java.sql.SQLException: Unknown column 'company0_.pia' in 'field list'
When I use this:
<many-to-one name="pia" class="something.something.Pia" cascade="all" property-ref="companyId" column="id"/>
I get NullPointerException when fetching the company???????????
When I use the suggestion from here Hibernate doesn't support optional one-to-one (see HHH-2007) so you'll have to use a fake many-to-one with not-null="false" instead
Optional one-to-one mapping in Hibernate
<many-to-one name="pia" class="something.something.Pia" cascade="all" not-null="false"/>
I get this familiar error when fetching the company:
Caused by: java.sql.SQLException: Unknown column 'company0_.pia' in 'field list'
When I tweak it a little bit as such:
<many-to-one name="pia" class="something.something.Pia" cascade="all">
<column name="id" not-null="false"/>
</many-to-one>
I get this very strange error:
Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: could not initialize proxy [something.something.Pia#1] - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy [something.something.Pia#1] - no Session (through reference chain: something.something.Company["pia"]->something.something.Pia$HibernateProxy$54WqyDsD["agreementNumber"])
The code
Company.hbm.xml
<class name="something.something.Company" table="COMPANY">
<id name="id" column="ID">
<generator class="increment"/>
</id>
<property name="name" column="NAME"/>
<many-to-one name="pia" class="something.something.Pia" cascade="all"/>
</class>
Pia.hbm.xml
<class class="something.something.Pia" table="PIA">
<id name="companyId" column="COMPANY_ID"/>
<property name="agreementNumber" column="AGREEMENT_NUMBER"/>
</class>
Company.java
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
public Company() { }
public Company(int id, String name, Pia pia) {
//I have no idea if this even does anything
super();
this.id = id;
this.name = name;
Pia companyPia = pia;
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Pia getPia() { return pia; }
public void setPia(Pia pia) { this.pia = pia; }
}
Pia.java
public class Pia implements Serializable {
private int companyId;
private String agreementNumber;
public Pia() { }
public Pia(int companyId, String agreementNumber) {
this.companyId = companyId;
this.agreementNumber = agreementNumber;
}
public int getCompanyId() { return companyId; }
public void setCompanyId(int companyId) { this.companyId = companyId; }
public String getAgreementNumber() { return agreementNumber; }
public void setAgreementNumber(String agreementNumber) { this.agreementNumber = agreementNumber; }
}
SELECT statement execution java code:
#Override
public Company findCompanyByCompanyId(int companyId) {
return (Company) DataAccessUtils.singleResult(template.find("from Company where id=?0", companyId));
}
INSERT statement execution java code:
#Override
#Transactional
public int insertCompany(Company company) {
int result = -1;
try {
template.save(company);
result = company.getId();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return result;
}
UPDATE statement execution java code:
#Override
#Transactional
public int updateCompany(Company myCompany) {
int result = 0;
try {
template.update(myCompany);
result = 1;
} catch (Exception e) {
logger.error(e.getMessage(), e);
result = -1;
}
return result;
}
Well, that's what you get when you read documentation for versions that are more than 15 years old. Here is the current documentation: https://docs.jboss.org/hibernate/orm/5.6/userguide/html_single/Hibernate_User_Guide.html#associations-one-to-one
Instead of googling and looking on stack overflow, try the official project website https://hibernate.org where you can find all the information you need. As for your model, it's pretty simple. This is all you need:
#Entity
public class Company {
#Id
private int id;
private String name;
#OneToOne(fetch = FetchType.LAZY, mappedBy = "company", cascade = CascadeType.ALL)
Pia pia;
}
#Entity
public class Pia {
#Id
#OneToOne(fetch = LAZY)
private Company company;
private String agreementNumber;
}

Hibernate persistence: Column not found

I am getting Column not found error during, and I can't figure out what is wrong, so I ask for help.
I need to generate a list of Task that references User and Project.
I am using h2 database.
Here are the tables:
CREATE TABLE TASK.APP_USER (
id INT NOT NULL GENERATED ALWAYS AS IDENTITY,
username VARCHAR(25) NOT NULL,
firstName VARCHAR(25) NOT NULL,
lastName VARCHAR(25) NOT NULL,
password VARCHAR(32) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE TASK.PROJECT (
id INT GENERATED ALWAYS AS IDENTITY,
name VARCHAR(50) NOT NULL,
companyName VARCHAR(50) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE TASK.PROJECT_TASK (
id INT GENERATED ALWAYS AS IDENTITY,
projectId INT NOT NULL,
userId INT NOT NULL,
description VARCHAR(500) NOT NULL,
estimatedDurationHours INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (projectId) REFERENCES TASK.PROJECT(id),
FOREIGN KEY (userId) REFERENCES TASK.APP_USER(id),
);
Here is the DAO class:
#Repository
public class TaskDaoHibernate implements TaskDao {
public TaskDaoHibernate() {
}
#Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
#SuppressWarnings("unchecked")
#Override
public List<User> fetchAllUsers() {
return getCurrentSession().createQuery("from User").list();
}
#Override
public User fetchUserById(Integer userId) {
return (User) getCurrentSession().get(User.class, userId);
}
#SuppressWarnings("unchecked")
#Override
public List<Project> fetchAllProjects() {
return getCurrentSession().createQuery("from Project").list();
}
#Override
public Project fetchProjectById(Integer projectId) {
return (Project) getCurrentSession().get(Project.class, projectId);
}
#Override
public void saveTask(Task task) {
getCurrentSession().save(task);
}
#SuppressWarnings("unchecked")
#Override
public List<Task> fetchAllTasks() {
return getCurrentSession().createQuery("from Task").list();
}
#Override
public Task fetchTaskById(Integer taskId) {
return (Task) getCurrentSession().get(Task.class, taskId);
}
#Override
public void editTask(Task task) {
getCurrentSession().update(task);
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
Here is the User class, I've mapped Project class on same principle:
#Entity
#Table(name="TASK.PROJECT")
public class Project implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#Column(name = "ID")
#GeneratedValue
private Integer id;
#Column(name = "NAME")
private String nazivProjekta;
#Column(name = "COMPANYNAME")
private String nazivTvrtke;
#ManyToOne
#JoinColumn(name="PROJECTID")
private Task task;
//setters, getters and overrided equal and hashcode methods
And last class is the Task class:
#Entity
#Table(name="TASK.PROJECT_TASK")
public class Task implements Serializable {
/**
*
*/
private static final long serialVersionUID = -4633753821563474175L;
#OneToMany(mappedBy="id", fetch=FetchType.EAGER)
private List<User> user;
#OneToMany(mappedBy="id", fetch=FetchType.EAGER)
private List<Project> project;
#Column(name = "DESCRIPTION ")
private String opisZadatka;
#Column(name = "ESTIMATEDDURATIONHOURS")
private Integer trajanje;
#Id
#Column(name = "ID")
#GeneratedValue
private Integer id;
public Task(){
}
And here is the beggining of stack trace:
org.h2.jdbc.JdbcSQLException: Column "USER0_.USERID" not found; SQL statement:
select user0_.ID as ID1_2_0_, user0_.ID as ID1_0_0_, user0_.ID as ID1_0_1_, user0_.FIRSTNAME as FIRSTNAM2_0_1_, user0_.USERNAME as USERNAME3_0_1_, user0_.LASTNAME as LASTNAME4_0_1_, user0_.USERID as USERID5_0_1_, task1_.ID as ID1_2_2_, task1_.DESCRIPTION as DESCRIPT2_2_2_, task1_.ESTIMATEDDURATIONHOURS as ESTIMATE3_2_2_ from TASK.APP_USER user0_ left outer join TASK.PROJECT_TASK task1_ on user0_.USERID=task1_.ID where user0_.ID=? [42122-176]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:344)
at org.h2.message.DbException.get(DbException.java:178)
at org.h2.message.DbException.get(DbException.java:154)
I think that I've posted all relevant info, but if something else is needed, I will gladly add it
Your Task entity has a List<User>, that expects your User to have a #ManyToOne relationship.
However, your table TASK.PROJECT_TASK has an FK to the TASK.APP_USER table. Meaning, the Task has a #ManyToOne relationship to the User, not the other way around.
You mappings are incorrect taking your table descriptions as the source of truth.
The relationship from project to task should be OneToMany and not ManyToOne.
Likewise the relationship from task to project should be ManyToOne and not OneToMany
The relationship between task and user should be ManyToOne and not OneToMany

Hibernate one to one mapping. Schema generation issue

I am generating schema with hibernate mapping. But for some reason by one to one mapping is not getting generated properly. Here are my classes:
#Entity
#Table(name = "resturant")
public class Restaurant {
private Integer restid;
private String restaurantName;
private Foursquare foursquare;
#Id
#Column(name = "restid")
#GeneratedValue(strategy = GenerationType.AUTO)
public Integer getId() {
return restid;
}
public void setId(Integer id) {
this.restid = id;
}
#OneToOne(fetch = FetchType.LAZY, mappedBy = "restaurant", cascade = CascadeType.ALL)
public Foursquare getFoursquare() {
return foursquare;
}
public void setFoursquare(Foursquare foursquare) {
this.foursquare = foursquare;
}
#Column(name = "restname")
public String getRestaurantName() {
return restaurantName;
}
public void setRestaurantName(String restaurantName) {
this.restaurantName = restaurantName;
}
}
and,
#Entity
#Table(name = "foursquare")
public class Foursquare {
private Integer foursquareid;
private Restaurant restaurant;
#Id
#Column(name = "fsid")
#GeneratedValue(strategy = GenerationType.AUTO)
public Integer getFoursquareid() {
return foursquareid;
}
public void setFoursquareid(Integer foursquareid) {
this.foursquareid = foursquareid;
}
#OneToOne(fetch = FetchType.LAZY)
#PrimaryKeyJoinColumn
public Restaurant getRestaurant() {
return restaurant;
}
public void setRestaurant(Restaurant restaurant) {
this.restaurant = restaurant;
}
}
My hbm file looks like:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- You need to complete the configuration here. This is just a sample,
you should use a connection pool -->
<property name="connection.url">jdbc:mysql://localhost:3306/menus3</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.jdbc.batch_size">50</property>
<property name="hibernate.cache.use_second_level_cache">false</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping class="Restaurant" />
<mapping class="Foursquare" />
</session-factory>
</hibernate-configuration>
Here is my HibernateUtil class:
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public final class HibernateUtil {
private static SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
private HibernateUtil() {
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
I am running a simple class to generate the schema by just loading the configuration:
public class Test {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.close();
}
}
This should create a foreign key of restid in Foursquare table but it does not. The sql looks like:
Hibernate: drop table if exists foursquare
Hibernate: drop table if exists resturant
Hibernate: create table foursquare (fsid integer not null auto_increment, idinfoursquare varchar(255), primary key (fsid))
Hibernate: create table resturant (restid integer not null auto_increment, restname varchar(255), staddress varchar(255), primary key (restid))
Can anyone point out why the one to one mapping is not getting reflected in my DB? Why the foreign key column is not getting generated?
You used #PrimaryKeyJoinColumn. The #PrimaryKeyJoinColumn annotation does say that the primary key of the entity is used as the foreign key value to the associated entity. So foreign key is not getting generated. To generate foreign key you should remove #PrimaryKeyJoinColumn annotaion.
#OneToOne(fetch = FetchType.LAZY)
//#PrimaryKeyJoinColumn Remove this annotation.
public Restaurant getRestaurant() {
return restaurant;
}

Java Hibernate - OneToMany relationship returning a null object (annotations)

I'm currently struggling with a mapping of one to many using annotations in hibernate, whenever I get an object, the set of items returned from the related table is always null (even when I can see in the database there are corresponding relationships with data). I have some many to one relationships in the same class which are working fine.
Other unrelated code omitted for readability
I have two tables, where a single member, can have 0 or more member membership periods:
CREATE TABLE member (
member_id INT NOT NULL AUTO_INCREMENT
PRIMARY KEY (member_id)
)
CREATE TABLE member_membership_period (
member_membership_period_id INT NOT NULL AUTO_INCREMENT ,
member_id INT NOT NULL ,
test_column VARCHAR(45) NOT NULL ,
PRIMARY KEY (member_membership_period_id) ,
INDEX member_membership_period_member_idx (member_id ASC) ,
CONSTRAINT member_membership_period_member
FOREIGN KEY (member_id)
REFERENCES member (member_id)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
The Member class maps to the member table:
#Entity
#Table(name="member")
public class Member implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "member_id")
private int id;
#OneToMany
#JoinColumn(name = "member_id")
#ForeignKey(name = "member_membership_period_member")
private Set<MemberMembershipPeriod> memberMembershipPeriods = new HashSet<MemberMembershipPeriod>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Set<MemberMembershipPeriod> getMemberMembershipPeriods() {
return memberMembershipPeriods;
}
public void setMemberMembershipPeriods(Set<MemberMembershipPeriod> memberMembershipPeriods) {
this.memberMembershipPeriods = memberMembershipPeriods;
}
}
And the MemberMembershipPeriod class maps to the member_membership_period table
#Entity
#Table(name="member_membership_period")
public class MemberMembershipPeriod implements Serializable {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
#Column(name = "member_membership_period_id")
private int id;
#Column(name = "test_column")
String testColumn;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTestColumn() {
return testColumn;
}
public void setTestColumn(String testColumn) {
this.testColumn = testColumn;
}
}
My DAO
public class MemberDaoImpl extends AbstractDAO<Member> implements MemberDao {
public MemberDaoImpl(SessionFactory factory) {
super(factory);
}
#Override
public List<Member> getAllMembers() {
Query query = currentSession().createQuery("from Member");
return list(query);
}
#Override
public Member getMemberById(int id) {
return get(id);
}
}
Implementation of get(id) (Part of drop wizards hibernate package)
protected E get(Serializable id) {
return (E) currentSession().get(entityClass, checkNotNull(id));
}
Any help provided would be greatly appreciated, I'm starting to lose the will to live over this!
Other tech being used is DropWizard (which does the hibernate configuration) and MySQL
Try this. It may help you.
#Override
public List<Member> getAllMembers() {
Criteria criteria = currentSession().createCriteria(Member.class,"member");
criteria.createAlias("member.memberMembershipPeriods","period");
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
return criteria.list();
}

Inheritance in hibernate

I would like to implement inheritance in Hibernate.
I created ObjectClass object:
#Entity
#Table(name = "object")
#Inheritance(strategy = InheritanceType.JOINED)
public class ObjectClass {
private id;
}
and CodeTable object that inhertance Object class:
#Entity
#ForeignKey(name = "id")
#Table(name = "code_table")
public class CodeTable extends ObjectClass{
private String description;
}
in the database
object table is:
CREATE TABLE `object` (
`id` bigint(11) NOT NULL auto_increment,
PRIMARY KEY (`id`),
)
code_table table is:
-
CREATE TABLE `code_table` (
`id` bigint(11) NOT NULL auto_increment,
`description` varchar(45) character set latin1 default NULL,
PRIMARY KEY (`id`),
KEY `FK_object` (`id`),
CONSTRAINT `FK_object` FOREIGN KEY (`id`) REFERENCES `object` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
)
I wrote the following code to retreive data from codeTable:
#SuppressWarnings( "unchecked" )
#Transactional( readOnly = true, propagation = Propagation.REQUIRED )
public Collection<CodeTable> findAll() {
Session session = getSessionFactory().getCurrentSession();
return
session.createCriteria( persistentClass
).setResultTransformer( Criteria.DISTINCT_ROOT_ENTITY
).list();
}
I gets empty list although there is one record in codetable table.
When I write the following SQL in my database:
SELECT * FROM `code_table`
I get:
id= 1,
description = company.
What went wrong in my Hibernate definition? How can I retrieve the object?
EDITED:
My hibernate.cfg.xml file looks like this:
<hibernate-configuration>
<session-factory>
<mapping class="com.mycompany.model.CodeTable" />
<mapping class="com.mycompany.model.ObjectClass" />
</session-factory>
</hibernate-configuration>
Your mappings and table structure are (roughly) correct for a JOINED inheritance strategy and I cannot reproduce your problem.
I use the following mappings (which are basically the one you provided):
#Entity
#Table(name = "object")
#Inheritance(strategy = InheritanceType.JOINED)
public class ObjectClass {
#Id #GeneratedValue
private Long id;
public ObjectClass() { }
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
}
And
#Entity
#ForeignKey(name = "id")
#Table(name = "code_table")
public class CodeTable extends ObjectClass{
private String description;
public CodeTable() { }
public String getDescription() { return description; }
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "CodeTable [getDescription()=" + getDescription() + ", getId()="
+ getId() + "]";
}
}
The following tables:
create table code_table (
description varchar(255),
id bigint not null,
primary key (id)
)
create table object (
id bigint not null,
primary key (id)
)
alter table code_table
add constraint id
foreign key (id)
references object
And the following parent/child records:
insert into object values (1);
insert into code_table(id, description) values (1, 'foo');
And running your criteria query:
session.createCriteria(CodeTable.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.list();
Returns:
CodeTable [getDescription()=foo, getId()=1]
Everything works as expected.
References
JPA 1.0 Specification
2.1.10 Inheritance Mapping Strategies
Hibernate Annotations Reference Guide
2.2.4. Mapping inheritance
How does your mapping looks like ?
Have you read this section in the Hibernate doc ?
Inheritance mapping in Hibernate
As you can read in the link I provided above, your mapping is not correct. You have to let Hibernate know that the code_table class inherits from the object class, and you 'll have to let Hibernate know how this link exists in the database.

Categories

Resources