Here a full solution how you can do this:
Code:
public class Class1 : List<Class2>
{
private int _ID;
public virtual int ID
{
get { return _ID; }
set { _ID = value; }
}
public virtual List<Class2> Class2List
{
get
{
return this;
}
set
{
Clear();
this.AddRange(value);
}
}
}
public class Class2
{
}
And the mapping for Class1:
Code:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="true" namespace="HiberTest" assembly="HiberTest">
<class name="HiberTest.Class1,HiberTest" table="class1" lazy="false">
<id name="ID" column="ID">
<generator class="native" />
</id>
<list name="Class2List" table="class2" lazy="true">
<key column="Class1_ID" />
<index column="IndexCol"/>
<composite-element class="HiberTest.Class2"/>
</list>
</class>
</hibernate-mapping>
The code created from Schemaexport looks like this:
Code:
alter table class2 drop foreign key FK151EA7672B4620AC
drop table if exists class1
drop table if exists class2
create table class1 (
ID INTEGER NOT NULL AUTO_INCREMENT,
primary key (ID)
)
create table class2 (
Class1_ID INTEGER not null,
IndexCol INTEGER not null,
primary key (Class1_ID, IndexCol)
)
alter table class2 add index (Class1_ID), add constraint FK151EA7672B4620AC foreign key (Class1_ID) references class1 (ID)
Because Class2 is empty you don't need a mapping file. But normally the class won't be empty, so you can simple create a mapping file for Class2.
One thing that is important is that you disable lazy loading. In this example Class1 inherits from a List. So Class1 inherits a lot of methods which are not virtual. If you have lazy loading enabled you will get an exception. What you can do is, you can override all these inherited methods and make them virtual.
Or you do not inherit from a List and implement this with an inner list.
One thing in the end: Don't name your index column "Index". I used MySQL and got an error. Index is a reserved word.