如何使用hibernate动态添加列

时间:2017-10-23 03:36:26

标签: java mysql hibernate ddl dialect

我正在练习' Hibernate'用mysql。

我想添加新列,例如' ALTER TABLE学生ADD COLUMN手机varchar(255)'通过使用hibernate。 但是,我不知道如何编写函数&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将列添加到表中。

1 个答案:

答案 0 :(得分: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(hibernate - 映射文件)中对此phone属性进行映射。