我在Nhibernate中编写了一个测试mysql连接项目。这个例外正在显示..
NHibernate.HibernateException: 'You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right
syntax to use near 'Character (Id VARCHAR(40) not null, Name
VARCHAR(255), HealthPoints INTEGER, Man' at line 1'
hibernate.cfg.xml
文件是
<?xml version="1.0" encoding="utf-8"?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="NHibernate.Test">
<property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver</property>
<property name="connection.connection_string">
Database=nhibernate;Data Source=localhost;User Id=ajoy;Password=ajoy
</property>
<property name="dialect">NHibernate.Dialect.MySQLDialect</property>
</session-factory>
</hibernate-configuration>
模型类是
namespace NhibernateTest.Domain
{
public class Character
{
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
public virtual int HealthPoints { get; set; }
public virtual int Mana { get; set; }
public virtual string Profession { get; set; }
}
}
映射xml是..
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="NhibernateTest"
namespace="NhibernateTest.Domain">
<class name="Character">
<id name="Id">
<generator class="guid" />
</id>
<property name="Name" />
<property name="HealthPoints" />
<property name="Mana" />
<property name="Profession" />
</class>
</hibernate-mapping>
我的主要课程是
class Program
{
static void Main(string[] args)
{
LoadNHibernateCfg();
/* CRUD */
CharacterRepository repo = new CharacterRepository();
//CREATE!
var MikeAbyss = new Character { Name = "MikeAbyss", HealthPoints = 700, Mana = 10, Profession = "Knight" };
repo.Add(MikeAbyss);
//READ!
Character mike = repo.GetCharacterByName("MikeAbyss");
//UPDATE!
mike.Name = "Mike";
repo.Update(mike);
//DELETE!
repo.Delete(mike);
Console.ReadKey();
}
public static void LoadNHibernateCfg()
{
var cfg = new Configuration();
cfg.Configure();
cfg.AddAssembly(typeof(Character).Assembly);
SchemaExport schemaExport = new SchemaExport(cfg);
schemaExport.SetDelimiter(";");
schemaExport.Execute(true, true, false);
}
我试过没有schemaExport.SetDelimiter(";");
,但仍然是同样的错误。
控制台中的输出是
drop table if exists Character;
create table Character (
Id VARCHAR(40) not null,
Name VARCHAR(255),
HealthPoints INTEGER,
Mana INTEGER,
Profession VARCHAR(255),
primary key (Id)
);
Mysql版本是5.7.14。我该如何解决这个问题?
答案 0 :(得分:1)
您的一个或多个标识符可能是reserved words。您需要quote them:定义用反向标记包围的数据库名称。
例如,引用Character
和Name
:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="NhibernateTest"
namespace="NhibernateTest.Domain">
<class name="Character" table="`Character`">
<id name="Id">
<generator class="guid" />
</id>
<property name="Name" column="`Name`" />
<property name="HealthPoints" />
<property name="Mana" />
<property name="Profession" />
</class>
</hibernate-mapping>