
Hibernate里面,应该自己构造会话工厂,用静态方法或者变量保存自己的会话。
如:
import org.hibernate.HibernateException
import org.hibernate.Session
import org.hibernate.cfg.Configuration
/**
* 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 HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "/com/sxws/chis/object/hibernate/hibernate.cfg.xml"
private static final ThreadLocal<Session>threadLocal = new ThreadLocal<Session>()
private static Configuration configuration = new Configuration()
private static org.hibernate.SessionFactory sessionFactory
private static String configFile = CONFIG_FILE_LOCATION
static {
try {
configuration.configure(configFile)
sessionFactory = configuration.buildSessionFactory()
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%")
e.printStackTrace()
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code>if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() 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 closeSession() throws HibernateException {
Session session = (Session) threadLocal.get()
threadLocal.set(null)
if (session != null) {
session.close()
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory
}
/**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile
sessionFactory = null
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration
}
}
方法/步骤首先,我们把hibernate最基本的数据库连接,使用mysql。
见一个java工程,见一个包名为book, 在book的包下加一个java类Book.java,其代码如下: package book
public class Book { private Integer idprivate String nameprivate
String writerpublic Integer get hibernate最基本的数据库连接,使用mysql。
见一个java工程,见一个包名为“book”
然后在在book的包下加一个java类Book.java,其代码如下:
package book public class Book {private Integer id private
String name private String writer public Integer getId() {
return id }public void setId(Integer id) {this.id = id
}public String getName() {return name }public void
setName(String name) {this.name = name }public String
getWriter() {return writer }public void setWriter(String
writer) {this.writer = writer }}
然后在book包下建一个book.hbm.xml,其代码如下:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="book"default-lazy="false">
<class name="Book"> <id name="id"> <generator
class="increment"/> </id> <property name="name"
></property> <property name="writer"
></property> </class> </hibernate-mapping>
温馨提示:下图仅供欣赏,不作为教学。
这个事与数据库里面的字段名形成映射关系,自己在mysql建立book表时与之对应,id是自增长的,
然后在工程的根目录下建一个hibernate.cfg.xml.其代码如下:<?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>
<property
name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost/mydb</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property
name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property> <!--
<property
name="hbm2ddl.auto">${hibernate.hbm2ddl.auto}</property>-->
<!-- <property
name="current_session_context_class">thread</property>-->
<mapping resource="book/Book.hbm.xml" />
</session-factory> </hibernate-configuration>
温馨提示:下图仅供欣赏,不作为教学。
这是连接mysql数据库的,用户名和密码改为你mysql数据库的
<property name="show_sql">true</property>这是在后台打印sql语句
<mapping resource="book/Book.hbm.xml" />这是找到映射文件。
温馨提示:下图仅供欣赏,不作为教学。
然后些个测试类:代码如下:
package test import org.hibernate.Session import
org.hibernate.SessionFactory import org.hibernate.Transaction
import org.hibernate.cfg.Configuration import book.Book public
class MainTest {/*** @param args*/public static void
main(String[] args) {try {Configuration cfg=new
Configuration()。configure();SessionFactory
sf=cfg.buildSessionFactory();Session session = sf.openSession();
Transaction ts=session.beginTransaction();Book b=new Book();
b.setName("hibernate");b.setWriter("div");session.save(b);//
Book b=(Book) session.get(Book.class,1);// if(b!=null){//
b.setName("xujun");// System.out.println("书名为:"+b.getName());//
System.out.println("作者为:"+b.getWriter());// session.delete(b);//
}ts.commit();session.close();sf.close();} catch
(Exception e) {e.printStackTrace();}}}
mysql表的字段如下:
把数据库建好后就可以测试。对了,关键的还没有说,还得把antlr.jar,cglib.jar,asm.jar,asm-attrs.jar,commons-colletions.jar,commons-logging.jar,ehcache.jar,
jta.jar,dom4.jar,log4.jar,hibernate3.jar引入到lib目录下
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)