hibernate主方法调用

时间:2011-08-16 11:23:18

标签: java hibernate

我对Hibernate很新,只是想查询最初的基础知识。

我已经创建了我的Hibernate bean ......

package com.behaviour.chapter1;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class User {

    private int userId;
    private String firstName;

    @Id
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
}

我在那里配置了hibernate.cfg.xml和db连接。我的问题很简单,我如何从main方法实际调用它并在Hibernate3.6.6中使用它?我在网上学习了一个教程,但它适用于Hibernate3.2,它看起来有点不同。如果有人能告诉我一个非常简单的主方法调用这个bean,创建一个新用户(这将在这个表中创建一个用户),将不胜感激。此外 - 如果任何人有任何好的Hibernate教程链接,那将是伟大的:)

谢谢,

4 个答案:

答案 0 :(得分:4)

有几种方法可以做到这一点,这是设计选择的问题,实现这一目标的基本方法是从hibernate.cfg.xml文件创建会话工厂。确保文件可以位于类路径中。

使用下面的类,创建一个Session Factory对象,然后用于打开新的Session

  public class HibernateUtil 
  {
    private static final SessionFactory sessionFactory;

     static 
     {
      try 
        {
         // Create the SessionFactory from hibernate.cfg.xml
         sessionFactory = new Configuration().configure().buildSessionFactory();
         } 
         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;
      }
   }

现在要创建新用户,请执行以下操作:

public class DaoFactory
{
   public void create(Object obj)throws Exception
   {
     Session session = HibernateUtil.getSessionFactory().getCurrentSession();
     session.beginTransaction();
     session.save(obj);
     session.getTransaction().commit();
   }
}

主要

public static void main(String[] args)
{
  try
  {
   User user = new User();
   user.setFirstName("david99world");
   DaoFactory factory = new DaoFactory();
   factory.create(user);
  }
   catch(Exception ex)
  {
   ex.printStackTrace(System.out);
  }
}

修改

您的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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">none</property>

<mapping class="com.behaviour.chapter1.User"/>

</session-factory>
</hibernate-configuration>

答案 1 :(得分:1)

我假设你已经设置了你的persistence.xml。如果是这样,您可以使用以下Java代码。您必须用“JDBC设置数据和持久性单元”替换“...”。

private static final String PERSISTENCE_UNIT = "...";

final Map<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.jdbc.driver", "...");
properties.put("javax.persistence.jdbc.url", "...");
properties.put("javax.persistence.jdbc.user", "...");
properties.put("javax.persistence.jdbc.password", "...");

final EntityManagerFactory emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties);
final EntityManager em = emf.createEntityManager();

User user = new User();
user.setUserID(0);
user.setFirstName("David");

em.getTransaction().begin();
em.persist(user);
em.getTransaction().commit();

HTH

答案 2 :(得分:0)

答案 3 :(得分:0)

您是否需要Session对象来访问持久性单元。这些对象由SessionFactory对象提供。

检查the Hibernate reference guide