JDBC - Getting tables from database

You can retrieve all tables from database using JDBC. DatabaseMetaData object contains various method to get the meta information from any database. This object can be accessed by invoking getMetaData() on the Connection object.


DatabaseMetaData dbmd=con.getMetaData();
 After getting the DatabaseMetaData, you can use it to retrieve the tables from any database like following statement,

ResultSet rs=dbmd.getTables(null,null,null,new String[]{"table"});
Here, you will get the ResultSet Object containing various other information like Schema, catalog, table name, etc. Table name available in third column of this ResultSet so we can get it as rs.getString(3);

To get all tables from a database using Connection, we need to traverse entire ResultSet object. We have to invoke rs.next() till it returns false and on each invocation of rs.next(), get the data from third column to get the name of the table.

Here is a method that returns the array of table names from the database connection.



 public String[] tables()throws Exception
{
           DatabaseMetaData dbmd=con.getMetaData();
           ResultSet rs=dbmd.getTables(null,null,null,new String[]{"table"});
           String tablesNames="";
           while(rs.next()){
                   //retrieving table name and concating it to string  tablesNames using comma as a separator between names        
                   tablesNames=tablesNames+rs.getString(3)+",";
           }
            // getting array of table names from comma separated tableNames String
           String names[]=tablesNames.split(",");
           return names;
}   





Hibernate- Defining table and columns for mapping


If you want to define customized name for the table and column, you have to use @Table and @Column annotations. @Table allows you to define the table, catalog, and schema names for your entity mapping.
If no @Table is defined the default values are used: the unqualified class name of the entity.

You can also define unique constraints to the table using the @UniqueConstraint annotation in conjunction with @Table

@Table(name="profile",
uniqueConstraints = {@UniqueConstraint(columnNames={"country", "state"})}
)


@Column annotation allows you to specify the column name to be pointed out in table.
Following are attribute of the @Column annotation
name="columnName";
boolean unique() default false;
boolean nullable() default true;
boolean insertable() default true;
boolean updatable() default true;
String columnDefinition() default "";
String table() default "";
int length() default 255;
int precision() default 0;
int scale() default 0;

example :
@Column(updatable = false, name = "fullname", nullable = false, length=50)
public String getName() { ... }


Demo
package domain;

import java.util.Date;

import javax.persistence.*;
import javax.persistence.Id;

@Entity
@Table(name="User_Profile")
public class Profile {
    private int id;
    private String name;
    private String email;
    private Date dateOfBirth;
    private long phone;

    public Profile() {

    }

    public Profile(int id, String name, String email, Date dateOfBirth,
            long phone) {
        super();
        this.id = id;
        this.name = name;
        this.email = email;
        this.dateOfBirth = dateOfBirth;
        this.phone = phone;
    }

    @Id
    @Column(name="Profile_id")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    @Column(name="Name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    @Column(name="Email")
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
    @Column(name="DateOfBirth")
    public Date getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }
    @Column(name="Phone")
    public long getPhone() {
        return phone;
    }

    public void setPhone(long phone) {
        this.phone = phone;
    }
}

SVN problem while committing or updating the directory

You may see following error when you are committing or updating directory,



Update/Commit
Working copy 'E:\work\myproject locked
Please execute the 'Cleanup' command.

According to the above error message, you should execute Cleanup command from svn-client like TortoiseSVN.

But when you are performing cleanup, you may get another problem as shown below.

Cleanup failed to process the following paths:
-'E:\work\myproject
''E:\work\myproject\build' is not a working copy directory

According to above error message, you should follow the following steps :
  • delete the build folder
  • update the folder myproject by executing the svn-command update
  • then commit the changes by executing the commit svn-command

If this problem is due to conflicting changes between local and server contents and you have resolve the problem manually, use resolved svn-command for confirmation.

There may be other issues and solution for svn, please let me know if you have.

ERROR org.hibernate.LazyInitializationException - could not initialize proxy - no Session

Following code was creating problem while I trying to use the hibernate to fetch data from database. After some debugging, I found the solution for it. Let see it.


Code fragment creating problem
System.out.println("read action");
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
user=(User) session.load(pack.User.class, user.getId());
session.getTransaction().commit();
System.out.println(user);

Exception
1038 [http-8080-2] ERROR org.hibernate.LazyInitializationException - could not initialize proxy - no Session
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:132)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:174)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
at pack.User_$$_javassist_0.toString(User_$$_javassist_0.java)
at java.lang.String.valueOf(Unknown Source)
at java.io.PrintStream.println(Unknown Source)
at org.apache.tomcat.util.log.SystemLogHandler.println(SystemLogHandler.java:242)
at MyAction.read(MyAction.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:440)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:279)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:163)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:249)
at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:148)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:128)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:148)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:128)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:468)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)

Solution :
System.out.println("read action");
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
user=(User) session.load(pack.User.class, user.getId());

System.out.println(user);
session.getTransaction().commit();

Use the entity before commit it. Here, hibernate is using lazy initializing strategy to load the data from database and I was committing the session without fetching data.

Hibernate - Using annotations based configuration



Hibrnate provides support for the annotations based mapping for the ORM(object relational mapping). You can use JPA annotations in hibernate to map the object to table. So , you don't require the *.hbm.xml file for the each entity to mapping in database. You can mix annotated persistent classes and classic hbm.cfg.xml declarations with the same SessionFactory.

You can however not declare a class several times (whether annotated or through hbm.xml). You cannot mix configuration strategies (hbm vs annotations) in an entity hierarchy either. Following annotaions are being used in the example;

@Entity declares the class as an entity (i.e. a persistent POJO class).
@Id declares the identifier property of this entity.
Other properties will be mapped by hibernate using convensions like column name, column type, table name etc.

Entity class
package domain;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Profile {
    private int id;
    private String name;
    private String email;
    private Date dateOfBirth;
    private long phone;

    public Profile() {

    }

    public Profile(int id, String name, String email, Date dateOfBirth,
            long phone) {
        super();
        this.id = id;
        this.name = name;
        this.email = email;
        this.dateOfBirth = dateOfBirth;
        this.phone = phone;
    }

    @Id
    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    public long getPhone() {
        return phone;
    }

    public void setPhone(long phone) {
        this.phone = phone;
    }
}

-----------------------------------------------------------------------------------------------------------------
<?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>
        <!-- Database connection settings -->
        <property name="connection.driver_class">org.h2.Driver</property>
        <property name="connection.url">jdbc:h2:~/test;TRACE_LEVEL_FILE=3</property>
        <property name="connection.username">sa</property>
        <property name="connection.password" />
        <property name="connection.pool_size">1</property>
        <property name="dialect">org.hibernate.dialect.H2Dialect</property>
        <property name="current_session_context_class">thread</property>
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto" >update</property>
        <mapping class="domain.Profile"/>
    </session-factory>
</hibernate-configuration>

--------------------------------------------------------------------------------------------------------------
import java.util.Calendar;
import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;

import domain.Profile;

public class Operations {
    public static void main(String[] args) {
        Session session = new AnnotationConfiguration().configure()
                .buildSessionFactory().openSession();
        session.beginTransaction();
        //create the date object to represent date, use calendar classs to do that
        Calendar date=Calendar.getInstance();
        date.set(19820220);
        Profile profile=new Profile(1,"hemraj","hemraj@domain.com",date.getTime(),983234923);
        session.save(profile);
        session.getTransaction().commit();
    }
}


Popular Posts