Hibernate初体验

鄙人不才,找工作的时候发现大家都要Java的SSH相关知识,于是开始恶补,摸索了好久,终于在hibernate上开始入门,这是入门的一个工程,本工程使用hibernate最新的4.6.7版本,废话不多说了,直接开始。
所需要的东西,
1. hibernate  http://hibernate.org/

点击此处下载最新版本的hibernate包,

上边这个链接是hibernate的相关工具在eclipse上的插件,可以协助创建hibernate的配置文件,以及映射文件。本文可以不用安装。
2. eclipse可以安装上hibernate的tool,以及有jdk,本人用的最新的jdk1.8.0_25版本
3. 本人用的数据库是最新版的5.6MySQL数据库。
演示问题是向数据库中存储事件,包括时间,以及事件标题,
1首先需要建立一个普通的Java项目即可,建立的目录结构如下所示:

将hibernate-release-4.3.7.Final\lib\required下的jar包拷贝到项目的lib目录里面,将数据库的驱动也拷贝到此目录,之后构建路径,将所有的包构建进去即可。完成环境的搭建。
2数据库端的建立SQL语句如下:
    
    
    
    
drop database if exists first;
create database first;
use first;
create table EVENTS(event_id int not null primary key auto_increment,
event_date date,
event_title varchar(100) default '');
建立的数据库名字叫做first,表名字叫做EVENTS(注意在windows平台下MYSQL数据库不区分大小写)
表中的字段包括event_id以及event_date,event_title,
3建立java类对应数据库表,所放路径见包名。
    
    
    
    
package org.hibernate.tutorial.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;
}
}
4.配置放到src根目录,名字叫做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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">786160313</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/first</property>
<property name="hibernate.connection.username">root</property>
<property name="current_session_context_class">thread</property>
<mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>
</session-factory>
</hibernate-configuration>
5.映射文件如下,和上述的Java类放到一起,名字是Event.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">
<!-- Generated 2014-11-18 10:19:49 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="org.hibernate.tutorial.domain.Event" table="EVENTS">
<id name="id">
<column name="EVENT_ID" />
<generator class="native" />
</id>
<property name="title">
<column name="EVENT_TITLE" />
</property>
<property name="date" type="timestamp">
<column name="EVENT_DATE" />
</property>
</class>
</hibernate-mapping>
6.日志配置文件
将解压目录hibernate-release-4.3.7.Final\project\etc下的log4j.properties放到项目的src根目录下即可。
7.开始使用,建立一个工具类,方便使用
    
    
    
    
package org.hibernate.tutorial.util;
 
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
 
public class HibernateUtil {
 
private static final SessionFactory sessionFactory = buildSessionFactory();
 
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
// return new Configuration().configure().buildSessionFactory(
// new StandardServiceRegistryBuilder().build() );
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
return configuration.buildSessionFactory(serviceRegistry);
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
 
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
 
}

8测试类
    
    
    
    
package org.hibernate.tutorial;
 
import org.hibernate.Session;
 
import java.util.*;
 
import org.hibernate.tutorial.domain.*;
import org.hibernate.tutorial.util.HibernateUtil;
 
public class EventManager {
 
public static void main(String[] args) {
EventManager mgr = new EventManager();
 
if (args[0].equals("store")) {
mgr.createAndStoreEvent("My Event", new Date());
}
else if (args[0].equals("list")) {
List events = mgr.listEvents();
for (int i = 0; i < events.size(); i++) {
Event theEvent = (Event) events.get(i);
System.out.println(
"Event: " + theEvent.getTitle() + " Time: " + theEvent.getDate()
);
}
}
 
HibernateUtil.getSessionFactory().close();
}
 
private void createAndStoreEvent(String title, Date theDate) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
 
Event theEvent = new Event();
theEvent.setTitle(title);
theEvent.setDate(theDate);
session.save(theEvent);
// long event_id = ((Event)(session.createQuery("from Event where title="+title).list().get(0))).getId();
 
session.getTransaction().commit();
//return event_id;
}
private List listEvents() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List result = session.createQuery("from Event").list();
session.getTransaction().commit();
return result;
}
 
}
9执行测试类之后数据库中的结果为
注意执行测试类的时候要给主函数一个参数,存储的时候是store,查询则是list,eclipse中给主函数赋值参数,右键项目,run as 里面的运行配置选项, 之后点击apply之后点击运行即可。


你可能感兴趣的:(java,eclipse,Hibernate,mysql)