Using nhib.pdf. Mapping. Attributes. dll, we can map the corresponding Table and Column like ActiveRecord.
Here is an example:
DataModel. Order
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using nhibtes. Mapping. Attributes;
Namespace DataModel
{
/// <Summary>
/// Order data model class
/// </Summary>
[Class (Table = "Orders", Name = "Order", Lazy = false, NameType = typeof (DataModel. Order)]
Public class Order
{
Private int _ orderId;
Private DateTime _ orderDate;
Private int _ customer;
[Id (1, Column = "OrderId", Name = "OrderId", TypeType = typeof (Int32)]
[Generator (2, Class = HibernateStrings. Generator. Native)]
Public int OrderId
{
Get {return _ orderId ;}
Set {_ orderId = value ;}
}
[Property (Column = "OrderDate")]
Public DateTime OrderDate
{
Get {return _ orderDate ;}
Set {_ orderDate = value ;}
}
// [Property (Column = "Customer")]
// Public int CustomerId
//{
// Get {return _ customer ;}
// Set {_ customer = value ;}
//}
[ManyToOne (Name = "Customer", Cascade = CascadeStyle. None, Column = "Customer", ClassType = typeof (DataModel. Customer)]
Public Customer
{Get; set ;}
[Bag (Name = "Products", Lazy = false, Generic = true,
Table = "OrderProduct", Cascade = CascadeStyle. AllDeleteOrphan)]
[Key (1, Column = "[Order]")]
[ManyToMany (2, Column = "Product", ClassType = typeof (DataModel. Product)]
Private IList <Product >_products = new List <Product> ();
Public IList <Product> Products
{
Get {return _ products ;}
Set {_ products = value ;}
}
Public override string ToString ()
{
Return String. Format ("[Order] OrderId = {0}, OrderDate = {1}, CustomerId = {2}, CustomerName = {3 }",
OrderId, OrderDate, Customer. mermerid, Customer. FullName );
}
}
}
You no longer need to write annoying hbm. xml files.
Note the following points:
(1) The ID must be Name, TypeType
(2) attributes such as Name and NameType must also be written to the Class.
(3) Session. Flush () varies according to the ID policy, and automatic Flush () is used when different. Commit requests are used to send SQL statements to the DB. Sometimes the database is not Flush and does not actually update the DB.
Load VS. Get
(1) When the record does not exist, the get method returns null, and the load method produces an exception.
(2) the load method can return the proxy class of the object. The get method returns the real entity class.
(3) the load method can make full use of existing data in hibernate's internal cache and second-level cache, while the get method only searches for data in the internal cache, if no data is found, it will go beyond the second-level cache and directly call SQL to query the database.
(4) Maybe someone has modified the data in the database. If load finds the data in the cache, it will not access the database, and get will return the latest data.