hibernate——实例【myeclipse自带实例】

 1.首先创建一张表【database: test】

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.主要的src文件,其实myeclipse自动生成了绝大多数的文件,此处只要自己添加一个就好了~!

   下面分析这些文件吧!

  1. package com.fox;
  2. /**
  3.  * AbstractUser entity provides the base persistence definition of the User
  4.  * entity.
  5.  * 
  6.  * @author MyEclipse Persistence Tools
  7.  */
  8. public abstract class AbstractUser implements java.io.Serializable {
  9.     // Fields
  10.     private Integer id;
  11.     private String username;
  12.     private String password;
  13.     private String firstName;
  14.     private String lastName;
  15.     private Long dateCreated;
  16.     // Constructors
  17.     /** default constructor */
  18.     public AbstractUser() {
  19.     }
  20.     /** full constructor */
  21.     public AbstractUser(Integer id, String username, String password,
  22.             String firstName, String lastName, Long dateCreated) {
  23.         this.id = id;
  24.         this.username = username;
  25.         this.password = password;
  26.         this.firstName = firstName;
  27.         this.lastName = lastName;
  28.         this.dateCreated = dateCreated;
  29.     }
  30.     // Property accessors
  31.     public Integer getId() {
  32.         return this.id;
  33.     }
  34.     public void setId(Integer id) {
  35.         this.id = id;
  36.     }
  37.     public String getUsername() {
  38.         return this.username;
  39.     }
  40.     public void setUsername(String username) {
  41.         this.username = username;
  42.     }
  43.     public String getPassword() {
  44.         return this.password;
  45.     }
  46.     public void setPassword(String password) {
  47.         this.password = password;
  48.     }
  49.     public String getFirstName() {
  50.         return this.firstName;
  51.     }
  52.     public void setFirstName(String firstName) {
  53.         this.firstName = firstName;
  54.     }
  55.     public String getLastName() {
  56.         return this.lastName;
  57.     }
  58.     public void setLastName(String lastName) {
  59.         this.lastName = lastName;
  60.     }
  61.     public Long getDateCreated() {
  62.         return this.dateCreated;
  63.     }
  64.     public void setDateCreated(Long dateCreated) {
  65.         this.dateCreated = dateCreated;
  66.     }
  67. }

2.2 BaseHibernateDAO.java

 

  1. package com.fox;
  2. import org.hibernate.Session;
  3. /**
  4.  * Data access object (DAO) for domain model
  5.  * @author MyEclipse Persistence Tools
  6.  */
  7. public class BaseHibernateDAO implements IBaseHibernateDAO {
  8.     
  9.     public Session getSession() {
  10.         return HibernateSessionFactory.getSession();
  11.     }
  12.     
  13. }

2.3 HibernateExample.java 【这个是自己添加的】

 

  1. package com.fox;
  2. import org.hibernate.Transaction;
  3. public class HibernateExample {
  4.     /**
  5.      * @param args
  6.      */
  7.     public static void main(String[] args) {
  8.         // 1. Add the new user
  9.         addUser();
  10.         
  11.         // 2. Retrieve the user and print it
  12.         listUser();
  13.         
  14.         // 3. Change the user record and update it
  15.         changeUser();
  16.     }
  17.     
  18.     private static void addUser() {
  19.         // 1. Create user
  20.         User user = new User();
  21.         user.setId(1);
  22.         user.setUsername("jdoe");
  23.         user.setPassword("1234");
  24.         user.setFirstName("John");
  25.         user.setLastName("Doe");
  26.         user.setDateCreated(System.currentTimeMillis());
  27.         
  28.         // 2. Create DAO
  29.         UserDAO dao = new UserDAO();
  30.         
  31.         // 3. Start the transaction
  32.         Transaction tx = dao.getSession().beginTransaction();
  33.         
  34.         // 4. Add user
  35.         dao.save(user);
  36.         
  37.         // 5. Commit the transaction (write to database)
  38.         tx.commit();
  39.         
  40.         // 6. Close the session (cleanup connections)
  41.         dao.getSession().close();
  42.     }
  43.     
  44.     private static void listUser() {
  45.         // 1. Create DAO
  46.         UserDAO dao = new UserDAO();
  47.         
  48.         // 2. Find user by ID
  49.         User user = dao.findById(1);
  50.         
  51.         // 3. Print the user information out
  52.         printUser("Printing User, ", user);
  53.         
  54.         // 4. Close the session (cleanup connections)
  55.         dao.getSession().close();
  56.     }
  57.     
  58.     private static void changeUser() {
  59.         // 1. Create DAO
  60.         UserDAO dao = new UserDAO();
  61.         
  62.         // 2. Find user by ID
  63.         User user = dao.findById(1);
  64.         
  65.         // 3. Change user information
  66.         user.setUsername("jsmith");
  67.         user.setPassword("abcd");
  68.         user.setFirstName("Jane");
  69.         user.setLastName("Smith");
  70.         
  71.         // 4. Start the transaction
  72.         Transaction tx = dao.getSession().beginTransaction();
  73.         
  74.         // 5. Update the user record with the changes
  75.         dao.save(user);
  76.         
  77.         // 6. Commit the transaction (write to database)
  78.         tx.commit();
  79.         
  80.         // 7. Load the updated user from the database
  81.         User updatedUser = dao.findById(1);
  82.         
  83.         // 8. Print the updated user information out to confirm the changes
  84.         printUser("Printing Updated User, ", updatedUser);
  85.         
  86.         // 9. Close the session (cleanup connections)
  87.         dao.getSession().close();
  88.     }
  89.     
  90.     private static void printUser(String extraText, User user) {
  91.         System.out.println(extraText 
  92.                             + " User[Username: " 
  93.                             + user.getUsername() 
  94.                             + ", Password: " 
  95.                             + user.getPassword() 
  96.                             + ", First Name: " 
  97.                             + user.getFirstName() 
  98.                             + ", Last Name: " 
  99.                             + user.getLastName() + "]");
  100.     }
  101. }

2.4 HibernateSessionFactory.java

 

  1. package com.fox;
  2. import org.hibernate.HibernateException;
  3. import org.hibernate.Session;
  4. import org.hibernate.cfg.Configuration;
  5. /**
  6.  * Configures and provides access to Hibernate sessions, tied to the
  7.  * current thread of execution.  Follows the Thread Local Session
  8.  * pattern, see {@link http://hibernate.org/42.html }.
  9.  */
  10. public class HibernateSessionFactory {
  11.     /** 
  12.      * Location of hibernate.cfg.xml file.
  13.      * Location should be on the classpath as Hibernate uses  
  14.      * #resourceAsStream style lookup for its configuration file. 
  15.      * The default classpath location of the hibernate config file is 
  16.      * in the default package. Use #setConfigFile() to update 
  17.      * the location of the configuration file for the current session.   
  18.      */
  19.     private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
  20.     private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
  21.     private  static Configuration configuration = new Configuration();
  22.     private static org.hibernate.SessionFactory sessionFactory;
  23.     private static String configFile = CONFIG_FILE_LOCATION;
  24.     static {
  25.         try {
  26.             configuration.configure(configFile);
  27.             sessionFactory = configuration.buildSessionFactory();
  28.         } catch (Exception e) {
  29.             System.err
  30.                     .println("%%%% Error Creating SessionFactory %%%%");
  31.             e.printStackTrace();
  32.         }
  33.     }
  34.     private HibernateSessionFactory() {
  35.     }
  36.     
  37.     /**
  38.      * Returns the ThreadLocal Session instance.  Lazy initialize
  39.      * the <code>SessionFactory</code> if needed.
  40.      *
  41.      *  @return Session
  42.      *  @throws HibernateException
  43.      */
  44.     public static Session getSession() throws HibernateException {
  45.         Session session = (Session) threadLocal.get();
  46.         if (session == null || !session.isOpen()) {
  47.             if (sessionFactory == null) {
  48.                 rebuildSessionFactory();
  49.             }
  50.             session = (sessionFactory != null) ? sessionFactory.openSession()
  51.                     : null;
  52.             threadLocal.set(session);
  53.         }
  54.         return session;
  55.     }
  56.     /**
  57.      *  Rebuild hibernate session factory
  58.      *
  59.      */
  60.     public static void rebuildSessionFactory() {
  61.         try {
  62.             configuration.configure(configFile);
  63.             sessionFactory = configuration.buildSessionFactory();
  64.         } catch (Exception e) {
  65.             System.err
  66.                     .println("%%%% Error Creating SessionFactory %%%%");
  67.             e.printStackTrace();
  68.         }
  69.     }
  70.     /**
  71.      *  Close the single hibernate session instance.
  72.      *
  73.      *  @throws HibernateException
  74.      */
  75.     public static void closeSession() throws HibernateException {
  76.         Session session = (Session) threadLocal.get();
  77.         threadLocal.set(null);
  78.         if (session != null) {
  79.             session.close();
  80.         }
  81.     }
  82.     /**
  83.      *  return session factory
  84.      *
  85.      */
  86.     public static org.hibernate.SessionFactory getSessionFactory() {
  87.         return sessionFactory;
  88.     }
  89.     /**
  90.      *  return session factory
  91.      *
  92.      *  session factory will be rebuilded in the next call
  93.      */
  94.     public static void setConfigFile(String configFile) {
  95.         HibernateSessionFactory.configFile = configFile;
  96.         sessionFactory = null;
  97.     }
  98.     /**
  99.      *  return hibernate configuration
  100.      *
  101.      */
  102.     public static Configuration getConfiguration() {
  103.         return configuration;
  104.     }
  105. }

2.5 IBaseHibernateDAO.java

 

  1. package com.fox;
  2. import org.hibernate.Session;
  3. /**
  4.  * Data access interface for domain model
  5.  * @author MyEclipse Persistence Tools
  6.  */
  7. public interface IBaseHibernateDAO {
  8.     public Session getSession();
  9. }

2.6 User.java

 

  1. package com.fox;
  2. /**
  3.  * User entity.
  4.  * 
  5.  * @author MyEclipse Persistence Tools
  6.  */
  7. public class User extends AbstractUser implements java.io.Serializable {
  8.     // Constructors
  9.     /** default constructor */
  10.     public User() {
  11.     }
  12.     /** full constructor */
  13.     public User(Integer id, String username, String password, String firstName,
  14.             String lastName, Long dateCreated) {
  15.         super(id, username, password, firstName, lastName, dateCreated);
  16.     }
  17. }

2.7 UserDAO.java

 

  1. package com.fox;
  2. import java.util.List;
  3. import org.apache.commons.logging.Log;
  4. import org.apache.commons.logging.LogFactory;
  5. import org.hibernate.LockMode;
  6. import org.hibernate.Query;
  7. import org.hibernate.criterion.Example;
  8. /**
  9.  * A data access object (DAO) providing persistence and search support for User
  10.  * entities. Transaction control of the save(), update() and delete() operations
  11.  * can directly support Spring container-managed transactions or they can be
  12.  * augmented to handle user-managed Spring transactions. Each of these methods
  13.  * provides additional information for how to configure it for the desired type
  14.  * of transaction control.
  15.  * 
  16.  * @see com.fox.User
  17.  * @author MyEclipse Persistence Tools
  18.  */
  19. public class UserDAO extends BaseHibernateDAO {
  20.     private static final Log log = LogFactory.getLog(UserDAO.class);
  21.     // property constants
  22.     public static final String USERNAME = "username";
  23.     public static final String PASSWORD = "password";
  24.     public static final String FIRST_NAME = "firstName";
  25.     public static final String LAST_NAME = "lastName";
  26.     public static final String DATE_CREATED = "dateCreated";
  27.     public void save(User transientInstance) {
  28.         log.debug("saving User instance");
  29.         try {
  30.             getSession().save(transientInstance);
  31.             log.debug("save successful");
  32.         } catch (RuntimeException re) {
  33.             log.error("save failed", re);
  34.             throw re;
  35.         }
  36.     }
  37.     public void delete(User persistentInstance) {
  38.         log.debug("deleting User instance");
  39.         try {
  40.             getSession().delete(persistentInstance);
  41.             log.debug("delete successful");
  42.         } catch (RuntimeException re) {
  43.             log.error("delete failed", re);
  44.             throw re;
  45.         }
  46.     }
  47.     public User findById(java.lang.Integer id) {
  48.         log.debug("getting User instance with id: " + id);
  49.         try {
  50.             User instance = (User) getSession().get("com.fox.User", id);
  51.             return instance;
  52.         } catch (RuntimeException re) {
  53.             log.error("get failed", re);
  54.             throw re;
  55.         }
  56.     }
  57.     public List findByExample(User instance) {
  58.         log.debug("finding User instance by example");
  59.         try {
  60.             List results = getSession().createCriteria("com.fox.User").add(
  61.                     Example.create(instance)).list();
  62.             log.debug("find by example successful, result size: "
  63.                     + results.size());
  64.             return results;
  65.         } catch (RuntimeException re) {
  66.             log.error("find by example failed", re);
  67.             throw re;
  68.         }
  69.     }
  70.     public List findByProperty(String propertyName, Object value) {
  71.         log.debug("finding User instance with property: " + propertyName
  72.                 + ", value: " + value);
  73.         try {
  74.             String queryString = "from User as model where model."
  75.                     + propertyName + "= ?";
  76.             Query queryObject = getSession().createQuery(queryString);
  77.             queryObject.setParameter(0, value);
  78.             return queryObject.list();
  79.         } catch (RuntimeException re) {
  80.             log.error("find by property name failed", re);
  81.             throw re;
  82.         }
  83.     }
  84.     public List findByUsername(Object username) {
  85.         return findByProperty(USERNAME, username);
  86.     }
  87.     public List findByPassword(Object password) {
  88.         return findByProperty(PASSWORD, password);
  89.     }
  90.     public List findByFirstName(Object firstName) {
  91.         return findByProperty(FIRST_NAME, firstName);
  92.     }
  93.     public List findByLastName(Object lastName) {
  94.         return findByProperty(LAST_NAME, lastName);
  95.     }
  96.     public List findByDateCreated(Object dateCreated) {
  97.         return findByProperty(DATE_CREATED, dateCreated);
  98.     }
  99.     public List findAll() {
  100.         log.debug("finding all User instances");
  101.         try {
  102.             String queryString = "from User";
  103.             Query queryObject = getSession().createQuery(queryString);
  104.             return queryObject.list();
  105.         } catch (RuntimeException re) {
  106.             log.error("find all failed", re);
  107.             throw re;
  108.         }
  109.     }
  110.     public User merge(User detachedInstance) {
  111.         log.debug("merging User instance");
  112.         try {
  113.             User result = (User) getSession().merge(detachedInstance);
  114.             log.debug("merge successful");
  115.             return result;
  116.         } catch (RuntimeException re) {
  117.             log.error("merge failed", re);
  118.             throw re;
  119.         }
  120.     }
  121.     public void attachDirty(User instance) {
  122.         log.debug("attaching dirty User instance");
  123.         try {
  124.             getSession().saveOrUpdate(instance);
  125.             log.debug("attach successful");
  126.         } catch (RuntimeException re) {
  127.             log.error("attach failed", re);
  128.             throw re;
  129.         }
  130.     }
  131.     public void attachClean(User instance) {
  132.         log.debug("attaching clean User instance");
  133.         try {
  134.             getSession().lock(instance, LockMode.NONE);
  135.             log.debug("attach successful");
  136.         } catch (RuntimeException re) {
  137.             log.error("attach failed", re);
  138.             throw re;
  139.         }
  140.     }
  141. }

2.8 User.hbm.xml

 

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  4. <!-- 
  5.     Mapping file autogenerated by MyEclipse Persistence Tools
  6. -->
  7. <hibernate-mapping>
  8.     <class name="com.fox.User" table="user" catalog="test">
  9.         <id name="id" type="java.lang.Integer">
  10.             <column name="id" />
  11.             <generator class="assigned" />
  12.         </id>
  13.         <property name="username" type="java.lang.String">
  14.             <column name="username" length="64" not-null="true" />
  15.         </property>
  16.         <property name="password" type="java.lang.String">
  17.             <column name="password" length="64" not-null="true" />
  18.         </property>
  19.         <property name="firstName" type="java.lang.String">
  20.             <column name="first_name" length="128" not-null="true" />
  21.         </property>
  22.         <property name="lastName" type="java.lang.String">
  23.             <column name="last_name" length="128" not-null="true" />
  24.         </property>
  25.         <property name="dateCreated" type="java.lang.Long">
  26.             <column name="date_created" not-null="true" />
  27.         </property>
  28.     </class>
  29. </hibernate-mapping>

2.9 hibernate.cfg.xml

 

  1. <?xml version='1.0' encoding='UTF-8'?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3.           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4.           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
  5. <!-- Generated by MyEclipse Hibernate Tools.                   -->
  6. <hibernate-configuration>
  7.     <session-factory>
  8.         <property name="connection.username">root</property>
  9.         <property name="connection.url">
  10.             jdbc:mysql://localhost:3306/test
  11.         </property>
  12.         <property name="dialect">
  13.             org.hibernate.dialect.MySQLDialect
  14.         </property>
  15.         <property name="myeclipse.connection.profile">
  16.             hibernateStart
  17.         </property>
  18.         <property name="connection.password">fox</property>
  19.         <property name="connection.driver_class">
  20.             com.mysql.jdbc.Driver
  21.         </property>
  22.         <mapping resource="com/fox/User.hbm.xml" />
  23.     </session-factory>
  24. </hibernate-configuration>

    贴出来,目的就是——做个参考~!

 

 

 

 

 

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值