Hibernate创建错误的create table语句?

时间:2014-11-16 17:26:22

标签: java hibernate postgresql

这是我第一次配置hibernate。我已经阅读了很多教程但不确定为什么这会创建错误的create table sql语句。我使用PostgreSQL作为我的数据库。

的hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL9Dialect</property>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.url">jdbc:postgresql://DBIP:5432/MYDB</property>
        <property name="hibernate.connection.username">MYDB</property>
        <property name="hibernate.connection.password">MYPASS</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create</property>
        <property name="show_sql">true</property>

        <mapping class="MYPROJ.model.User"/>
    </session-factory>
</hibernate-configuration>

User.java

package MYPROJ.model;

import javax.persistence.*;

@Entity
public class User
{
  @Id @GeneratedValue
  @Column(name = "id")
  private int id;

  @Column(name = "username")
  private String username;

  @Column(name = "age")
  private int age;

    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    public String getUsername()
    {
        return username;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    public int getAge()
    {
        return age;
    }

    public void setAge(int age)
    {
        this.age = age;
    }
}

Main.java

public class Main
{
    public static void main(String[] args)
    {
        User user = new User();
        user.setId(1);
        user.setAge(20);
        user.setUsername("david");

        SessionFactory sessionFactory;
        ServiceRegistry serviceRegistry;

        Configuration configuration = new Configuration();
        configuration.configure();
        serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);


        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(user);
        session.getTransaction().commit();
        System.out.println("Done!");

    }
}

当我运行程序时,它会显示以下用于创建表的SQL语句,该表在运行程序时或我手动复制粘贴时不起作用

create table User (id int4 not null, age int4, username varchar(255), primary key (id))

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

事实证明,“user”是PostgreSQL中的保留关键字,改变了这个问题解决了问题。

答案 1 :(得分:0)

您可以告诉hibernate您的列名必须被转义以避免与数据库关键字冲突。为此,请将名称括在`之间。例如:

@Column(name="`user`")