NHibernate configuration error - nhibernate

I've just begun working as a developer and I'm running into the same issue over and over again. I keep getting this error:
Exception (SessionFactory): An exception occurred during configuration of persistence layer. / em NHibernate.Cfg.ConfigurationSchema.HibernateConfiguration..ctor(XmlReader hbConfigurationReader, Boolean fromAppSetting)
em NHibernate.Cfg.Configuration.Configure(XmlReader textReader)
em NHibernate.Cfg.Configuration.Configure(String fileName, Boolean ignoreSessionFactoryConfig)
em DataLayer.Repository.NHibernateHelper.get_SessionFactory() at 14/12/2016 16:52:52 0
PCService Error on: 14/12/2016 16:52:52 Referência de objeto não definida para uma instância de um objeto. em DataLayer.Repository.ConfigRobotRepository.FindByName(String name)
em RSPC.PCService.ScheduleService() at line 0
My hibernate.cfg.xml:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">
NHibernate.Connection.DriverConnectionProvider
</property>
<property name="dialect">
NHibernate.Dialect.MySQLDialect
</property>
<property name="connection.driver_class">
NHibernate.Driver.MySqlDataDriver
</property>
<property name="connection.connection_string">
Server=localhost; Database=bd; Uid=ti; Pwd=************;
</property>
<property name="show_sql">false</property>
</session-factory>
</hibernate-configuration>
My NHibernateHelper.cs:
public class NHibernateHelper
{
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
try
{
if (_sessionFactory == null)
//CreateSessionFactory();
{
var configuration = new Configuration();
//configuration.SetProperty(NHibernate.Cfg.Environment.ConnectionString, ConnectionString);
configuration.Configure("hibernate.cfg.xml");
configuration.AddAssembly(typeof(ConfigRobot).Assembly);
_sessionFactory = configuration.BuildSessionFactory();
}
return _sessionFactory;
}
catch (Exception e)
{
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(e, true);
var frame = trace.GetFrame(0);
var line = frame.GetFileLineNumber();
Log("Exception (SessionFactory): " + e.Message + " / " + e.StackTrace + " at {0} " + line, Path.GetTempPath() + "PCService" + ".txt");
return null;
}
}
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
Any help is much appreciated! Thanks!

Well there are multiple reasons why this may happen:
Are you sure configuration.Configure("hibernate.cfg.xml"); line is picking up config file correctly? Try specifying complete path. Make sure you are copying it to bin (release/debug) folder.
Make sure details mentioned in config file are correct.
Try configuring using code. Use NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();. Refer this post for details.
Check InnerException of Exception being thrown. Keep running down the Exceptinn tree.
Make sure your Entities and HBM files are correct and match with database structure. This is least likely cause because NHibernate throws different exception in that case mentioning exact name of class.

Related

How can I Run hibernate application with datasource in Intellij IDEA

Hibernate.cfg.xml
<property name="connection.datasource">java:/comp/env/jdbc/MyStatus-process</property>
web.xml
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/MyStatus-process</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
HibernateUtil class
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration().configure("hibernate.cfg.xml"); //configuration settings from hibernate.cfg.xml
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
serviceRegistryBuilder.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
return configuration.buildSessionFactory(serviceRegistry);
}
catch (Throwable ex) {
log.error("--- Exception while creating the initial session factory creation ---", ex);
throw new ExceptionInInitializerError(ex);
}
}
I was not able to run with above configuration. Can any one give some ideas on it.
I was able to run with below configuration:
Working Hibernate Configuration:
<property name="hibernate.connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:jtds:sqlserver://localhost:1433/DB_INSTANCE_NAME;tds=8.0;lastupdatecount=true</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password">sa1234</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServer2012Dialect</property>

Creating a Junit test that tests conection to SQL Server

I am having a great deal of difficulty in either understanding what I am doing wrong or missing something fundamental. I have searched for my problem for a day or so and not understanding what I am missing.
So what I am trying to do is Create a JUnit test that connects to my SQL server and does a query to get the current time. My connection to the server works and I have tested my SQL code in the Query on the server and works perfectly. For some reason the test isn't sending my code and getting anything returned.. Not sure what Ive done wrong an if this is too extensive for this form(little new to this)
#Override
public Timestamp PCNow() throws PCSQLException {
//SQL Server uses GETDATAE
String strSQL = "SELECT GETDATE()";;
try {
//Get a result set with the timestamp field
Timestamp datTs = (Timestamp)jdbcTemplate.queryForObject( strSQL, Timestamp.class );
//Make sure there is a result
if ( datTs == null )
//Throw an exception indicating the server could not give a time
throw new PCSQLException( "UNABLE_SERVER_TIME" );
return datTs;
}
catch (Exception e) {
throw new PCSQLException( "This didn't work PCNow", e );
}
}
This is my Test class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:applicationContext-sql.xml"} )
//instantiate TestExecutionListener class
#TestExecutionListeners
public class ConnectionAdapterSQLTest {
#Autowired
ConnectionAdapterImpl connectionAdapterPC;
private final Log log = LogFactory.getLog( getClass() );
#Before
public void setUp() throws Exception {
}
/**
* #throws java.lang.Exception
*/
#After
public void tearDown() throws Exception {
}
#Test
public final void testPCNow() {
log.info("testPCNow()");
//fail("Not yet implemented");
}
applicationContext-sql.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- connection to Sql Server using JDBC sqljdbc4.2 -->
<bean id="dataSourcePC" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url" value="jdbc:sqlserver://******;databaseName=******" />
<property name="username" value="******" />
<property name="password" value="******" />
</bean>
<bean id="connectionAdapterPC"
class="com.*******.*******.connections.ConnectionAdapterSQL">
<property name="dataSource" ref="dataSourcePC" />
<property name="useConnectionPool" value="false" />
</bean>
<bean id="dxDateTimeFormatter" class="com.*******.*******.data.format.DateTimeFormatter">
<property name="dateFormat" value="dd-MMM-yyyy" />
</bean>
</beans>
Matt, you are logging the String "testPCNow()" not invoking the method PCNow().
So replace the test method:
#Test
public void testPCNow() {
log.info(new TheClassThatContainsTestPCNowMethod().PCNow());
}
Remember replacing TheClassThatContainsTestPCNowMethod with a valid constructor of the class that contains the method PCNow().

MVC 5 NHibernate Autofac, not able to see database data

I'm building an MVC5 web app connecting to a MS SQL 2008 database, so that the users can search and make changes to data stored there. I've looked at a bunch of autofac tutorials and examples, but can't seem to make any of them work.
I'm assuming my autofac configuration is the problem, because when I run the app it says my model is null. Which I think means the autofac is not connecting to the datbase.
So, in my global.asax.cs file I have the following:
protected void Application_Start()
{
#region Autofac
// Register Controllers
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly); //all controllers in assembly at once ?
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterFilterProvider();
// Set the Dependency Resolver
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
// Register Model Binders
builder.RegisterModelBinders(typeof(MvcApplication).Assembly); //all binders in assembly at once ?
builder.RegisterModelBinderProvider();
// Register Modules
builder.RegisterModule<PersistenceModule>();
#endregion
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
I have a hibernate.cfg.xml file as
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Data Source=DEVSRV\SQLSERVER;Initial Catalog=tipdemo;Persist Security Info=True;User ID=admin;Password=***********</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
<!--<mapping assembly="NHibernateTest"/> -->
</session-factory>
</hibernate-configuration>
</configuration>
And my PersistenceModule class is:
public class PersistenceModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
if (builder == null)
throw new ArgumentException("builder", "builder is null");
base.Load(builder);
}
private ISessionFactory ConfigureDB()
{
Configuration cfg = new Configuration().Configure(System.Web.HttpContext.Current.Server.MapPath("~/Config/hibernate.cfg.xml"));
cfg.AddAssembly(typeof(Domain.General.Project).Assembly);
return cfg.BuildSessionFactory();
}
}
You can't register things in the container after it's built.
On line 11 in the sample for Application_Start you're building the container, but then after you set the DependencyResolver you're registering more stuff with the ContainerBuilder. You can't do that - you have to register everything first, then build the container as the last thing you do.
That's why it's never entering your PersistenceModule - you've already built the container, so it's not actually getting registered.
If, for some reason, you need to add registrations to an already-built container, you need to create an all new ContainerBuilder and call builder.Update(container). However, I strongly recommend you just reorder things so the container is built last rather than go the Update route if possible.

NHibernateHelper - many tables

I am new in NHibernate, I have based on tutorial: http://nhibernate.info/doc/tutorials/first-nh-app/your-first-nhibernate-based-application.html . So I have NHibernateHelper:
public class NHibernateHelper {
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
{
var configuration = new Configuration();
configuration.Configure();
configuration.AddAssembly(typeof (Product).Assembly);
_sessionFactory = configuration.BuildSessionFactory();
}
return _sessionFactory;
}
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
} }
But I have also entity Category and User? Do I need each entity add to configuration using code AddAssembly?? Because when I have added code:
configuration.AddAssembly(typeof (Product).Assembly);
configuration.AddAssembly(typeof(Category).Assembly);
I have error:
Could not compile the mapping document: MvcApplication1.Mappings.Product.hbm.xml
First check whether you have set the "Build Action" of all the mapping files (*.hbm.xml) to "Embedded Resource". This is VERY important.
Then you only need to add a call to AddAssembly once as NHibernate is clever enough to scan through the assembly to sniff out all your entities that map to all your embedded hbm.xml files..
e.g. You only need to supply the assembly once that contains all your entities:-
_configuration.AddAssembly(typeof (Product).Assembly);
NHibernate will now find Category (and all others) automatically as long as they are in the same assembly as Product. HTH
you can alternatively add the mapping tag into the web.config, instead of adding it in code on the SessionFactory initialization. Then, your code will look like this:
if (_sessionFactory == null)
{
var configuration = new Configuration();
configuration.Configure();
_sessionFactory = configuration.BuildSessionFactory();
}
And in the web config you will have to indicate the assembly where all of your mappings are, like this:
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">
NHibernate.Connection.DriverConnectionProvider
</property>
<property name="dialect">
NHibernate.Dialect.MsSql2005Dialect
</property>
<property name="connection.driver_class">
NHibernate.Driver.SqlClientDriver
</property>
<property name="connection.connection_string">
-- YOUR STRING CONNECTION --
</property>
<property name="proxyfactory.factory_class">
NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle
</property>
<mapping assembly="You.Assembly.Namespace" />
</session-factory>
Being the important configuration tag "mapping assembly="Your.Assembly.Namespace". As the other contributor mentioned before, it is very important that you mark each of the hbm.xml file as embedded resource, otherwise it will be as you never created it. By doing this, you just need to create all of the mappings inside of this assembly (project) and those will be automatically read when NH configures.

NHibernate ClassMappings = 0

I am trying to user NHibernate / FluentNHibernate to create a table in my database. I seem to have figured it out for the most part but when I run the test the table isn't created. I see in the Configuration object that the ClassMappings is a big fat zero even thought I have user FluentNHibernate to configure them from an assembly. I somewhat understand this but I am missing some connection somewhere... Here is the code snippets, maybe someone can see what I forogt?
Here is my dataconfig class.
public static FluentConfiguration GetFluentConfiguration()
{
string hibernateCfgFile = #"C:\Users\kenn\Documents\Visual Studio 2008\Projects\NHibernateTestTwo\Infrastructure\hibernate.cfg.xml";
return Fluently.Configure(new Configuration().Configure(#hibernateCfgFile))
.Mappings(cfg => cfg.FluentMappings.AddFromAssembly(typeof(AddressMap).Assembly));
}
Here is the test class.
[Test, Explicit]
public void SetupDatabase()
{
FluentConfiguration conf = DataConfig.GetFluentConfiguration();
conf.ExposeConfiguration(BuildSchema).BuildSessionFactory();
}
private static void BuildSchema(Configuration conf)
{
new SchemaExport(conf).SetOutputFile("drop.sql").Drop(false, true);
new SchemaExport(conf).SetOutputFile("create.sql").Create(false, true);
}
Here is the mappings
public AddressMap()
{
Table("Address");
DynamicUpdate();
Id(a => a.Id).GeneratedBy.GuidComb();
Map(a => a.AddressOne).Not.Nullable().Length(100);
Map(a => a.AddressTwo).Length(100);
Map(a => a.City).Not.Nullable().Length(100);
Map(a => a.state).Not.Nullable().Length(100);
Map(a => a.zip).Not.Nullable().Length(50);
Map(a => a.Primary).Not.Nullable();
}
The hibernate.cfg.xml file
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.driver_class">
NHibernate.Driver.SqlClientDriver
</property>
<property name="connection.connection_string">
Data Source=MYPC;Initial Catalog=NHibernateSample;Integrated Security=True;
</property>
<property name="show_sql">true</property>
<property name="dialect">
NHibernate.Dialect.MsSql2005Dialect
</property>
<property name="adonet.batch_size">100</property>
<!--<property name="proxyfactory.factory_class">
NHibernate.ByteCode.LinFu.ProxyFactoryFactory,
NHibernate.ByteCode.LinFu
</property>-->
<property name="proxyfactory.factory_class">
NHibernate.ByteCode.Castle.ProxyFactoryFactory,
NHibernate.ByteCode.Castle
</property>
</session-factory>
I am just not sure what is missing there... It clearly is talking to the DB cause if I change the name of the database to something that doesn't exist it trows an exception, I am stuck - I have gone round and round on this and just haven't figured it out yet so any help would be greatly appreciated.
Thanks!
See my comment... Don't forget to make your map classes public or FluentNHibernate won't see them.