Hibernate只创建一些表

时间:2018-05-02 10:58:24

标签: java spring postgresql hibernate spring-mvc

Hibernate hbm2ddl仅在创建SessionFactory时创建6个表中的2个。

创建的表格示例:

@Entity
@Table(name = "AUTHORITIES")
public class Authorities {
  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  private int id;


  @Column(name = "AUTHORITY", nullable=false)
  private String authority;

  @ManyToOne
  @JoinColumn(name = "USERNAME", nullable=false)
  private User user;
...getters, setters...

未创建的表格示例:

@Entity
@Table(name = "EXERCISES")
public class Exercise {
  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  private int id;


  @Column(name = "NAME", nullable=false)
      private String name;


  @Column(name = "DESCRIPTION")
      private String description;
...getters, setters...

Hibernate属性

hibernate.show_sql=true
hibernate.hbm2ddl.auto=create
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

来自控制台的SQL:

Hibernate: drop table if exists AUTHORITIES cascade
Hibernate: drop table if exists USERS cascade
Hibernate: create table AUTHORITIES (id  serial not null, AUTHORITY varchar(255) not null, USERNAME varchar(255) not null, primary key (id))
Hibernate: create table USERS (USERNAME varchar(255) not null, ENABLED boolean not null, PASSWORD varchar(255) not null, primary key (USERNAME))
Hibernate: alter table AUTHORITIES add constraint FKl8gm1dxqhdixkdsm1p7er9c21 foreign key (USERNAME) references USERS

数据库是远程的ElephantSQL。

1 个答案:

答案 0 :(得分:0)

好的,正如duffymo指出的那样,配置错误。

  @Bean

public LocalSessionFactoryBean getSessionFactory(){     LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();

Properties props = new Properties();

// Setting JDBC properties
props.put(DRIVER, env.getProperty("driver"));
props.put(URL, env.getProperty("jdbcUrl"));
props.put(USER, env.getProperty("username"));
props.put(PASS, env.getProperty("password"));

// Setting Hibernate properties
props.put(SHOW_SQL, env.getProperty("hibernate.show_sql"));
props.put(HBM2DDL_AUTO, env.getProperty("hibernate.hbm2ddl.auto"));
props.put(DIALECT, env.getProperty("hibernate.dialect"));

// Setting C3P0 properties
props.put(C3P0_MIN_SIZE, env.getProperty("hibernate.c3p0.min_size"));
props.put(C3P0_MAX_SIZE, env.getProperty("hibernate.c3p0.max_size"));
props.put(C3P0_ACQUIRE_INCREMENT, env.getProperty("hibernate.c3p0.acquire_increment"));
props.put(C3P0_TIMEOUT, env.getProperty("hibernate.c3p0.timeout"));
props.put(C3P0_MAX_STATEMENTS, env.getProperty("hibernate.c3p0.max_statements"));

factoryBean.setHibernateProperties(props);
factoryBean.setAnnotatedClasses(User.class, Authorities.class, Exercise.class, ExerciseUnit.class, Routine.class, Training.class);

return factoryBean;

我忘了在下面设置新实体:

    factoryBean.setAnnotatedClasses(User.class, Authorities.class, Exercise.class, ExerciseUnit.class, Routine.class, Training.class);