我现在已经在网上研究了一段时间了,但是对我来说它们并没有真正有意义。也许我是Hibernate的新手。
然而,客户表假设加入customerProduct表然后加入产品表 我有一个字符串产品变量我想能够匹配产品表名称值列 .. 在SQL SERVER中我想做的查询
select c.Name, c.Address1, c.Address2, c.County, p.Name
from dbo.Customers as c inner join dbo.CustomerProducts as cp
on c.CustomerID = cp.CustomerID inner join dbo.Products as p
on cp.ProductID = p.ProductID
where c.Address1 ='&somthing&' and c.Name='&somthing&' and c.Address1='&somthing&' and p.Name='&somthing&'
然而这就是我现在所拥有的,我无法想到如何在Nhibernate中进行内部联接 并将字符串产品变量放入搜索产品表
public IPagedList<Customer> GetSearchPagedCustomer(string product, string practice, string address, string county, int pageNumber = 1, int pageSize = 100)
{
ICriteria criteria = Session.CreateCriteria<Customer>();
if (!string.IsNullOrEmpty(product))
criteria.Add(Restrictions.Like("Product.Name",product,MatchMode.Anywhere));
if (!string.IsNullOrEmpty(practice))
criteria.Add(Restrictions.Like("Name", practice,MatchMode.Anywhere));
//One value and search 3 column: address 1, address 2 and address 3
if (!string.IsNullOrEmpty(address))
criteria.Add(Restrictions.Like("Address1", address, MatchMode.Anywhere) || Restrictions.Like("Address2", address, MatchMode.Anywhere) || Restrictions.Like("Address3", address, MatchMode.Anywhere));
if (!string.IsNullOrEmpty(county))
criteria.Add(Restrictions.Like("County", county, MatchMode.Anywhere));
return criteria.Future<Customer>().OrderBy(x => x.Name).ToPagedList<Customer>(pageNumber, pageSize);
}
任何人都可以将我的SQL查询代码转换为Nhibernate代码, 非常感谢你!!
答案 0 :(得分:1)
我猜你的映射是<bag>
和<many-to-many>
,而客户有一个产品系列:
public class Customer
{
public virtual IList<Product> Products { get; set; }
public virtual string Name { get; set; }
...
然后如何进行连接的方式如下:
ICriteria criteria = Session.CreateCriteria<Customer>();
if (!string.IsNullOrEmpty(product))
{
// here we do LEFT JOIN on Products
var productCriteria = criteria
.CreateCriteria("Products", "Product", JoinType.LeftOuterJoin);
// the subcriteria targeting the products table
productCriteria.Add(Restrictions.Like("Name",product,MatchMode.Anywhere));
}
...
此外,我们可以在服务器上进行分页和排序
criteria
.SetMaxResults(pageSize)
.SetFirstResult(0) // calculate from pageNumber
.AddOrder(new Order("Name", true))
.Future<Customer>()
//.OrderBy(x => x.Name)
//.ToPagedList<Customer>(pageNumber, pageSize)
;