Search Results

Search found 33 results on 2 pages for 'schemaexport'.

Page 1/2 | 1 2  | Next Page >

  • Entity Framework equivalence for NHibernte SchemaExport

    - by jbandi
    Is there an equivalence in Entity Framework to NHibernate SchemaExport? Given I have a working Entity-Model, I would like to programmatically initialize a database. I would like to use this functionality in the setup of my integration tests. Creating the matching DDL for an Entity-Model would also suffice.

    Read the article

  • Fluent NHibernate SchemaExport to SQLite not pluralizing Table Names

    - by weenet
    I am using SQLite as my db during development, and I want to postpone actually creating a final database until my domains are fully mapped. So I have this in my Global.asax.cs file: private void InitializeNHibernateSession() { Configuration cfg = NHibernateSession.Init( webSessionStorage, new [] { Server.MapPath("~/bin/MyNamespace.Data.dll") }, new AutoPersistenceModelGenerator().Generate(), Server.MapPath("~/NHibernate.config")); if (ConfigurationManager.AppSettings["DbGen"] == "true") { var export = new SchemaExport(cfg); export.Execute(true, true, false, NHibernateSession.Current.Connection, File.CreateText(@"DDL.sql")); } } The AutoPersistenceModelGenerator hooks up the various conventions, including a TableNameConvention like so: public void Apply(FluentNHibernate.Conventions.Instances.IClassInstance instance) { instance.Table(Inflector.Net.Inflector.Pluralize(instance.EntityType.Name)); } This is working nicely execpt that the sqlite db generated does not have pluralized table names. Any idea what I'm missing? Thanks.

    Read the article

  • Fluent NHibernate ExportSchema without connexion string

    - by Vince
    Hi all, I want to propose to user a way to generate database table script creation. To do this for now i use NHibernate ExportSchema bases on a NHibernate configuration generated with Fluent NHibernate this way (during my ISessionFactory creation method): FluentConfiguration configuration = Fluently.Configure(); ... Mapping conf ... configuration.Database(fluentDatabaseProvider); this.nhibernateConfiguration = configuration.BuildConfiguration(); returnSF = configuration.BuildSessionFactory(); ... Later new SchemaExport(this.nhibernateConfiguration) .SetOutputFile(filePath) .Execute(false, false, false); fluentDatabaseProvider is a FluentNHibernate IPersistenceConfigurer which is needed to get proper sql dialect for database creation. When factory is created with an existing database, everything works fine. But what i want to do is to create an NHibernate Configuration object on a selected database engine without a real database behind the scene... And i don't manage to do this. If anybody has some idea.

    Read the article

  • How to manage a One-To-One and a One-To-Many of same type as unidirectional mapping?

    - by user1652438
    I'm trying to implement a model for private messages between two or more users. That means I've got two Entities: User PrivateMessage The User model shouldn't be edited, so I'm trying to set up an unidirectional relationship: @Entity (name = "User") @Table (name = "user") public class User implements Serializable { @Id String username; String password; // something like this ... } The PrivateMessage Model addresses multiple receivers and has exactly one sender. So I need something like this: @Entity (name = "PrivateMessage") @Table (name = "privateMessage") @XmlRootElement @XmlType (propOrder = {"id", "sender", "receivers", "title", "text", "date", "read"}) public class PrivateMessage implements Serializable { private static final long serialVersionUID = -9126766942868177246L; @Id @GeneratedValue private Long id; @NotNull private String title; @NotNull private String text; @NotNull @Temporal(TemporalType.TIMESTAMP) private Date date; @NotNull private boolean read; @NotNull @ElementCollection(fetch = FetchType.EAGER, targetClass = User.class) private Set<User> receivers; @NotNull @OneToOne private User sender; // and so on } The according 'privateMessage' table won't be generated and just the relationship between the PM and the many receivers is satisfied. I'm confused about this. Everytime I try to set a 'mappedBy' attribute, my IDE marks it as an error. It seems to be a problem that the User-entity isn't aware of the private message which maps it. What am I doing wrong here? I've solved some situation similar to this one, but none of those solutions will work here. Thanks in advance!

    Read the article

  • AssertionFailure: "null identifier" - FluentNH + SQLServerCE

    - by Stefan
    The code fails at session.Save(employee); with AssertionFailure "null identifier". What am I doing wrong? using FluentNHibernate.Cfg; using FluentNHibernate.Cfg.Db; using FluentNHibernate.Mapping; using NHibernate; using NHibernate.Cfg; using NHibernate.Tool.hbm2ddl; namespace FNHTest { public class Employee { public virtual int Id { get; private set; } public virtual string Name { get; set; } public virtual string Surname { get; set; } } public class EmployeeMap : ClassMap { public EmployeeMap() { Id(e = e.Id); Map(e = e.Name); Map(e = e.Surname); } } public class DB { private static ISessionFactory mySessionFactory = null; private static ISessionFactory SessionFactory { get { if (mySessionFactory == null) { mySessionFactory = Fluently.Configure() .Database(MsSqlCeConfiguration.Standard .ConnectionString("Data Source=MyDB.sdf")) .Mappings(m = m.FluentMappings.AddFromAssemblyOf()) .ExposeConfiguration(BuildSchema) .BuildSessionFactory(); } return mySessionFactory; } } private static void BuildSchema(Configuration configuration) { SchemaExport schemaExport = new SchemaExport(configuration); schemaExport.Execute(false, true, false); } public static ISession OpenSession() { return SessionFactory.OpenSession(); } } public class Program { public static void Main(string[] args) { var employee = new Employee { Name = "John", Surname = "Smith" }; using (ISession session = DB.OpenSession()) { session.Save(employee); } } } }

    Read the article

  • NHibernate Tutorial Run-Time Error: HibernateException

    - by Kashif
    I'm a newbie at NHibernate so please go easy on me if I have asked a stupid question... I am following the tutorial for NHibernate posted here and am getting a run-time error of type "HibernateException" The code in question looks like this: using System; using System.Collections.Generic; using System.Linq; using System.Text; using FirstSolution; using NHibernate.Cfg; using NHibernate.Tool.hbm2ddl; using NUnit.Framework; namespace FirstSolution.Tests { [TestFixture] public class GenerateSchema_Fixture { [Test] public void Can_generate_schema() { var cfg = new Configuration(); cfg.Configure(); cfg.AddAssembly(typeof(Product).Assembly); new SchemaExport(cfg).Execute(false, true, false); } } } The line I am getting the error at is: cfg.AddAssembly(typeof(Product).Assembly); The inner-most exception is: The IDbCommand and IDbConnection implementation in the assembly System.Data.SqlServerCe could not be found And here's my stack trace: at NHibernate.Connection.ConnectionProvider.ConfigureDriver(IDictionary`2 settings) at NHibernate.Connection.ConnectionProvider.Configure(IDictionary`2 settings) at NHibernate.Connection.ConnectionProviderFactory.NewConnectionProvider(IDictionary`2 settings) at NHibernate.Tool.hbm2ddl.SchemaExport.Execute(Action`1 scriptAction, Boolean export, Boolean justDrop) at NHibernate.Tool.hbm2ddl.SchemaExport.Execute(Boolean script, Boolean export, Boolean justDrop) at FirstSolution.Tests.GenerateSchema_Fixture.Can_generate_schema() in C:\Users\Kash\Documents\Visual Studio 2010\Projects\FirstSolution\FirstSolution\GenerateSchema_Fixture.cs:line 23 at HibernateUnitTest.Form1.button1_Click(Object sender, EventArgs e) in C:\Users\Kash\Documents\Visual Studio 2010\Projects\FirstSolution\HibernateUnitTest\Form1.cs:line 23 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at HibernateUnitTest.Program.Main() in C:\Users\Kash\Documents\Visual Studio 2010\Projects\FirstSolution\HibernateUnitTest\Program.cs:line 18 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() I've made sure that System.Data.SqlServerCe has been referenced and that its Copy Local property is set to True. The error persists, however. Your help would be appreciated. Thanks.

    Read the article

  • How to set up precision attribute used by @Collumn annotation ???

    - by Arthur Ronald F D Garcia
    I often use java.lang.Integer as primary key. Here you can see some piece of code @Entity private class Person { private Integer id; @Id @Column(precision=8, nullable=false) public Integer getId() { } } I need to set up its precision attribute value equal to 8. But, when exporting The schema (Oracle), it does not work as expected. AnnotationConfiguration configuration = new AnnotationConfiguration(); configuration .addAnnotatedClass(Person.class) .setProperty(Environment.DIALECT, "org.hibernate.dialect.OracleDialect") .setProperty(Environment.DRIVER, "oracle.jdbc.driver.OracleDriver"); SchemaExport schema = new SchemaExport(configuration); schema.setOutputFile("schema.sql"); schema.create(true, false); schema.sql outputs create table Person (id number(10,0) not null) Always i get 10. Is There some workaround to get 8 instead of 10 ?

    Read the article

  • What causes this org.hibernate.MappingException?

    - by stacker
    I'm trying to configure an ejb3 sample application, it's entities where mapped to postgres now I want the app run on Jboss4.3 and Informix using JPA. If the DDL creation <property name="hibernate.hbm2ddl.auto" value="create"/> is active this error appears > WARN [ServiceController] Problem > starting service > persistence.units:ear=weblog.ear,jar=weblog.jar,unitName=weblog > javax.persistence.PersistenceException: > [PersistenceUnit: weblog] Unable to > build EntityManagerFactory > at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:677) > at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:132) > at org.jboss.ejb3.entity.PersistenceUnitDeployment.start(PersistenceUnitDeployment.java:246) followed by Caused by: org.hibernate.MappingException: No Dialect mapping for JDBC type: 2005 at org.hibernate.dialect.TypeNames.get(TypeNames.java:56) at org.hibernate.dialect.TypeNames.get(TypeNames.java:81) at org.hibernate.dialect.Dialect.getTypeName(Dialect.java:291) at org.hibernate.mapping.Column.getSqlType(Column.java:182) at org.hibernate.mapping.Table.sqlCreateString(Table.java:394) at org.hibernate.cfg.Configuration.generateSchemaCreationScript(Configuration.java:854) at org.hibernate.tool.hbm2ddl.SchemaExport.<init>(SchemaExport.java:74) at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:311) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1300) at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:874) at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669) What does JDBC type: 2005 mean? Any idea how I can track down the entity/column causes the problem? Thanks

    Read the article

  • Fluent Nhibernate - Mapping two entities to same table

    - by Andy
    Hi, I'm trying to map two domain entities to the same table. We're doing a smart entity for our domain model, so we have the concept of an Editable Address and a readonly Address. I have both mapped using Classmaps, and everything seems to go fine until we try to export the schema using the SchemaExport class from NHibernate. It errors out saying the table already exists. I assume it's something simple that I'm just not seeing. Any ideas? Thanks

    Read the article

  • Make Fluent NHibernate output schema update to file

    - by Bender
    I am successfully getting Fluent NHibernate to update my database by calling UpdateBaseFiles: Public Sub UpdateBaseFiles() Dim db As SQLiteConfiguration db = SQLiteConfiguration.Standard.UsingFile(BASE_DBNAME) Fluently.Configure() _ .Database(db) _ .Mappings(Function(m) m.FluentMappings.AddFromAssemblyOf(Of FluentMap)()) _ .ExposeConfiguration(AddressOf UpdateSchema) _ .BuildConfiguration() End Sub Private Sub UpdateSchema(ByVal Config As Configuration) Dim SchemaUpdater As New SchemaUpdate(Config) SchemaUpdater.Execute(True, True) End Sub How do I output the DDL to a file, I do this when initially creating the schema by using: Private Sub BuildSchema(ByVal Config As Configuration) Dim SchemaExporter As New SchemaExport(Config) SchemaExporter.SetOutputFile("schema.sql") SchemaExporter.Create(False, True) End Sub but SchemaUpdate does not have a SetOutputFile method.

    Read the article

  • NHibernate - fast way to clear out database

    - by csetzkorn
    Hi, I intend to perform some automated integration tests. This requires the db to be put back into a 'clean state'. Is this the fastest/best way to do this: var cfg = new Configuration(); cfg.Configure(); cfg.AddAssembly("Bla"); new SchemaExport(cfg).Execute(false, true, false); Thanks. Christian

    Read the article

  • Derby gets stuck closing?

    - by bmargulies
    I've got unit tests (in maven) that use derby. At the end of the test run, there is a very long pause, with these log messages before the pause. INFO: Closing Hibernate SessionFactory Nov 16, 2009 8:30:31 PM org.hibernate.impl.SessionFactoryImpl close INFO: closing Nov 16, 2009 8:30:31 PM org.hibernate.tool.hbm2ddl.SchemaExport execute INFO: Running hbm2ddl schema export Nov 16, 2009 8:30:31 PM org.hibernate.tool.hbm2ddl.SchemaExport execute INFO: exporting generated schema to database Hibernate config: <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.DerbyDialect</property> <property name="hbm2ddl.auto">create-drop</property> <property name="show_sql">false</property> </session-factory> </hibernate-configuration> referenced from: <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- data source elsewhere --> <property name="dataSource" ref="dataSource" /> <property name="mappingResources"> <list> <value>com/basistech/configdb/dao/Gazetteer.hbm.xml</value> <value>com/basistech/configdb/dao/FileGazetteer.hbm.xml</value> <value>com/basistech/configdb/dao/Regexpset.hbm.xml</value> <value>com/basistech/configdb/dao/Redactjoiner.hbm.xml</value> <value>com/basistech/configdb/dao/Misc.hbm.xml</value> </list> </property> <property name="configLocation" value="classpath:com/basistech/configdb/dao/hibernate.xml"/> and finally maven: <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>hibernate3-maven-plugin</artifactId> <version>2.2</version> <executions> <execution> <id>codegen</id> <goals> <goal>hbm2java</goal> </goals> <phase>generate-sources</phase> <configuration> <components> <component> <name>hbm2java</name> </component> </components> <componentProperties> <configurationfile>src/main/hibernate/codegen-hibernate.xml</configurationfile> </componentProperties> </configuration> </execution> </executions> </plugin>

    Read the article

  • NHibernate HiLo - new column per entity and HiLo catches

    - by Gareth
    Im currently using the hilo id generator for my classes but have just been using the minimal of settings eg <class name="ClassA" <id name="Id" column="id" unsaved-value="0" <generator class="hilo" / </id ... But should I really be specifying a new column for NHibernate to use foreach entity and providing it with a max lo? <class name="ClassA" <id name="Id" column="id" unsaved-value="0" <generator class="hilo" <param name="table"hibernate_unique_key</param <param name="column"classA_nexthi</param <param name="max_lo"20</param </generator </id ... <class name="ClassB" <id name="Id" column="id" unsaved-value="0" <generator class="hilo" <param name="table"hibernate_unique_key</param <param name="column"classB_nexthi</param <param name="max_lo"20</param </generator </id ... Also I've noticed that when I do the above the SchemaExport will not create all the columns - only classB_nexthi, is there something else im doing wrong. Thanks

    Read the article

  • unit test service layer - NUnit, NHibernate

    - by csetzkorn
    Hi, I would like to unit test a DEPENDENT service layer which allows me to perform CRUD operation without mocking using NUnit. I know this is probably bad practice but I want to give it a try anyway - even if the tests have to run over night. My data is persisted using NHibernate and I have implemented a little library that 'bootstraps' the database which I could use in a [Setup] method. I am just wondering if someone has done something similar and what the fastest method for bootstrapping the database is. I am using something like this: var cfg = new Configuration(); cfg.Configure(); cfg.AddAssembly("Bla"); new SchemaExport(cfg).Execute(false, true, false); to establish the db schema. After that I populate some lookup tables from some Excel tables. Any feedback would be very much appreciated. Thanks. Christian

    Read the article

  • Nhibernate.Bytecode.Castle Trust Level on IIS

    - by jack london
    Trying to deploy the wcf service, depended on nhibernate. And getting the following exception On Reflection activator. [SecurityException: That assembly does not allow partially trusted callers.] System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed) +150 System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0 System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +86 System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +230 System.Activator.CreateInstance(Type type, Boolean nonPublic) +67 NHibernate.Bytecode.ActivatorObjectsFactory.CreateInstance(Type type) +8 NHibernate.Driver.ReflectionBasedDriver.CreateConnection() +28 NHibernate.Connection.DriverConnectionProvider.GetConnection() +56 NHibernate.Tool.hbm2ddl.SchemaExport.Execute(Action`1 scriptAction, Boolean export, Boolean justDrop) +376 in IIS configuration service's trust level is Full-trust also application's web config's trust level is full. how could i make this service in working state?

    Read the article

  • Modifying annotation attribute value at runtime in java

    - by Lici
    Hi folks: some methods in our model pojos have been annotated like this: @Column(name="cli_clipping_id", updatable=false, columnDefinition = "varchar(" + ModelUtils.ID_LENGTH + ") COLLATE utf8_bin") columnDefinition attribute is database vendor dependant, so when trying to drop schema in HSQLDB using Hibernate it fails: [ERROR] 16 jun 12:58:42.480 PM main [org.hibernate.tool.hbm2ddl.SchemaExport] Unexpected token: COLLATE in statement [create table cms.edi_editorial_obj (edi_uuid varchar(23) COLLATE ] To fix this, i'm thinking on this solution (but don't want to spend time if it isn't possible) , at runtime, for each method column annotated: Get @Column annotation Create a copy of the column annotation, setting columnDefinition null using javaassist. set column method annotation to the copy column annotation object overriding the old one (i don't know it this is possible) Is it possible to "hack" these methods this way? Any help would be much appreciated ...

    Read the article

  • SQLite not pluralizing Table Names

    - by weenet
    I am using SQLite as my db during development, and I want to postpone actually creating a final database until my domains are fully mapped. So I have this in my Global.asax.cs file: private void InitializeNHibernateSession() { Configuration cfg = NHibernateSession.Init( webSessionStorage, new [] { Server.MapPath("~/bin/MyNamespace.Data.dll") }, new AutoPersistenceModelGenerator().Generate(), Server.MapPath("~/NHibernate.config")); if (ConfigurationManager.AppSettings["DbGen"] == "true") { var export = new SchemaExport(cfg); export.Execute(true, true, false, NHibernateSession.Current.Connection, File.CreateText(@"DDL.sql")); } } The AutoPersistenceModelGenerator hooks up the various conventions, including a TableNameConvention like so: public void Apply(FluentNHibernate.Conventions.Instances.IClassInstance instance) { instance.Table(Inflector.Net.Inflector.Pluralize(instance.EntityType.Name)); } This is working nicely execpt that the sqlite db generated does not have pluralized table names. Any idea what I'm missing? Thanks.

    Read the article

  • Fluent NHibernate Automap does not take into account IList<T> collections as indexed

    - by Francisco Lozano
    I am using automap to map a domain model (simplified version): public class AppUser : Entity { [Required] public virtual string NickName { get; set; } [Required] [DataType(DataType.Password)] public virtual string PassKey { get; set; } [Required] [DataType(DataType.EmailAddress)] public virtual string EmailAddress { get; set; } public virtual IList<PreferencesDescription> PreferencesDescriptions { get; set; } } public class PreferencesDescription : Entity { public virtual AppUser AppUser { get; set; } public virtual string Content{ get; set; } } The PreferencesDescriptions collection is mapped as an IList, so is an indexed collection (when I require standard unindexed collections I use ICollection). The fact is that fluent nhibernate's automap facilities map my domain model as an unindexed collection (so there's no "position" property in the DDL generated by SchemaExport). ¿How can I make it without having to override this very case - I mean, how can I make Fluent nhibernate's automap make always indexed collections for IList but not for ICollection

    Read the article

  • change custom mapping - sharp architecture/ fluent nhibernate

    - by csetzkorn
    I am using the sharp architecture which also deploys FNH. The db schema sql code is generated during the testing like this: [TestFixture] [Category("DB Tests")] public class MappingIntegrationTests { [SetUp] public virtual void SetUp() { string[] mappingAssemblies = RepositoryTestsHelper.GetMappingAssemblies(); configuration = NHibernateSession.Init( new SimpleSessionStorage(), mappingAssemblies, new AutoPersistenceModelGenerator().Generate(), "../../../../app/XXX.Web/NHibernate.config"); } [TearDown] public virtual void TearDown() { NHibernateSession.CloseAllSessions(); NHibernateSession.Reset(); } [Test] public void CanConfirmDatabaseMatchesMappings() { var allClassMetadata = NHibernateSession.GetDefaultSessionFactory().GetAllClassMetadata(); foreach (var entry in allClassMetadata) { NHibernateSession.Current.CreateCriteria(entry.Value.GetMappedClass(EntityMode.Poco)) .SetMaxResults(0).List(); } } /// <summary> /// Generates and outputs the database schema SQL to the console /// </summary> [Test] public void CanGenerateDatabaseSchema() { System.IO.TextWriter writeFile = new StreamWriter(@"d:/XXXSqlCreate.sql"); var session = NHibernateSession.GetDefaultSessionFactory().OpenSession(); new SchemaExport(configuration).Execute(true, false, false, session.Connection, writeFile); } private Configuration configuration; } I am trying to use: using FluentNHibernate.Automapping; using xxx.Core; using SharpArch.Data.NHibernate.FluentNHibernate; using FluentNHibernate.Automapping.Alterations; namespace xxx.Data.NHibernateMaps { public class x : IAutoMappingOverride<x> { public void Override(AutoMapping<Tx> mapping) { mapping.Map(x => x.text, "text").CustomSqlType("varchar(max)"); mapping.Map(x => x.url, "url").CustomSqlType("varchar(max)"); } } } To change the standard mapping of strings from NVARCHAR(255) to varchar(max). This is not picked up during the sql schema generation. I also tried: mapping.Map(x = x.text, "text").Length(100000); Any ideas? Thanks. Christian

    Read the article

  • Learning Hibernate: too many connections

    - by stivlo
    I'm trying to learn Hibernate and I wrote the simplest Person Entity and I was trying to insert 2000 of them. I know I'm using deprecated methods, I will try to figure out what are the new ones later. First, here is the class Person: @Entity public class Person { private int id; private String name; @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "person") @TableGenerator(name = "person", table = "sequences", allocationSize = 1) public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Then I wrote a small App class that insert 2000 entities with a loop: public class App { private static AnnotationConfiguration config; public static void insertPerson() { SessionFactory factory = config.buildSessionFactory(); Session session = factory.getCurrentSession(); session.beginTransaction(); Person aPerson = new Person(); aPerson.setName("John"); session.save(aPerson); session.getTransaction().commit(); } public static void main(String[] args) { config = new AnnotationConfiguration(); config.addAnnotatedClass(Person.class); config.configure("hibernate.cfg.xml"); //is the default already new SchemaExport(config).create(true, true); //print and execute for (int i = 0; i < 2000; i++) { insertPerson(); } } } What I get after a while is: Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Cannot open connection Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Too many connections Now I know that probably if I put the transaction outside the loop it would work, but mine was a test to see what happens when executing multiple transactions. And since there is only one open at each time, it should work. I tried to add session.close() after the commit, but I got Exception in thread "main" org.hibernate.SessionException: Session was already closed So how to solve the problem?

    Read the article

  • How to manage sessions in NHibernate unit tests?

    - by Ben
    I am a little unsure as to how to manage sessions within my nunit test fixtures. In the following test fixture, I am testing a repository. My repository constructor takes in an ISession (since I will be using session per request in my web application). In my test fixture setup I configure NHibernate and build the session factory. In my test setup I create a clean SQLite database for each test executed. [TestFixture] public class SimpleRepository_Fixture { private static ISessionFactory _sessionFactory; private static Configuration _configuration; [TestFixtureSetUp] // called before any tests in fixture are executed public void TestFixtureSetUp() { _configuration = new Configuration(); _configuration.Configure(); _configuration.AddAssembly(typeof(SimpleObject).Assembly); _sessionFactory = _configuration.BuildSessionFactory(); } [SetUp] // called before each test method is called public void SetupContext() { new SchemaExport(_configuration).Execute(true, true, false); } [Test] public void Can_add_new_simpleobject() { var simpleObject = new SimpleObject() { Name = "Object 1" }; using (var session = _sessionFactory.OpenSession()) { var repo = new SimpleObjectRepository(session); repo.Save(simpleObject); } using (var session =_sessionFactory.OpenSession()) { var repo = new SimpleObjectRepository(session); var fromDb = repo.GetById(simpleObject.Id); Assert.IsNotNull(fromDb); Assert.AreNotSame(simpleObject, fromDb); Assert.AreEqual(simpleObject.Name, fromDb.Name); } } } Is this a good approach or should I be handling the sessions differently? Thanks Ben

    Read the article

  • How to make Spring load a JDBC Driver BEFORE initializing Hibernate's SessionFactory?

    - by Bill_BsB
    I'm developing a Spring(2.5.6)+Hibernate(3.2.6) web application to connect to a custom database. For that I have custom JDBC Driver and Hibernate Dialect. I know for sure that these custom classes work (hard coded stuff on my unit tests). The problem, I guess, is with the order on which things get loaded by Spring. Basically: Custom Database initializes Spring load beans from web.xml Spring loads ServletBeans(applicationContext.xml) Hibernate kicks in: shows version and all the properties correctly loaded. Hibernate's HbmBinder runs (maps all my classes) LocalSessionFactoryBean - Building new Hibernate SessionFactory DriverManagerConnectionProvider - using driver: MyCustomJDBCDriver at CustomDBURL I get a SQLException: No suitable driver found for CustomDBURL Hibernate loads the Custom Dialect My CustomJDBCDriver finally gets registered with DriverManager (log messages) SettingsFactory runs SchemaExport runs (hbm2ddl) I get a SQLException: No suitable driver found for CustomDBURL (again?!) Application get successfully deployed but there are no tables on my custom Database. Things that I tried so far: Different techniques for passing hibernate properties: embedded in the 'sessionFactory' bean, loaded from a hibernate.properties file. Nothing worked but I didn't try with hibernate.cfg.xml file neither with a dataSource bean yet. MyCustomJDBCDriver has a static initializer block that registers it self with the DriverManager. Tried different combinations of lazy initializing (lazy-init="true") of the Spring beans but nothing worked. My custom JDBC driver should be the first thing to be loaded - not sure if by Spring but...! Can anyone give me a solution for this or maybe a hint for what else I could try? I can provide more details (huge stack traces for instance) if that helps. Thanks in advance.

    Read the article

  • NHibernate not dropping foreign key constraints.

    - by Kendrick
    I'm new to NHibernate, so this is probably my mistake, but when I use: schema.Create(true, true); I get: SchemaExport [(null)]- There is already an object named 'XXX' in the database. System.Data.SqlClient.SqlException: There is already an object named 'XXX' in the database. I grabbed the SQL code nHibernate was using, ran it directly from MSSMS, and recieved similar errors. Looking into it, the generated code is not properly dropping the foreign key constraints. The drop looks like this: if exists (select 1 from sysobjects where id = OBJECT_ID(N'dbo[FK22212EAFBFE4C58]') AND parent_obj = OBJECT_ID('YYY')) alter table dbo.YYY drop constraint FK22212EAFBFE4C58 Doing a "select OBJECT_ID(N'dbo[FK22212EAFBFE4C58]')" I get null. If I take out the "dbo" (i.e. "select OBJECT_ID(N'[FK22212EAFBFE4C58]')") then the ID is returned. So, my question is, why is nHibernate adding the dbo, and why does that prevent the object from being returned (since the table owning the constraint is dbo.XXX) One of my mapping files: <?xml version="1.0" encoding="utf-8"?> <hibernate-mapping namespace="CanineApp.Model" assembly="CanineApp.Model" xmlns="urn:nhibernate-mapping-2.2"> <class name="MedicalLog" table="MedicalLog" schema="dbo"> <id name="MedicalLogID" type="Int64"> <generator class="identity" /> </id> <property name="InvoiceAmount" type="Decimal" not-null="true" /> ... <many-to-one name="Canine" class="Canine" column="CanineID" not-null="true" fetch="join" /> <many-to-one name="TreatmentCategory" class="TreatmentCategory" column="TreatmentCategoryID" not-null="true" access="field.camelcase-underscore" /> </class> </hibernate-mapping>

    Read the article

1 2  | Next Page >