2017-10-23 17 views
0

私はmysqlで 'Hibernate'を実践しています。hibernateを使ってカラムを動的に追加する方法

hibernateを使用して 'ALTER TABLE Student ADD COLUMN phone varchar(255)'のような新しい列を追加したいと思います。 しかし、私はどのように関数 'addColumn()'をコードするのか分かりません。

Student.java

package hib.dia.gol; 

public class Student 
{ 
    private long id; 
    private String name; 
    private String degree; 

    public Student() { 
     this.name = null; 
     this.degree = null; 
    } 

    public Student(String name, String degree) { 
     this.name = name; 
     this.degree = degree; 
    } 

    public long getId() { 
     return id; 
    } 

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

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public String getDegree() { 
     return degree; 
    } 

    public void setDegree(String degree) { 
     this.degree = degree; 
    } 
} 

student.xml

<?xml version="1.0" encoding="UTF-8"?> 
    <!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping> 
    <class name="hib.dia.gol.Student" table="STUDENT"> 
     <id column="ID" name="id" type="long"> 
      <generator class="increment" /> 
    </id> 
      <property column="STUDENT_NAME" name="name" type="string" /> 
      <property column="DEGREE" name="degree" type="string" /> 
      <property column="PHONE" name="phone" type="string" /> 
    </class> 
</hibernate-mapping> 

configure.xml

<?xml version="1.0" encoding="utf-8"?> 
<!DOCTYPE hibernate-configuration PUBLIC 
"-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 

<hibernate-configuration> 
    <session-factory> 
     <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">test</property> 
     <property name="hibernate.connection.password">test</property> 
     <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> 
     <property name="show_sql">true</property> 
     <property name="format_sql">true</property> 
     <property name="hbm2ddl.auto"> update </property> 
     <mapping resource="hib/dia/gol/student.xml" /> 
    </session-factory> 
</hibernate-configuration> 

Test.java

package hib.dia.gol; 

import java.util.Iterator; 
import java.util.List; 

import org.hibernate.Query; 
import org.hibernate.Session; 
import org.hibernate.Transaction; 
import org.hibernate.SessionFactory; 
import org.hibernate.cfg.Configuration; 
import org.hibernate.HibernateException; 

public class Test 
{ 
    private static SessionFactory mFactory; 

    public static void main(String[] args) { 
     try { 
      mFactory = new Configuration().configure("configure.xml").buildSessionFactory(); 
     } catch (Throwable ex) { 
      System.err.println("Failed to create sessionFactory object." + ex); 
      throw new ExceptionInInitializerError(ex); 
     } 

     Test sTest = new Test(); 

     Long sSt1 = sTest.addStudent("Lee", "MD"); 
     Long sSt2 = sTest.addStudent("Kim", "DD"); 
     Long sSt3 = sTest.addStudent("Park", "MD"); 
     Long sSt4 = sTest.addStudent("Ha", "DD"); 
     Long sSt5 = sTest.addStudent("Kwak", "BD"); 
     Long sSt6 = sTest.addStudent("Oh", "DD"); 
     Long sSt7 = sTest.addStudent("Shin", "BD"); 

     sTest.listStudent(); 

     sTest.updateStudent(sSt3, "DD"); 

     sTest.listStudent(); 

     sTest.deleteStudent(sSt2); 

     sTest.listStudent(); 
    } 

    public Long addStudent(String name, String degree) { 
     Session session = mFactory.openSession(); 
     Transaction tx = null; 
     Long id = null; 

     try { 
      tx = (Transaction) session.beginTransaction(); 
      Student student = new Student(name, degree); 
      id = (Long) session.save(student); 
      tx.commit(); 

      System.out.println("add success"); 
     } catch(HibernateException e) { 
      if(tx != null) { 
       tx.rollback(); 
      } 
      System.out.println("add fail"); 
      e.printStackTrace(); 
     } finally { 
      session.close(); 
     } 
     return id; 
    } 

    public void listStudent() { 
     Session session = mFactory.openSession(); 
     Transaction tx = null; 
     Query query = null; 

     try{ 
      tx = session.beginTransaction(); 

      query = session.createQuery("FROM Student"); 

      query.setMaxResults(10); 
      query.setFirstResult(0); 
      query.setFetchSize(5); 

      @SuppressWarnings("unchecked") 
      List<Student> students = (List<Student>) query.list(); 

      for(Iterator<Student> iter = students.iterator(); iter.hasNext();) { 
       Student student = (Student) iter.next(); 
       System.out.print("id: " + student.getId()); 
       System.out.print(" name: " + student.getName()); 
       System.out.print(" degree: " + student.getDegree()); 
      } 

      tx.commit(); 
     } catch (HibernateException e) { 
      e.printStackTrace(); 
     } finally { 
      session.close(); 
     } 
    } 

    public void updateStudent(long id, String degree) { 
     Session session = mFactory.openSession(); 
     Transaction tx = null; 

     try { 
      tx = session.beginTransaction(); 

      Student student = (Student) session.get(Student.class, id); 
      student.setDegree(degree); 

      session.update(student); 

      tx.commit(); 

      System.out.println("update success"); 
     } catch (HibernateException e) { 
      if(tx != null) { 
       tx.rollback(); 
      } 
      System.out.println("update fail"); 
      e.printStackTrace(); 
     } finally { 
      session.close(); 
     } 
    } 

    public void deleteStudent(long id) { 
     Session session = mFactory.openSession(); 
     Transaction tx = null; 

     try { 
      tx = session.beginTransaction(); 
      Student student = (Student) session.get(Student.class, id);  
      session.delete(student); 
      tx.commit();   
      System.out.println("delete success"); 
     } catch (HibernateException e) { 
      if(tx != null) { 
       tx.rollback(); 
      } 

      System.out.println("delete fail"); 
      e.printStackTrace(); 
     } finally { 
      session.close(); 
     } 
    } 

    public addColumn(String table, String column, Types type) { 
     Session session = mFactory.openSession(); 
     Transaction tx = null; 
     Query query = null; 

    /* I don't know this part.*/ 
    } 
} 

hibernateを使ってテーブルにカラムを追加する方法を教えてください。

答えて

0

現在のテーブルがHibernateを使用して生成されている場合は、phoneプロパティのJavaエンティティクラスにphoneプロパティを追加するだけです。

hibernate.hbm2ddl.autoプロパティをupdateに設定し、次回にSessionFactoryをビルドするときにhibernateが自動的にこの列を作成します。


Student.java

public class Student 
     { 
     private long id; 
     private String name; 
     private String degree; 
     private String phone; 

     //generate getters & setters 
     } 

ともstudent.xmlで、この携帯電話のプロパティのマッピングを行う(休止状態 - マッピングファイル)。

+0

代わりにStudentクラスに追加してください。他の方法はalter table節を使用することです。 –

+0

@KwangHunLee、Hibernateはエンティティクラス(つまり、Studentクラス)にプロパティを追加するだけで、あなたのためにカラムを作成しています。なぜ、ハードコードしてカラムを追加したいのですか?私の知る限り、urの改訂プロパティ更新するためにhibernate.hbm2ddl.autoを実行してください。 –

+0

私は私たちのコンパイラのために私自身のDialectクラスを作っているからです。だから私はDiaclectの機能についてすべてをテストする必要があります。 –

関連する問題