根据下面这个blog修改而成:
http://blog.aspcool.com/billy_zh/archive/2005/11/12/926.html#3337
use master
go
create database Hibernate
go
use Hibernate
go
create table Users (user_id int identity primary key, name varchar(100))
go
create table Groups(group_id int identity primary key, name varchar(100), description varchar(100))
go
create table UserGroups (group_id int foreign key references Groups(group_id),
user_id int foreign key references Users(user_id))
go
- User.cs
using System;
using System.Collections;
public class User {
public User() {
}
public int UserId
{
get { return userId; }
set { userId = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public IList Groups
{
get { return groups; }
set { groups = value; }
}
private int userId;
private string name;
private IList groups = new ArrayList();
} //class User
- Group.cs
using System;
using System.Collections;
public class Group {
public Group() {
}
public int GroupId
{
get { return groupId; }
set { groupId = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Description
{
get { return description; }
set { description = value; }
}
public IList Users
{
get { return users; }
set { users = value; }
}
private int groupId;
private string name;
private string description;
private IList users = new ArrayList();
} //class Group
- User.hbm.xml
-
Group.hbm.xml
-
TestUser.cs
using System;
using NHibernate;
using NHibernate.Cfg;
using System.Text;
using System.Collections;
using NHibernate.Expression;
public class TestCreate
{
ISession session;
public TestCreate()
{
Configuration cfg = new Configuration();
cfg.AddXmlFile("User.hbm.xml");
cfg.AddXmlFile("Group.hbm.xml");
ISessionFactory factory = cfg.BuildSessionFactory();
session = factory.OpenSession();
}
public void Test()
{
User user1 = new User();
user1.Name = “test1”;
User user2 = new User();
user2.Name = “test2”;
Group group1 = new Group();
group1.Name = “group1”;
Group group2 = new Group();
group2.Name = “group2”;
user1.Groups.Add( group2);
user2.Groups.Add( group1 );
group1.Users.Add( user2 );
group2.Users.Add( user1);
ITransaction trans = null;
try {
trans = session.BeginTransaction();
session.Save( user1 );
session.Save( user2 );
session.Save( group1 );
session.Save( group2 );
trans.Commit();
}
catch ( Exception e ) {
if ( trans != null ) trans.Rollback();
throw e;
}
finally {
session.Close();
}
}
static void Main()
{
TestCreate tc = new TestCreate();
tc.Test();
}
}
- TestUser.exe.config
<section />
<section />
- UserGroup.dll
csc /t:library /out:UserGroup.dll User.cs Group.cs
- TestUser.exe
csc /r:Nhibernate.dll,UserGroup.dll TestUser.cs
- runtime assemblies needed
HashCodeProvider.dll
Iesi.Collections.dll
log4net.dll
NHibernate.dll