1:创建maven工程,引入hibernate需要的依赖
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.6.5.Final</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-nop</artifactId> <version>1.6.4</version> </dependency> <!-- 添加javassist --> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.11.0.GA</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency>
2:持久化一个类
package com.nerd.entity; import java.util.Date; public class Event { private int id; private Date date; private String title; public Date getDate() { return date; } public int getId() { return id; } public String getTitle() { return title; } public void setDate(Date date) { this.date = date; } public void setId(int id) { this.id = id; } public void setTitle(String title) { this.title = title; } }
3:hibernate需要怎么去存储和加载持久化类的对象,这时我们要搞一个映射文件(该文件和实体类放在同一目录下面)
<?xml version="1.0" encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > <hibernate-mapping> <class name="com.nerd.entity.Event" table="events"> <id name="id" type="int" column="EVENT_ID"> <generator class="native" /> </id> <property name="date" type="timestamp" column="EVENT_DATE" /> <property name="title" /> </class> </hibernate-mapping>
4:hibernate配置(放在resource目录下面)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://127.0.0.1:3306/db_hibe?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true</property> <property name="connection.username">root</property> <property name="connection.password">1234</property> <property name="javax.persistence.validation.mode">none</property> <property name="connection.pool_size">1</property> <property name="dialect">org.hibernate.dialect.SQLServerDialect</property> <property name="current_session_context_class">thread</property> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <property name="show_sql">true</property> <!-- <property name="format_sql">true</property> --> <property name="hbm2ddl.auto">create</property> <property name="hbm2ddl.auto">update</property> <mapping resource="com/nerd/entity/Event.hbm.xml"/> <mapping resource="com/nerd/entity/Person.hbm.xml"/> </session-factory> </hibernate-configuration>
5:启动和辅助类
package com.nerd.util; import org.apache.log4j.Logger; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory; private static final Logger LOGGER = Logger.getLogger(HibernateUtil.class); static{ try { LOGGER.debug("HibernateUti.static - loading cofig"); sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory(); LOGGER.debug("HibernateUtil.static - end"); } catch (Throwable ex) { LOGGER.error("HibernateUti error : ExceptionInInitializerError"); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getsSessionFactory(){ return sessionFactory; } }
package com.nerd.test; import java.util.Date; import java.util.List; import org.hibernate.classic.Session; import com.nerd.entity.Event; import com.nerd.util.HibernateUtil; public class EventManger { public static void main(String[] args) { EventManger mgr = new EventManger(); if(args[0].equals("insert")){ mgr.createAndStoreEvent("my event", new Date()); }else if(args[0].equals("list")){ @SuppressWarnings("rawtypes") List list = mgr.listEvents(); for(int i=0;i<list.size();i++){ Event theEvent = (Event)list.get(i); System.out.println("Event "+theEvent.getTitle()+"date "+theEvent.getDate()); } } HibernateUtil.getsSessionFactory().close(); } private void createAndStoreEvent(String title,Date date){ Session session = HibernateUtil.getsSessionFactory().getCurrentSession(); session.beginTransaction(); Event event = new Event(); event.setDate(date); event.setTitle(title); session.save(event); session.getTransaction().commit(); } @SuppressWarnings("rawtypes") private List listEvents(){ Session session = HibernateUtil.getsSessionFactory().getCurrentSession(); session.beginTransaction(); List list = session.createQuery("from Event").list(); session.getTransaction().commit(); return list; } }
这样一个简单的hibernate实例就完成了。
时间: 2024-11-08 22:28:54