67,513
社区成员
发帖
与我相关
我的任务
分享
package mypackage.domain;
import java.util.Date;
public class Event {
private Long id;
private String title;
private Date date;
public Event() {}
public Long getId() {
return id;
}
private void setId(Long id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
<hibernate-mapping package="mypackage.domain">
<class name="Event" table="EVENTS">
</class>
</hibernate-mapping
>
<class name="Event" table="EVENTS">
<id name="id" column="EVENT_ID">
<generator class="native"/>
</id>
</class>
<property name="date" type="timestamp" column="EVENT_DATE"/>
<property name="title" column="EVENT_TITLE"/>
<hibernate-configuration>
<session-factory>
<!-- 驱动 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 数据库地址 -->
<property name="hibernate.connection.url">jdbc:mysql:///test</property>
<property name="connection.username">sa</property>
<property name="connection.password">sa</property>
<!-- SQL 方言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 打印SQL执行语句 -->
<property name="show_sql">true</property>
<!-- 以下是映射文件列表 -->
<mapping resource="mypackage/domain/Event.hbm.xml"/>
</session-factory>
</hibernate-configuration
>
package mypackage.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// configuration实例的configure()方法会调用classpath根目录下的hibernate.cfg.xml文件
return new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex) {
ex.printStackTrace();
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
//开启事务
session.beginTransaction();
//创建并设置实体类
Event theEvent = new Event();
theEvent.setTitle("event1");
theEvent.setDate(new Date());
//持久化实体类
session.save(theEvent);
//提交事务
session.getTransaction().commit();
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List result = session.createQuery("from Event").list();
session.getTransaction().commit();
return result;