Wednesday, June 4, 2014

Get Database/Connection details from hibernate session with out entity mangaer


As many of us dont know that we can get the database metadata information from hibernate session, below sample code will help us to get the db metadata information.

ConnetionInfo.java class which will implement the hibernate jdbc work interface and override the execute method with connection object as argument, this connection object we will be getting from session of hibernate.

import java.sql.Connection;
import java.sql.SQLException;
import org.hibernate.jdbc.Work;
public class ConnectionInfo implements Work {
public String dataBaseUrl;
public String dataBaseProductName;
public String driverName;
public String username;
@Override
public void execute(Connection connection) throws SQLException {
dataBaseUrl = connection.getMetaData().getURL();
dataBaseProductName = connection.getMetaData().getDatabaseProductName();
driverName = connection.getMetaData().getDriverName();
username = connection.getMetaData().getUserName();
}
public String getDataBaseProductName() {
return dataBaseProductName;
}
public void setDataBaseProductName(String dataBaseProductName) {
this.dataBaseProductName = dataBaseProductName;
}
public String getDataBaseUrl() {
return dataBaseUrl;
}
public void setDataBaseUrl(String dataBaseUrl) {
this.dataBaseUrl = dataBaseUrl;
}
public String getDriverName() {
return driverName;
}
public void setDriverName(String driverName) {
this.driverName = driverName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}



hibernate connection test code to get the db metadata details

public class GetDbMetadata{
public static void main(String[] args) throws Exception {
Session session = sessionFactory.getCurrentSession();
ConnectionInfo connectionInfo = new ConnectionInfo();
session.doWork(connectionInfo);
log.info("DataBaseProductName : "+connectionInfo.getDataBaseProductName());
log.info("DataBaseUrl : "+connectionInfo.getDataBaseUrl());
log.info("DriverName : "+connectionInfo.getDriverName());
log.info("Username : "+connectionInfo.getUsername());
}
}


Related Posts:

1 comment: