【问题标题】:how to add column dynamically using hibernate如何使用休眠动态添加列
【发布时间】:2018-04-03 13:02:33
【问题描述】:

我正在用 mysql 练习“休眠”。

我想通过使用休眠添加新列,例如“ALTER TABLE Student ADD COLUMN phone varchar(255)”。 但是,我不知道如何编写函数'addColumn()'。

学生.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;
    }
}

学生.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>

配置.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.*/
    }
}

请告诉我如何使用休眠向表中添加列。

【问题讨论】:

    标签: java mysql hibernate ddl dialect


    【解决方案1】:

    如果您当前的表是使用 Hibernate 生成的,您只需在 java 实体类中为 phone 列添加 phone 属性。

    然后将hibernate.hbm2ddl.auto属性设置为update,下次构建SessionFactory时hibernate会自动创建该列。


    学生.java

        public class Student
            {
            private long id;
            private String name;
            private String degree;
            private String phone;
    
            //generate getters & setters
            }
    

    并且还在 student.xml(休眠 - 映射文件)中为这个电话属性做映射。

    【讨论】:

    • 添加到Student类,有没有其他方法可以使用alter table子句。
    • @KwangHunLee,Hibernate 只是通过在实体类(即学生类)中添加一个属性来为您创建列,那么您为什么要硬编码并添加一个列。据我所知,它是在实体类中添加您的 revise 属性并执行 hibernate.hbm2ddl.auto 进行更新的最佳方法。
    • 因为,我正在为我们的公司制作自己的方言课程。所以我需要测试有关方言函数的所有内容。
    • @KwangHunLee,你能参考这篇文章吗[链接](infoq.com/articles/hibernate-custom-fields)。
    猜你喜欢
    • 1970-01-01
    • 2018-05-25
    • 2014-04-13
    • 2019-06-16
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    相关资源
    最近更新 更多