方法与问题总结:

收集:Hibernate中常见问题 No row with the given identifier exists问题的原因及解决 标签: hibernatetablestruts数据库nullquery

数据库存配置不正确常见出错:

对象名无效

 

 

 

 

ids for this class must be manually assigned before calling save():  ?

第一步:确认调用save方法的时候是否保证主键不为空

第二步:如果主键是字符串形式,因为软件生成xxx.hbm.xml文件时,如果主键是字符串

会生成形式为: 

<id name="UserId" column="user_id" />

这时我们要更改成:

<id name="UserId" column="user_id" type="System.String">
<generator class="assigned" />
</id>

 

为什么我用Nhibernate总是会报No persister for: Model.AdminInfo?

 

 

 

 

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 

Compiler Error Message: CS0234: The type or namespace name 'Ajax' does not exist in the namespace 'System.Web.Mvc' (are you missing an assembly reference?)

Source Error:

 
Line 102:        <add namespace="System.Web.Helpers" />
Line 103:        <add namespace="System.Web.Mvc" />
Line 104:        <add namespace="System.Web.Mvc.Ajax" />
Line 105:        <add namespace="System.Web.Mvc.Html" />
Line 106:        <add namespace="System.Web.Routing" />


Source File: d:\Tx\1.1.0\Agency\TX.Agency.WebSite\Web.config    Line: 104 



 

 

 

 

Server Error in '/' Application.


The input stream is not a valid binary format. The starting contents (in bytes) are: 3C-68-74-6D-6C-3E-0D-0A-3C-68-65-61-64-3E-3C-74-69 ...

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Runtime.Serialization.SerializationException: The input stream is not a valid binary format. The starting contents (in bytes) are: 3C-68-74-6D-6C-3E-0D-0A-3C-68-65-61-64-3E-3C-74-69 ...

Source Error: 

Line 103:                    Version = version
Line 104:                };
Line 105:                var rsp = AgencyService.AgencyLogin(req);

 出现原因一:使用remoting远程调用端口是否正确

<add key="AppHost" value="agency.app.com" />   

<r:saoFactory id="CreditService"
serviceInterface="TX.Common.Api.ICreditService, TX.Common"
serviceUrl="http://${AppHost}/credit.soap" />

如果是本地的则用 <add key="AppHost" value="localhost:9000" />否则会出现以上错误

 

 

The element 'class' in namespace 'urn:nhibernate-mapping-2.2' has invalid child element 'property' in namespace 'urn:nhibernate-mapping-2.2'. List of possible elements expected: 'meta, subselect, cache, synchronize, comment, tuplizer, id, composite-id' in namespace 'urn:nhibernate-mapping-2.2'.

这是因为这个表中没有设置主键 

 

 

 

Server stack trace:     at System.Runtime.Serialization.FormatterServices.InternalGetSerializableMe

 Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'   is not marked as serializable.

这个问题一值搞左很久:

第一次检查的时候:说明类必须打上【serializable】标签。检 查确认也的确打上,运行问题仍然存在

原来:程序集同时引用不同的DLL,也会导致上述问题的出现,故要检查二样:

一:是否每一个类打上serializable

二:是否引用同一个程序集

 

 

If you store an object in session state, that object must be serializable.

如果你将一个对象存储在会话状态,对象必须是可序列化的。

 

1.0:Invalid URI: Invalid port specified. 无效的URI:无效的指定港口。

应确认连接的端口是否正确

错: <add key="AppHost" value="localhost:8d888" />

对: <add key="AppHost" value="localhost:8888" />

 

 

加载映射文件的方法

第一种:

配置文件法(直接在session-factory配置文件叫指定程序集名称)

如:<mapping assembly="NH02"/> <mapping assembly="{程序集名称}"/>

 1     <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
 2     <property name="connection.driver_class">
 3       NHibernate.Driver.SqlClientDriver
 4     </property>
 5     <property name="show_sql">true</property>
 6     <property name="connection.connection_string">server=127.0.0.1;database=Company;uid=sa;pwd=123;</property>
 7 
 8 
 9     <!--配置二级缓存-->
10 
11     <property name="cache.provider_class">NHibernate.Caches.MemCache.MemCacheProvider,NHibernate.Caches.MemCache</property>
12     <!--<property name="cache.provider_class">NHibernate.Cache.HashtableCacheProvider</property>-->
13     <!--3.-->
14     <property name="cache.use_second_level_cache">true</property>
15     <property name="cache.use_query_cache">true</property>
16     <property name="cache.default_expiration">300</property>
17    
18     <mapping assembly="NH02"/>
19     <!--3.配置映射的二级缓存-->
20     <!--<class-cache class="NH02.Domain.EmployeeInfo,NH02" usage="read-write"/>-->
21 
22 
23 
24   </session-factory>
25 </hibernate-configuration>
26 
27 
28 
29 <!--下面对几个重要的key值说明一下:
30 hibernate.connection.provider
31 连接提供者,取值必须是实现了IConnectionProvider接口的类的全名,当前版本只能取值NHibernate.Connection.DriverConnectionProvider;
32 hibernate.connection.driver_class
33 数据驱动类,取值必须是实现了IDriver接口的类的全名,常用的选择有NHibernate.Driver.SqlClientDriver, NHibernate.Driver.OleDbDriver等;
34 hibernate.dialect
35 数据库方言,取值必须是继承之Dialect的类的全名,最常用的就是NHibernate.Dialect.MsSql2000Dialect/NHibernate.Dialect.MsSql2008Dialect了, 其它的没用过,不清楚能不能正常使用;
36 hibernate.connection.connection_string
37 连接字符串(如:server=127.0.0.1;database=Company;uid=sa;pwd=123;),取值与driver_class对应即可;
38 hibernate.show_sql
39 指明是否在log4net日志中显示sql语句,主要用于调试,取值为true或false;-->
配置

第二种方法:使用代码加载法 cfg.AddDirectory(new DirectoryInfo(@"E:\NH2015\02\NH02\NH02\Domain\Mapping"));  

cfg.AddDirectory(new DirectoryInfo(@"{映射文件所在路径}"));
static ISessionFactory CreateISessionFactoryByXml()
        {
            Configuration cfg = new Configuration().Configure(@"E:\NH2015\02\NH02\NH02\NHibernate\Configuration\hibernate.cfg.xml"); //读取xml文件
          cfg.AddDirectory(new DirectoryInfo(@"E:\NH2015\02\NH02\NH02\Domain\Mapping"));   //读取实体类的映射文件
            ISessionFactory sessionFactory = cfg.BuildSessionFactory();   //创建工厂
            return sessionFactory;
        }

注意:二种方法不能同时存在(只能选其一),否则报错:

Could not compile the mapping document: E:\NH2015\02\NH02\NH02\Domain\Mapping\EmployeeInfo.hbm.xml

设置类缓存策略

方法有二

1.在配置文件法

1.0(直接在session-factory配置文件叫指定程序集名称)中单独配置某个类使用缓存策略

    <class-cache class="NH02.Domain.EmployeeInfo,NH02" usage="read-write"/>

完整:

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
 3   <session-factory>
 4     <property name="connection.provider">
 5       NHibernate.Connection.DriverConnectionProvider
 6     </property>
 7     <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
 8     <property name="connection.driver_class">
 9       NHibernate.Driver.SqlClientDriver
10     </property>
11     <property name="show_sql">true</property>
12     <property name="connection.connection_string">server=127.0.0.1;database=Company;uid=sa;pwd=123;</property>
13 
14 
15     <!--配置二级缓存-->
16 
17     <property name="cache.provider_class">NHibernate.Caches.MemCache.MemCacheProvider,NHibernate.Caches.MemCache</property>
18     <!--<property name="cache.provider_class">NHibernate.Cache.HashtableCacheProvider</property>-->
19     <!--3.-->
20     <property name="cache.use_second_level_cache">true</property>
21     <property name="cache.use_query_cache">true</property>
22     <property name="cache.default_expiration">300</property>
23     <!--3.配置加载映射文件   <mapping assembly="{程序集名称}"/>-->
24     <mapping assembly="NH02"/>
25     <!--3.配置映射的二级缓存-->
26     <class-cache class="NH02.Domain.EmployeeInfo,NH02" usage="read-write"/>
27 
28 
29 
30   </session-factory>
31 </hibernate-configuration>
32 
33 
34 
35 <!--下面对几个重要的key值说明一下:
36 hibernate.connection.provider
37 连接提供者,取值必须是实现了IConnectionProvider接口的类的全名,当前版本只能取值NHibernate.Connection.DriverConnectionProvider;
38 hibernate.connection.driver_class
39 数据驱动类,取值必须是实现了IDriver接口的类的全名,常用的选择有NHibernate.Driver.SqlClientDriver, NHibernate.Driver.OleDbDriver等;
40 hibernate.dialect
41 数据库方言,取值必须是继承之Dialect的类的全名,最常用的就是NHibernate.Dialect.MsSql2000Dialect/NHibernate.Dialect.MsSql2008Dialect了, 其它的没用过,不清楚能不能正常使用;
42 hibernate.connection.connection_string
43 连接字符串(如:server=127.0.0.1;database=Company;uid=sa;pwd=123;),取值与driver_class对应即可;
44 hibernate.show_sql
45 指明是否在log4net日志中显示sql语句,主要用于调试,取值为true或false;-->
配置映射的二级缓存

2.0 通过映射文件设置缓存策略 .....hbm.xml

 <cache usage="read-write"/>(注意:必须紧跟着类的下面位置)

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <hibernate-mapping assembly="NH02" namespace="NH02.Domain" xmlns="urn:nhibernate-mapping-2.2">
 3   <!--<hibernate-mapping assembly="{程序集名称}" namespace="{命名空间}" xmlns="urn:nhibernate-mapping-2.2">-->
 4   <class name="EmployeeInfo" table="EmployeeInfo" lazy="true" >
 5     <cache usage="read-write"/>
 6     <!--<class name="{类名}" table="{数据库表名}" lazy="{是否延迟加载true/false}" >-->
 7     <id name="EmpNo" column="Emp_No">
 8       <!--<id name="{类属性名字}" column="{数据为表属性名}">-->
 9       <generator class="identity" />
10       <!--<generator class="identity" />  identity:用于MySql数据库。特点:递增-->
11     </id>
12     <property name="EmpName">
13       <column name="Emp_Name" sql-type="varchar" not-null="true" />
14     </property>
15     <!--<property name="{类属性名}">
16       <column name="{数据为表属性名称}" sql-type="{类型:如:decimal、varchar...}" not-null="{是否可以为NULL:true/false}" />
17     </property>-->
18     <property name="Salary">
19       <column name="Salary" sql-type="decimal" not-null="true" />
20     </property>
21     <property name="DeptName">
22       <column name="Dept_Name" sql-type="varchar" not-null="true" />
23     </property>
24     <property name="Designation">
25       <column name="Designation" sql-type="varchar" not-null="true" />
26     </property>
27   </class>
28 </hibernate-mapping>
映射文件配置缓存策略

 

配置时出现:Object reference not set to an instance of an object.

详细信细如下:

 1 Server Error in '/' Application.
 2 
 3 Object reference not set to an instance of an object.
 4 
 5 Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
 6 
 7 Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
 8 
 9 Source Error: 
10 
11 An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
12 
13 Stack Trace: 
14 
15 
16 [NullReferenceException: Object reference not set to an instance of an object.]
17    Memcached.ClientLibrary.SockIOPool.Initialize() +324
18    NHibernate.Caches.MemCache.MemCacheProvider.Start(IDictionary`2 properties) +1760
19    NHibernate.Impl.SessionFactoryImpl..ctor(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners) +755
20    NHibernate.Cfg.Configuration.BuildSessionFactory() +103
21    Spring.Data.NHibernate.LocalSessionFactoryObject.NewSessionFactory(Configuration config) +16
22    Spring.Data.NHibernate.LocalSessionFactoryObject.AfterPropertiesSet() +2530
23    Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.InvokeInitMethods(Object target, String name, IConfigurableObjectDefinition definition) +167
24    Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.ConfigureObject(String name, RootObjectDefinition definition, IObjectWrapper wrapper) +424
25    Spring.Objects.Factory.Support.WebObjectFactory.ConfigureObject(String name, RootObjectDefinition definition, IObjectWrapper wrapper) in c:\_prj\spring-net\src\Spring\Spring.Web\Objects\Factory\Support\WebObjectFactory.cs:478
26    Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.InstantiateObject(String name, RootObjectDefinition definition, Object[] arguments, Boolean allowEagerCaching, Boolean suppressConfigure) +618
27 
28 [ObjectCreationException: Error creating object with name 'SessionFactory' defined in 'file [E:\NH2015\Remove\App\App\App_Data\Spring\Hibernate.xml] line 15' : Initialization of object failed : Object reference not set to an instance of an object.]
29    Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.InstantiateObject(String name, RootObjectDefinition definition, Object[] arguments, Boolean allowEagerCaching, Boolean suppressConfigure) +758
30    Spring.Objects.Factory.Support.AbstractObjectFactory.CreateAndCacheSingletonInstance(String objectName, RootObjectDefinition objectDefinition, Object[] arguments) +238
31    Spring.Objects.Factory.Support.WebObjectFactory.CreateAndCacheSingletonInstance(String objectName, RootObjectDefinition objectDefinition, Object[] arguments) in c:\_prj\spring-net\src\Spring\Spring.Web\Objects\Factory\Support\WebObjectFactory.cs:299
32    Spring.Objects.Factory.Support.AbstractObjectFactory.GetObjectInternal(String name, Type requiredType, Object[] arguments, Boolean suppressConfigure) +1117
33    Spring.Objects.Factory.Support.DefaultListableObjectFactory.PreInstantiateSingletons() +428
34    Spring.Context.Support.AbstractApplicationContext.Refresh() +690
35    Spring.Context.Support.WebApplicationContext..ctor(WebApplicationContextArgs args) in c:\_prj\spring-net\src\Spring\Spring.Web\Context\Support\WebApplicationContext.cs:125
36    _dynamic_Spring.Context.Support.WebApplicationContext..ctor(Object[] ) +245
37    Spring.Reflection.Dynamic.SafeConstructor.Invoke(Object[] arguments) +10
38    Spring.Context.Support.RootContextInstantiator.InvokeContextConstructor(ConstructorInfo ctor) +129
39    Spring.Context.Support.ContextInstantiator.InstantiateContext() +43
40    Spring.Context.Support.ContextHandler.InstantiateContext(IApplicationContext parentContext, Object configContext, String contextName, Type contextType, Boolean caseSensitive, IList`1 resources) +190
41    Spring.Context.Support.WebContextHandler.InstantiateContext(IApplicationContext parent, Object configContext, String contextName, Type contextType, Boolean caseSensitive, IList`1 resources) in c:\_prj\spring-net\src\Spring\Spring.Web\Context\Support\WebContextHandler.cs:121
42    Spring.Context.Support.ContextHandler.Create(Object parent, Object configContext, XmlNode section) +246
43 
44 [ConfigurationErrorsException: Error creating context 'spring.root': Error creating object with name 'SessionFactory' defined in 'file [E:\NH2015\Remove\App\App\App_Data\Spring\Hibernate.xml] line 15' : Initialization of object failed : Object reference not set to an instance of an object.]
45    System.Configuration.BaseConfigurationRecord.EvaluateOne(String[] keys, SectionInput input, Boolean isTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult) +181
46    System.Configuration.BaseConfigurationRecord.Evaluate(FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult, Boolean getLkg, Boolean getRuntimeObject, Object& result, Object& resultRuntimeObject) +1241
47    System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject) +1543
48    System.Configuration.BaseConfigurationRecord.GetSection(String configKey) +41
49    System.Web.HttpContext.GetSection(String sectionName) +52
50    System.Web.Configuration.HttpConfigurationSystem.GetSection(String sectionName) +55
51    System.Web.Configuration.HttpConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String configKey) +6
52    System.Configuration.ConfigurationManager.GetSection(String sectionName) +78
53    Spring.Util.ConfigurationUtils.GetSection(String sectionName) +80
54    Spring.Context.Support.WebApplicationContext.GetContextInternal(String virtualPath) in c:\_prj\spring-net\src\Spring\Spring.Web\Context\Support\WebApplicationContext.cs:327
55    Spring.Context.Support.WebApplicationContext.GetRootContext() in c:\_prj\spring-net\src\Spring\Spring.Web\Context\Support\WebApplicationContext.cs:223
56    Spring.Context.Support.WebSupportModule.Init(HttpApplication app) in c:\_prj\spring-net\src\Spring\Spring.Web\Context\Support\WebSupportModule.cs:0
57    System.Web.HttpApplication.InitModulesCommon() +80
58    System.Web.HttpApplication.InitModules() +64
59    System.Web.HttpApplication.InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers) +792
60    System.Web.HttpApplicationFactory.GetNormalApplicationInstance(HttpContext context) +336
61    System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext context) +107
62    System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +525
63 
64 Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929
ERROR错误信息

分析发现上面紫色字体关于MENCACHED问题,于是查找MENCACHED发现在WEB.CONFIG文件中没有配置MENCACHED配置

 

Could not load type from string value 'App.Dao.EmployeeInfoDao,App.Dao'.

原来发现要配置类实体时出现出错

错误:  <object id="EmployeeInfoDao" type="App.Dao.EmployeeInfoDao,App.Dao" />

正确: <object id="EmployeeInfoDao" type="App.Dao.EmployeeInfoDao,App" />

    <object id="{类名}" type="{类全名称},{程序集名称}" />

 

 

Remoting configuration failed with the exception 'System.Runtime.Remoting.RemotingException: The channel 'http' is already registered.

 

 

Error creating context 'spring.root': ServiceInterface must be an interface

 

{"Error creating object with name 'AgencyService' : Initialization of object failed : ServiceInterface must be an interface"}

 

ould not load file or assembly 'Spring.Services, Version=2.0.0.45000, Culture=neutral, PublicKeyToken=65e474d141e25e07' or one of its dependencies. The system cannot find the file specified

 

Attempted to call a method declared on type 'App.Service.AgencyService' on an object which exposes 

 

 

 Invalid object name 'Student'.

检查数据库存连接参数是否正确,

报错原因:

<db:provider id="DbProvider" provider="System.Data.SqlClient" connectionString="server=.;database=staging_tx;uid=sa;pwd=123;"/>,因为数据库连接名字有误staging_tx

正确:

<db:provider id="DbProvider" provider="System.Data.SqlClient"  connectionString="server=.;database=School;uid=sa;pwd=123;"/>

 

Hibernate operation: could not load an entity: [TX.Common.Domain.Student#1][SQL: SELECT student0_.Id as Id0_0_, student0_.topic_Id as topic2_0_0_, student0_.SName as SName0_0_, student0_.SNum as SNum0_0_ FROM Student student0_ WHERE student0_.Id=?]; bad SQL grammar [SELECT student0_.Id as Id0_0_, student0_.topic_Id as topic2_0_0_, student0_.SName as SName0_0_, student0_.SNum as SNum0_0_ FROM Student student0_ WHERE student0_.Id=?]; Invalid object name 'Student'.
Invalid object name 'Student'.

 

 

自动装配失败原因   default-autowire="byName"

前天一直遇到一个问题,在注入空对象时,已确认对象已注入到容器中

            IApplicationContext ctxf = ContextRegistry.GetContext();
            EmployeeInfoDao dao = ctxf.GetObject("EmployeeInfoDao") as EmployeeInfoDao;
            var domo = dao.FindById(1);

但在执行下面方法时, EmployeeInfoDao 对象没有注入,为NULL,因此一直报错;

public class AgencyService : MarshalByRefObject, IAgencyService
    {
        EmployeeInfoDao EmployeeInfoDao { get; set; } 没有 public 
public void GetPerson() { EmployeeInfo info = EmployeeInfoDao.FindById(1); } }

最后发现原因是因为注入的对象必须为public  

然后把对象属性更改为以下则可以了

    public class AgencyService : MarshalByRefObject, IAgencyService
    {
        public EmployeeInfoDao EmployeeInfoDao { get; set; }

        public void GetPerson()
        {
            EmployeeInfo info = EmployeeInfoDao.FindById(1);
        }
    }

总结自动注入的三大要求:

对XML配置要求:

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net" default-autowire="byName">
<!--
第一:设置装配的方法 default-autowire="byName"
第二:必须id必须与类中的属性名一致
-->
<object id="EmployeeInfoDao" type="App.Dao.EmployeeInfoDao,App"/>
<object id="AgencyService" type="App.Service.AgencyService,App" />
</objects>

使用类要求:

public class AgencyService : MarshalByRefObject, IAgencyService
{
EmployeeInfoDao EmployeeInfoDao { get; set; }报错
第三:类必须保证是公开的(public)
public EmployeeInfoDao EmployeeInfoDao { get; set; }

public void GetPerson()
{
EmployeeInfo info = EmployeeInfoDao.FindById(1);
}
}

三点:

第一:设置装配的方法 default-autowire="byName"
第二:必须id必须与类中的属性名一致
第三:类必须保证是公开的(public)

 

 

 

Type 'Command.Request' in Assembly 'Command, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

 

posted on 2016-01-12 16:03  高达  阅读(1290)  评论(0)    收藏  举报

导航