unique in .hbm.xml file not raising exception

≯℡__Kan透↙ 提交于 2019-12-25 04:56:19

问题


I am having the following in my .hbm.xml file

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                                    namespace="Core.Domain.Model"
                                    assembly="Core">

  <class name="Category" table="Categories" dynamic-update="true">
    <cache usage="read-write"/>
    <id name="Id" column="Id" type="Guid">
      <generator class="guid"/>
    </id>
    <property name="Name" length="100">
    <column name="Name" unique="true" index="IX_Category"/>
    </property>
  </class>
</hibernate-mapping>

I am having the following code, however, I can see that no exception is being raised when I am inserting a duplicate value for the Name field. Why is that so?

 void IRepository<Category>.Save(Category entity)
        {
            using (var scope = new TransactionScope(TransactionScopeOption.Required))
            {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Save(entity);
                    transaction.Commit();
                }
            }
            scope.Complete();
            }    
        }

回答1:


The unique attribute is only used when generating a DDL schema from a mapping (hbm).

If you want to check uniqueness with NHibernate, it is data validation and you should look NHibernate validator. And as Rafael said you have to write your own validator.

You can also check the natural-id element.

Unless you absolutely need to validate uniqueness on application side, this sample and this one make me think it may be better to let the database do this job.




回答2:


Did NHibernate generate the database schema for you? Because even though you set the property as unique, if the schema does not have the unique constraint, it will do nothing. Basically, that property won't query the database looking for uniqueness; it will only set the SQL constraint on insert.



来源:https://stackoverflow.com/questions/3726478/unique-in-hbm-xml-file-not-raising-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!