0

I'm practicing 'Hibernate' with mysql.

I want to add new column like 'ALTER TABLE Student ADD COLUMN phone varchar(255)' by using hibernate. But, I don't know how to code function '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.*/
    }
}

Please let's me know how to add column to table by using hibernate.

1 Answer 1

1

If you current tables are generated using Hibernate, you can simply add the phone property in the java entity class for the phone column.

Then set the hibernate.hbm2ddl.auto property to update and hibernate will automatically create this column when the SessionFactory is built next time.


Student.java

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

        //generate getters & setters
        }

and also do mapping for this phone property in student.xml (hibernate - mapping file).

Sign up to request clarification or add additional context in comments.

4 Comments

Instead add to Student class, is there other way by using alter table clause.
@KwangHunLee, Hibernate is creating the column for you just by adding a property in entity class (ie Student class) so why do you want to hardcode and add a column.According to my knowledge, it's the best approach to add ur revise property in entity class and execute hibernate.hbm2ddl.auto to update.
Because, I'm making my own Dialect class for our compay. So I need to test all about Diaclect functions.
@KwangHunLee, Can you refer this article [link] ( infoq.com/articles/hibernate-custom-fields).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.