Hibernate使软件适应不同的数据库易如反掌
对于一个通用型的软件来说,有的客户喜欢MySQL,有的客户则已经购买了Oracle,还有些客户已经习惯了SQLServer,因此软件要面对的后台数据库类型可能是多种多样的。如果为了让软件能适应各种数据库,而开发一连串针对不同数据库的软件版本,对于开发和维护都是一场噩梦,幸好我们有了Hibernate。下面我通过一个简单的小例子来表明Hibernate对于开发适应不同数据库的软件是多么的易如反掌。程序结构图
源代码
db.HibernateUtil
package
db;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.SessionFactory;
/** */ /**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html}.
*/
public class HibernateUtil {
/** *//**
* Location of hibernate.cfg.xml file.
* NOTICE: Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file. That
* is place the config file in a Java package - the default location
* is the default Java package.<br><br>
* Defaults: <br>
* <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml"</code>
* You can change location with setConfigFile method
* session will be rebuilded after change of config file
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal threadLocal = new ThreadLocal();
private static Configuration configuration = new Configuration();
private static SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
private HibernateUtil() {
}
/** *//**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getCurrentSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/** *//**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/** *//**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeCurrentSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/** *//**
* return session factory
*
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
/** *//**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateUtil.configFile = configFile;
sessionFactory = null;
}
/** *//**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
model.User
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.SessionFactory;
/** */ /**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html}.
*/
public class HibernateUtil {
/** *//**
* Location of hibernate.cfg.xml file.
* NOTICE: Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file. That
* is place the config file in a Java package - the default location
* is the default Java package.<br><br>
* Defaults: <br>
* <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml"</code>
* You can change location with setConfigFile method
* session will be rebuilded after change of config file
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal threadLocal = new ThreadLocal();
private static Configuration configuration = new Configuration();
private static SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
private HibernateUtil() {
}
/** *//**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getCurrentSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/** *//**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/** *//**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeCurrentSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/** *//**
* return session factory
*
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
/** *//**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateUtil.configFile = configFile;
sessionFactory = null;
}
/** *//**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
package
model;
public class User
{
private int id;
private String username;
private String password;
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
}
model.hbm.xml
public class User
{
private int id;
private String username;
private String password;
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
}
<?
xml version='1.0' encoding='UTF-8'
?>
<! DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
< hibernate-mapping >
< class name ="model.User" table ="user1" >
< id name ="id" >
< generator class ="identity" />
</ id >
< property name ="username" />
< property name ="password" />
</ class >
</ hibernate-mapping >
hibernate.cfg.xml
<! DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
< hibernate-mapping >
< class name ="model.User" table ="user1" >
< id name ="id" >
< generator class ="identity" />
</ id >
< property name ="username" />
< property name ="password" />
</ class >
</ hibernate-mapping >
<?
xml version='1.0' encoding='UTF-8'
?>
<! DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd" >
<!-- Generated by MyEclipse Hibernate Tools. -->
< hibernate-configuration >
< session-factory >
< property name ="dialect" > net.sf.hibernate.dialect.SQLServerDialect </ property >
< property name ="connection.url" > jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=login </ property >
< property name ="connection.username" > lzqdiy </ property >
< property name ="connection.password" > lzqdiy </ property >
< property name ="connection.driver_class" > com.microsoft.jdbc.sqlserver.SQLServerDriver </ property >
< property name ="myeclipse.connection.profile" > conn2 </ property >
< mapping resource ="model/model.hbm.xml" />
</ session-factory >
</ hibernate-configuration >
HibernateTest
<! DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd" >
<!-- Generated by MyEclipse Hibernate Tools. -->
< hibernate-configuration >
< session-factory >
< property name ="dialect" > net.sf.hibernate.dialect.SQLServerDialect </ property >
< property name ="connection.url" > jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=login </ property >
< property name ="connection.username" > lzqdiy </ property >
< property name ="connection.password" > lzqdiy </ property >
< property name ="connection.driver_class" > com.microsoft.jdbc.sqlserver.SQLServerDriver </ property >
< property name ="myeclipse.connection.profile" > conn2 </ property >
< mapping resource ="model/model.hbm.xml" />
</ session-factory >
</ hibernate-configuration >
import
java.util.List;
import model.User;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Query;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import db.HibernateUtil;
public class HibernateTest
{
/** *//**
* @param args
* @throws HibernateException
*/
public void insertUser() throws HibernateException
{
Session session = HibernateUtil.getCurrentSession();
Transaction tx = session.beginTransaction();
User user = new User();
user.setUsername("lzqdiy");
user.setPassword("lzqdiy");
session.save(user);
tx.commit();
HibernateUtil.closeCurrentSession();
}
public List<User> getUsers() throws HibernateException
{
Session session = HibernateUtil.getCurrentSession();
Transaction tx = session.beginTransaction();
String sql = "select u from User as u where u.username=:name";
Query query = session.createQuery(sql);
query.setString("name", "lzqdiy");
List<User> list = query.list();
tx.commit();
HibernateUtil.closeCurrentSession();
return list;
}
public static void main(String[] args) throws HibernateException
{
// TODO Auto-generated method stub
new HibernateTest().insertUser();
List<User> list = new HibernateTest().getUsers();
for (User user : list)
{
System.out.println(user.getUsername());
System.out.println(user.getPassword());
}
}
}
以上的程序使用的数据库是SQLServer2000,如果你想将数据库更换为MySQL,只需将hibernate.cfg.xml更改如下:
import model.User;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Query;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import db.HibernateUtil;
public class HibernateTest
{
/** *//**
* @param args
* @throws HibernateException
*/
public void insertUser() throws HibernateException
{
Session session = HibernateUtil.getCurrentSession();
Transaction tx = session.beginTransaction();
User user = new User();
user.setUsername("lzqdiy");
user.setPassword("lzqdiy");
session.save(user);
tx.commit();
HibernateUtil.closeCurrentSession();
}
public List<User> getUsers() throws HibernateException
{
Session session = HibernateUtil.getCurrentSession();
Transaction tx = session.beginTransaction();
String sql = "select u from User as u where u.username=:name";
Query query = session.createQuery(sql);
query.setString("name", "lzqdiy");
List<User> list = query.list();
tx.commit();
HibernateUtil.closeCurrentSession();
return list;
}
public static void main(String[] args) throws HibernateException
{
// TODO Auto-generated method stub
new HibernateTest().insertUser();
List<User> list = new HibernateTest().getUsers();
for (User user : list)
{
System.out.println(user.getUsername());
System.out.println(user.getPassword());
}
}
}
<?
xml version='1.0' encoding='UTF-8'
?>
<! DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd" >
<!-- Generated by MyEclipse Hibernate Tools. -->
< hibernate-configuration >
< session-factory >
< property name ="dialect" > net.sf.hibernate.dialect.MySQLDialect </ property >
< property name ="connection.url" > jdbc:mysql://localhost:3306/login </ property >
< property name ="connection.username" > root </ property >
< property name ="connection.password" > root </ property >
< property name ="connection.driver_class" > com.mysql.jdbc.Driver </ property >
< property name ="myeclipse.connection.profile" > myconn </ property >
< mapping resource ="model/model.hbm.xml" />
</ session-factory >
</ hibernate-configuration >
其他的源程序代码都不需要更改,是不是很爽,呵呵。
<! DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd" >
<!-- Generated by MyEclipse Hibernate Tools. -->
< hibernate-configuration >
< session-factory >
< property name ="dialect" > net.sf.hibernate.dialect.MySQLDialect </ property >
< property name ="connection.url" > jdbc:mysql://localhost:3306/login </ property >
< property name ="connection.username" > root </ property >
< property name ="connection.password" > root </ property >
< property name ="connection.driver_class" > com.mysql.jdbc.Driver </ property >
< property name ="myeclipse.connection.profile" > myconn </ property >
< mapping resource ="model/model.hbm.xml" />
</ session-factory >
</ hibernate-configuration >
|
|