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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} |
I really enjoy the blog article.Much thanks again.
ReplyDeletego langaunage training
azure training
java training