<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>crazyjava</groupId>
<artifactId>hibernateTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>hibernateTest</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!-- mysql的依赖包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- Hibernate的依赖包 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
<?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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<mapping class="org.crazyit.app.domain.News"/>
<mapping class="org.crazyit.app.domain.Person"/>
<mapping class="org.crazyit.app.domain.Address"/>
</session-factory>
</hibernate-configuration>
第二个是hbm文件 hibernate.cfg.xml
下面是hibernatutils
package lee; import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.service.*;
import org.hibernate.boot.registry.*; public class HibernateUtil
{
public static final SessionFactory sessionFactory; static
{
try
{
// 使用默认的hibernate.cfg.xml配置文件创建Configuration实例
Configuration cfg = new Configuration()
.configure();
// 以Configuration实例来创建SessionFactory实例
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
}
catch (Throwable ex)
{
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
} // ThreadLocal可以隔离多个线程的数据共享,因此不再需要对线程同步
public static final ThreadLocal<Session> session
= new ThreadLocal<Session>(); public static Session currentSession()
throws HibernateException
{
Session s = session.get();
// 如果该线程还没有Session,则创建一个新的Session
if (s == null)
{
s = sessionFactory.openSession();
// 将获得的Session变量存储在ThreadLocal变量session里
session.set(s);
}
return s;
} public static void closeSession()
throws HibernateException
{
Session s = session.get();
if (s != null)
s.close();
session.set(null);
}
}
下面是实体类和测试类
package lee; import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.service.*;
import org.hibernate.boot.registry.*;
import org.crazyit.app.domain.*; public class NewsManager
{
public static void main(String[] args)
throws Exception
{
// 实例化Configuration,
Configuration conf = new Configuration()
// 不带参数的configure()方法默认加载hibernate.cfg.xml文件,
// 如果传入abc.xml作为参数,则不再加载hibernate.cfg.xml,改为加载abc.xml
.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(conf.getProperties()).build();
// 以Configuration实例创建SessionFactory实例
SessionFactory sf = conf.buildSessionFactory(serviceRegistry);
// 创建Session
Session sess = sf.openSession();
// 开始事务
Transaction tx = sess.beginTransaction();
// 创建消息对象
News n = new News();
// 设置消息标题和消息内容
n.setTitle("疯狂Java联盟成立了");
n.setContent("疯狂Java联盟成立了,"
+ "网站地址http://www.crazyit.org");
// 保存消息
sess.save(n);
// 提交事务
tx.commit();
// 关闭Session
sess.close();
sf.close();
}
}
package org.crazyit.app.domain; import javax.persistence.*; @Entity
@Table(name="news_inf")
public class News
{
// 消息类的标识属性
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
// 消息标题
private String title;
// 消息内容
private String content; // id的setter和getter方法
public void setId(Integer id)
{
this.id = id;
}
public Integer getId()
{
return this.id;
} // title的setter和getter方法
public void setTitle(String title)
{
this.title = title;
}
public String getTitle()
{
return this.title;
} // content的setter和getter方法
public void setContent(String content)
{
this.content = content;
}
public String getContent()
{
return this.content;
}
}
package org.crazyit.app.domain; import lee.HibernateUtil; import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; public class TestQuery {
private Session session = null;
private Transaction tx = null; @Before
public void before() {
session = HibernateUtil.currentSession();
tx = session.beginTransaction();
}
@Test
public void test1() {
Person p = new Person();
// 设置Person的name为crazyit字符串
p.setName("crazyit");
p.setAge(21);
// 创建一个瞬态的Address对象
Address a = new Address("广州天河");
// 设置Person和Address之间的关联关系
// p.setAddress(a);
a.setPerson(p);
// 持久化Address对象
session.persist(a);
// 持久化Person对象
session.save(p);
} @After
public void after() {
tx.commit();
HibernateUtil.closeSession();
}
}
使用junit更好