概要:对hibernate开发准备工作做个总结,主要介绍下开发前的准备 和简单的helloworld
步骤:
1.eclipse 以及安装好对应的hibernate tools插件:
kepler版本的update site:
http://download.jboss.org/jbosstools/updates/stable/kepler/
安装过程如图:
筛选一下,安装hibernate tools
2.新建Java工程,将下载好的hibernate的lib\required目录下的jar包
添加到buildpath:有三种方式
- 添加userlib
- 通过maven构建
- 直接在工程目录下新建lib目录把jar包复制过来添加到buildpath
3.添加数据库驱动,同添加hibernate必须jar包,本次使用的是MySQL5
以上几步相当于把基本开发环境搭好了,接下来进入helloworld阶段
- 在src下新建hibernate配置文件,通过hibernatetools插件:
- 在hibernate.hbm.xml配置文件中配置基本信息:
- 编写实体类,并生成映射文件:
package com.song.hibernate; import java.util.Date; public class User { private int id; private String uname; private Date birth; public User() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public String toString() { return "User [id=" + id + ", uname=" + uname + ", birth=" + birth + "]"; } public User(int id, String uname, Date birth) { this.id = id; this.uname = uname; this.birth = birth; } }
生成的映射文件User.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 2016-1-13 21:18:09 by Hibernate Tools 3.4.0.CR1 --> <hibernate-mapping> <class name="com.song.hibernate.User" table="USER"> <id name="id" type="int"> <column name="ID" /> <generator class="assigned" /> </id> <property name="uname" type="java.lang.String"> <column name="UNAME" /> </property> <property name="birth" type="java.util.Date"> <column name="BIRTH" /> </property> </class> </hibernate-mapping>
- 在配置文件中配置映射文件:
- 调用hibernate API测试:
package com.song.test; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.song.hibernate.User; public class TestHibernate { private Configuration config; private ServiceRegistry serviceRegistry; private SessionFactory sessionFactory; private Session session; private Transaction transaction; @Before public void init(){ config = new Configuration().configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); sessionFactory = config.buildSessionFactory(serviceRegistry); session = sessionFactory.openSession(); transaction = session.getTransaction(); transaction.begin(); } @Test public void testSave(){ User u = new User(1, "老李", new Date()); session.save(u); } @After public void distroy(){ transaction.commit(); session.close(); } }
hibernate 实现的helloworld到此为止