Riyad
Riyad

Reputation: 111

I cannot auto create table from hibernate project

I have a hibernate project and I want to auto create table. And if a table is already created then I add a new field in the Entity class then I want to create a new field in the table without deleting data of the table.I'm giving my source in the below.

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.MySQLDialect</property>
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.connection.password">1234</property>
  <property name="hibernate.show_sql">true</property>
  <property name="hibernate.hbm2ddl.auto">create</property>

  <mapping class="Inventory" package="com.mycompany.testhibernate"/>


   </session-factory>
   </hibernate-configuration>

EntityClass

     package com.mycompany.testhibernate;

     import java.io.Serializable;
     import javax.persistence.Entity;
     import javax.persistence.GeneratedValue;
     import javax.persistence.GenerationType;
     import javax.persistence.Id;

     @Entity
    public class Inventory implements Serializable {
       private Integer id;
       private String itemName;
       private String itemNote;
       private Integer quantity;

       @Id
       @GeneratedValue(strategy=GenerationType.AUTO)
       public int getId() {
        return id;
       }

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

   public String getItemName() {
    return this.itemName;
   }

   public void setItemName(String itemName) {
    this.itemName = itemName;
   }

   public String getItemNote() {
    return itemNote;
   }

   public void setItemNote(String itemNote) {
    this.itemNote = itemNote;
  }

   public void setQuantity(Integer quantity) {
    this.quantity = quantity;
  }

  public int getQuantity() {
    return this.quantity;
  }    


   }

Upvotes: 0

Views: 91

Answers (1)

cralfaro
cralfaro

Reputation: 5948

Did you try with this option?

<property name="hibernate.hbm2ddl.auto">update</property>

Should update your DDL according to your beans

hbm2ddl.auto update :

If the value is update then hibernate checks for the table and columns. If table doesn’t exist then it creates a new table and if a column doesn’t exist it creates new column for it.

Also change the property to:

<mapping class="com.mycompany.testhibernate.Inventory"/>

Upvotes: 1

Related Questions