Hibernate 最简单例子

Hibernate 最简单例子

guoqiang-vip@hotmail.com

开发环境

Windows XP Pack 2

MyEclipse 5.5.1 GA

jdk1.5.0_07

Tomcat 5.0

MySQL Server 5.0

MySQL Tools for 5.0

 

开发代码

1 创建数据库,sql语句如下:

DROP TABLE IF EXISTS `test`.`user`;

CREATE TABLE  `test`.`user` (

  `id` int(10) unsigned NOT NULL auto_increment,

  `username` varchar(64) NOT NULL,

  `password` varchar(64) NOT NULL,

  `first_name` varchar(128) NOT NULL,

  `last_name` varchar(128) NOT NULL,

  `date_created` bigint(20) unsigned NOT NULL,

  PRIMARY KEY  (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

2 程序代码:

1hibernate.cfg.xml

package com.guoqiang.hibernate;

 

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.cfg.Configuration;

 

/**

 * Configures and provides access to Hibernate sessions, tied to the

 * current thread of execution.  Follows the Thread Local Session

 * pattern, see {@link http://hibernate.org/42.html }.

 */

public class HibernateSessionFactory {

 

    /**

     * Location of hibernate.cfg.xml file.

     * Location should be on the classpath as Hibernate uses 

     * #resourceAsStream style lookup for its configuration file.

     * The default classpath location of the hibernate config file is

     * in the default package. Use #setConfigFile() to update

     * the location of the configuration file for the current session.  

     */

    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";

    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

    private  static Configuration configuration = new Configuration();

    private static org.hibernate.SessionFactory sessionFactory;

    private static String configFile = CONFIG_FILE_LOCATION;

 

    static {

    try {

           configuration.configure(configFile);

           sessionFactory = configuration.buildSessionFactory();

        } catch (Exception e) {

           System.err

                  .println("%%%% Error Creating SessionFactory %%%%");

           e.printStackTrace();

       }

    }

    private HibernateSessionFactory() {

    }

   

    /**

     * Returns the ThreadLocal Session instance.  Lazy initialize

     * the <code>SessionFactory</code> if needed.

     *

     *  @return Session

     *  @throws HibernateException

     */

    public static Session getSession() throws HibernateException {

        Session session = (Session) threadLocal.get();

 

       if (session == null || !session.isOpen()) {

           if (sessionFactory == null) {

              rebuildSessionFactory();

           }

           session = (sessionFactory != null) ? sessionFactory.openSession()

                  : null;

           threadLocal.set(session);

       }

 

        return session;

    }

 

    /**

     *  Rebuild hibernate session factory

     *

     */

    public static void rebuildSessionFactory() {

       try {

           configuration.configure(configFile);

           sessionFactory = configuration.buildSessionFactory();

       } catch (Exception e) {

           System.err

                  .println("%%%% Error Creating SessionFactory %%%%");

           e.printStackTrace();

       }

    }

 

    /**

     *  Close the single hibernate session instance.

     *

     *  @throws HibernateException

     */

    public static void closeSession() throws HibernateException {

        Session session = (Session) threadLocal.get();

        threadLocal.set(null);

 

        if (session != null) {

            session.close();

        }

    }

 

    /**

     *  return session factory

     *

     */

    public static org.hibernate.SessionFactory getSessionFactory() {

       return sessionFactory;

    }

 

    /**

     *  return session factory

     *

     *  session factory will be rebuilded in the next call

     */

    public static void setConfigFile(String configFile) {

       HibernateSessionFactory.configFile = configFile;

       sessionFactory = null;

    }

 

    /**

     *  return hibernate configuration

     *

     */

    public static Configuration getConfiguration() {

       return configuration;

    }

 

}

 

2User.hbm.xml

<?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">

<!--

    Mapping file autogenerated by MyEclipse Persistence Tools

-->

<hibernate-mapping>

    <class name="com.guoqiang.hibernate.User" table="user" catalog="test">

        <id name="id" type="java.lang.Integer">

            <column name="id" />

            <generator class="assigned" />

        </id>

        <property name="username" type="java.lang.String">

            <column name="username" length="64" not-null="true" />

        </property>

        <property name="password" type="java.lang.String">

            <column name="password" length="64" not-null="true" />

        </property>

        <property name="firstName" type="java.lang.String">

            <column name="first_name" length="128" not-null="true" />

        </property>

        <property name="lastName" type="java.lang.String">

            <column name="last_name" length="128" not-null="true" />

        </property>

        <property name="dateCreated" type="java.lang.Long">

            <column name="date_created" not-null="true" />

        </property>

    </class>

</hibernate-mapping>

 

3AbstractUser.java

package com.guoqiang.hibernate;

 

/**

 * AbstractUser generated by MyEclipse Persistence Tools

 */

 

public abstract class AbstractUser implements java.io.Serializable {

 

    // Fields

 

    private Integer id;

 

    private String username;

 

    private String password;

 

    private String firstName;

 

    private String lastName;

 

    private Long dateCreated;

 

    // Constructors

 

    /** default constructor */

    public AbstractUser() {

    }

 

    /** full constructor */

    public AbstractUser(Integer id, String username, String password,

           String firstName, String lastName, Long dateCreated) {

       this.id = id;

       this.username = username;

       this.password = password;

       this.firstName = firstName;

       this.lastName = lastName;

       this.dateCreated = dateCreated;

    }

 

    // Property accessors

 

    public Integer getId() {

       return this.id;

    }

 

    public void setId(Integer id) {

       this.id = id;

    }

 

    public String getUsername() {

       return this.username;

    }

 

    public void setUsername(String username) {

       this.username = username;

    }

 

    public String getPassword() {

       return this.password;

    }

 

    public void setPassword(String password) {

       this.password = password;

    }

 

    public String getFirstName() {

       return this.firstName;

    }

 

    public void setFirstName(String firstName) {

       this.firstName = firstName;

    }

 

    public String getLastName() {

       return this.lastName;

    }

 

    public void setLastName(String lastName) {

       this.lastName = lastName;

    }

 

    public Long getDateCreated() {

       return this.dateCreated;

    }

 

    public void setDateCreated(Long dateCreated) {

       this.dateCreated = dateCreated;

    }

 

}

 

(4)User.java

package com.guoqiang.hibernate;

 

// Generated by MyEclipse Persistence Tools

 

/**

 * User generated by MyEclipse Persistence Tools

 */

public class User extends AbstractUser implements java.io.Serializable {

 

    // Constructors

 

    /** default constructor */

    public User() {

    }

 

    /** full constructor */

    public User(Integer id, String username, String password, String firstName,

           String lastName, Long dateCreated) {

       super(id, username, password, firstName, lastName, dateCreated);

    }

 

}

 

5DemoHibernateTest.java

package com.guoqiang.hibernate;

 

import org.hibernate.Transaction;

 

public class DemoHibernateTest {

 

    /**

     * @param args

     */

    public static void main(String[] args) {

       // TODO Auto-generated method stub

       addUser();

       listUser();

       changeUser();

    }

 

    private static void printUser(String extraText, User user) {

       System.out.println(extraText

              + "User[Username: "

              + user.getUsername()

              + ", Password:"

              + user.getPassword()

              + ",First Name: "

              + user.getFirstName()

              + ",Last Name: "

              + user.getLastName()

              + "]");

    }

 

    private static void addUser() {

       // Create user

       User user = new User();

       user.setId(1);

       user.setUsername("guoqiang");

       user.setFirstName("guo");

       user.setLastName("qiang");

       user.setPassword("guoqiang");

       user.setDateCreated(System.currentTimeMillis());

       // Create DAO

       UserDAO dao = new UserDAO();

       // Start the transaction

       Transaction tx = dao.getSession().beginTransaction();

       // Add user

       dao.save(user);

       // Commit the transaction

       tx.commit();

       // Close the session

       dao.getSession().close();

 

    }

 

    private static void listUser() {

       UserDAO dao = new UserDAO();

       User user = dao.findById(1);

       printUser("Pringting User, ", user);

       dao.getSession().close();

    }

 

    private static void changeUser() {

       UserDAO dao = new UserDAO();

       User user = dao.findById(1);

       user.setUsername("test");

       user.setPassword("test");

       user.setFirstName("demo");

       user.setLastName("demo");

 

       Transaction tx = dao.getSession().beginTransaction();

       // Add user

       dao.save(user);

       // Commit the transaction

       tx.commit();

 

       User updateUser = dao.findById(1);

       printUser("Pringting Updated User, ", updateUser);

       dao.getSession().close();

    }

 

}

 

运行结果如下:

Pringting User, User[Username: guoqiang, Password:guoqiang,First Name: guo,Last Name: qiang]

Pringting Updated User, User[Username: test, Password:test,First Name: demo,Last Name: demo]

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

log4j:WARN Please initialize the log4j system properly.

 

存在问题和解决

问题1hibernate.cfg.xml文件找不到 如下:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

log4j:WARN Please initialize the log4j system properly.

org.hibernate.HibernateException: /hibernate.cfg.xml not found

    at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)

    at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1287)

    at org.hibernate.cfg.Configuration.configure(Configuration.java:1309)

    at org.hibernate.cfg.Configuration.configure(Configuration.java:1296)

    at com.hibernate.DemoHibernateTest.main(DemoHibernateTest.java:15)

解决:1 Create a Java project时,一定要选Project layout中的Create separate source and output foldedrs 解决找不到hibernate.cfg.xml

     2 src下在创建log4j.properties 解决log4j:WARN

内容为:

log4j.rootLogger=debug, A1 , R

log4j.appender.A1=org.apache.log4j.ConsoleAppender

log4j.appender.A1.layout=org.apache.log4j.PatternLayout

log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m -(:%L)%n

 

log4j.appender.R=org.apache.log4j.RollingFileAppender

log4j.appender.R.File=D:/workspace/DemoHibernate/HibernateDemoLog.log

log4j.appender.R.MaxFileSize=100KB

log4j.appender.R.MaxBackupIndex=1

log4j.appender.R.layout=org.apache.log4j.PatternLayout

log4j.appender.R.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m -(:%L)%n

 

修改DemoHibernateTest.java如下:

public class DemoHibernateTest {

    private static Logger log =Logger.getLogger(DemoHibernateTest.class);

 

    /**

     * @param args

     */

    public static void main(String[] args) {

       // TODO Auto-generated method stub

         log.debug("------测试!----");

       //addUser();

       listUser();

       changeUser();

    }

//省略

}

运行就会在Console输出log,选中工程DemoHibernate刷新就会看到HibernateDemoLog.log 内容如下(节选):

2007-06-16 11:25:33 [com.guoqiang.hibernate.DemoHibernateTest]-[DEBUG] ------测试!---- -(:14)

//省略

2007-06-16 11:41:31 [org.hibernate.impl.SessionImpl]-[DEBUG] after transaction completion -(:417)

Pringting Updated User, User[Username: test, Password:test,First Name: demo,Last Name: demo]//输出内容!!!!

2007-06-16 11:41:31 [org.hibernate.impl.SessionImpl]-[DEBUG] closing session -(:268)

2007-06-16 11:41:31 [org.hibernate.jdbc.ConnectionManager]-[DEBUG] connection already null in cleanup : no action -(:369)

 

参考资料

1 Introduction to Hibernate Tutorial

http://www.myeclipseide.com/images/tutorials/quickstarts/introduction_to_hibernate/tutorial.html

2 《最简单的Log4j使用》

3 First Hibernate example

http://www.laliluna.de/download/first-hibernate-example-tutorialen.pdf 
posted @ 2007-06-16 11:49  深潭  阅读(6192)  评论(1编辑  收藏  举报