写hibernate程序必需的:
hibernate.cfg.xml文件
- <!DOCTYPE hibernate-configuration PUBLIC
- "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
- <hibernate-configuration>
- <session-factory name="foo">
- <property name="hibernate.connection.url">
- jdbc:mysql://localhost/hibernate_fir
- </property>
- <property name="hibernate.connection.driver_class">
- com.mysql.jdbc.Driver
- </property>
- <property name="hibernate.connection.username">root</property>
- <property name="hibernate.connection.password">
- chx/1988
- </property>
- <property name="hibernate.dialect">
- org.hibernate.dialect.MySQLDialect
- </property>
- <property name="hibernate.show_sql">true</property>
- <mapping resource="cn/xteam/obj/User.hbm.xml" />
- </session-factory>
- </hibernate-configuration>
这个文件主要设置和数据库链接相关的东西,这里以MySQL为例。
<mapping resource="cn/xteam/obj/User.hbm.xml" />这一行是映射实体类的
下面是导出数据库的一个类。
- package cn.xteam.obj;
- import org.hibernate.cfg.Configuration;
- import org.hibernate.tool.hbm2ddl.SchemaExport;
- public class ExportDB {
- /**
- * @param args
- */
- public static void main(String[] args) {
- Configuration cfg = new Configuration().configure();
- SchemaExport export = new SchemaExport(cfg);
- export.create(true, true);
- }
- }
要让它创建出表的话,还要有个实体类和一个与实体类相关的配置文件:
配置文件如下:
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">
- <hibernate-mapping>
- <class name="cn.xteam.obj.User">
- <id name = "id">
- <generator class="uuid"/>
- </id>
- <property name="name"/>
- <property name="password" />
- </class>
- </hibernate-mapping>
OK了!再建个实体类,里面包含配置文件中相关属性即可:
比如这里可以用下面这个类做实体类:
- package cn.xteam.obj;
- public class User {
- private String id;
- private String name;
- private String password;
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- }
用下面这个类测试:
- package cn.xteam.obj;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- public class Client {
- /**
- * @param args
- */
- public static void main(String[] args) {
- Configuration cfg = new Configuration().configure();
- SessionFactory sf = cfg.buildSessionFactory();
- Session session = null;
- try{
- session = sf.openSession();
- session.beginTransaction();
- User user = new User();
- user.setName("neil");
- user.setPassword("123456");
- session.save(user);
- session.getTransaction().commit();
- }catch(Exception e){
- session.getTransaction().rollback();
- }finally {
- if(session != null){
- if(session.isOpen()){
- session.close();
- }
- }
- }
- }
- }