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自动生成了绝大多数的文件,此处只要自己添加一个就好了~!
下面分析这些文件吧!
- package com.fox;
- /**
- * AbstractUser entity provides the base persistence definition of the User
- * entity.
- *
- * @author 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;
- }
- }
2.2 BaseHibernateDAO.java
- package com.fox;
- import org.hibernate.Session;
- /**
- * Data access object (DAO) for domain model
- * @author MyEclipse Persistence Tools
- */
- public class BaseHibernateDAO implements IBaseHibernateDAO {
- public Session getSession() {
- return HibernateSessionFactory.getSession();
- }
- }
2.3 HibernateExample.java 【这个是自己添加的】
- package com.fox;
- import org.hibernate.Transaction;
- public class HibernateExample {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // 1. Add the new user
- addUser();
- // 2. Retrieve the user and print it
- listUser();
- // 3. Change the user record and update it
- changeUser();
- }
- private static void addUser() {
- // 1. Create user
- User user = new User();
- user.setId(1);
- user.setUsername("jdoe");
- user.setPassword("1234");
- user.setFirstName("John");
- user.setLastName("Doe");
- user.setDateCreated(System.currentTimeMillis());
- // 2. Create DAO
- UserDAO dao = new UserDAO();
- // 3. Start the transaction
- Transaction tx = dao.getSession().beginTransaction();
- // 4. Add user
- dao.save(user);
- // 5. Commit the transaction (write to database)
- tx.commit();
- // 6. Close the session (cleanup connections)
- dao.getSession().close();
- }
- private static void listUser() {
- // 1. Create DAO
- UserDAO dao = new UserDAO();
- // 2. Find user by ID
- User user = dao.findById(1);
- // 3. Print the user information out
- printUser("Printing User, ", user);
- // 4. Close the session (cleanup connections)
- dao.getSession().close();
- }
- private static void changeUser() {
- // 1. Create DAO
- UserDAO dao = new UserDAO();
- // 2. Find user by ID
- User user = dao.findById(1);
- // 3. Change user information
- user.setUsername("jsmith");
- user.setPassword("abcd");
- user.setFirstName("Jane");
- user.setLastName("Smith");
- // 4. Start the transaction
- Transaction tx = dao.getSession().beginTransaction();
- // 5. Update the user record with the changes
- dao.save(user);
- // 6. Commit the transaction (write to database)
- tx.commit();
- // 7. Load the updated user from the database
- User updatedUser = dao.findById(1);
- // 8. Print the updated user information out to confirm the changes
- printUser("Printing Updated User, ", updatedUser);
- // 9. Close the session (cleanup connections)
- dao.getSession().close();
- }
- 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() + "]");
- }
- }
2.4 HibernateSessionFactory.java
- package com.fox;
- 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;
- }
- }
2.5 IBaseHibernateDAO.java
- package com.fox;
- import org.hibernate.Session;
- /**
- * Data access interface for domain model
- * @author MyEclipse Persistence Tools
- */
- public interface IBaseHibernateDAO {
- public Session getSession();
- }
2.6 User.java
- package com.fox;
- /**
- * User entity.
- *
- * @author 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);
- }
- }
2.7 UserDAO.java
- package com.fox;
- import java.util.List;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.hibernate.LockMode;
- import org.hibernate.Query;
- import org.hibernate.criterion.Example;
- /**
- * A data access object (DAO) providing persistence and search support for User
- * entities. Transaction control of the save(), update() and delete() operations
- * can directly support Spring container-managed transactions or they can be
- * augmented to handle user-managed Spring transactions. Each of these methods
- * provides additional information for how to configure it for the desired type
- * of transaction control.
- *
- * @see com.fox.User
- * @author MyEclipse Persistence Tools
- */
- public class UserDAO extends BaseHibernateDAO {
- private static final Log log = LogFactory.getLog(UserDAO.class);
- // property constants
- public static final String USERNAME = "username";
- public static final String PASSWORD = "password";
- public static final String FIRST_NAME = "firstName";
- public static final String LAST_NAME = "lastName";
- public static final String DATE_CREATED = "dateCreated";
- public void save(User transientInstance) {
- log.debug("saving User instance");
- try {
- getSession().save(transientInstance);
- log.debug("save successful");
- } catch (RuntimeException re) {
- log.error("save failed", re);
- throw re;
- }
- }
- public void delete(User persistentInstance) {
- log.debug("deleting User instance");
- try {
- getSession().delete(persistentInstance);
- log.debug("delete successful");
- } catch (RuntimeException re) {
- log.error("delete failed", re);
- throw re;
- }
- }
- public User findById(java.lang.Integer id) {
- log.debug("getting User instance with id: " + id);
- try {
- User instance = (User) getSession().get("com.fox.User", id);
- return instance;
- } catch (RuntimeException re) {
- log.error("get failed", re);
- throw re;
- }
- }
- public List findByExample(User instance) {
- log.debug("finding User instance by example");
- try {
- List results = getSession().createCriteria("com.fox.User").add(
- Example.create(instance)).list();
- log.debug("find by example successful, result size: "
- + results.size());
- return results;
- } catch (RuntimeException re) {
- log.error("find by example failed", re);
- throw re;
- }
- }
- public List findByProperty(String propertyName, Object value) {
- log.debug("finding User instance with property: " + propertyName
- + ", value: " + value);
- try {
- String queryString = "from User as model where model."
- + propertyName + "= ?";
- Query queryObject = getSession().createQuery(queryString);
- queryObject.setParameter(0, value);
- return queryObject.list();
- } catch (RuntimeException re) {
- log.error("find by property name failed", re);
- throw re;
- }
- }
- public List findByUsername(Object username) {
- return findByProperty(USERNAME, username);
- }
- public List findByPassword(Object password) {
- return findByProperty(PASSWORD, password);
- }
- public List findByFirstName(Object firstName) {
- return findByProperty(FIRST_NAME, firstName);
- }
- public List findByLastName(Object lastName) {
- return findByProperty(LAST_NAME, lastName);
- }
- public List findByDateCreated(Object dateCreated) {
- return findByProperty(DATE_CREATED, dateCreated);
- }
- public List findAll() {
- log.debug("finding all User instances");
- try {
- String queryString = "from User";
- Query queryObject = getSession().createQuery(queryString);
- return queryObject.list();
- } catch (RuntimeException re) {
- log.error("find all failed", re);
- throw re;
- }
- }
- public User merge(User detachedInstance) {
- log.debug("merging User instance");
- try {
- User result = (User) getSession().merge(detachedInstance);
- log.debug("merge successful");
- return result;
- } catch (RuntimeException re) {
- log.error("merge failed", re);
- throw re;
- }
- }
- public void attachDirty(User instance) {
- log.debug("attaching dirty User instance");
- try {
- getSession().saveOrUpdate(instance);
- log.debug("attach successful");
- } catch (RuntimeException re) {
- log.error("attach failed", re);
- throw re;
- }
- }
- public void attachClean(User instance) {
- log.debug("attaching clean User instance");
- try {
- getSession().lock(instance, LockMode.NONE);
- log.debug("attach successful");
- } catch (RuntimeException re) {
- log.error("attach failed", re);
- throw re;
- }
- }
- }
2.8 User.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.fox.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>
2.9 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">
- <!-- Generated by MyEclipse Hibernate Tools. -->
- <hibernate-configuration>
- <session-factory>
- <property name="connection.username">root</property>
- <property name="connection.url">
- jdbc:mysql://localhost:3306/test
- </property>
- <property name="dialect">
- org.hibernate.dialect.MySQLDialect
- </property>
- <property name="myeclipse.connection.profile">
- hibernateStart
- </property>
- <property name="connection.password">fox</property>
- <property name="connection.driver_class">
- com.mysql.jdbc.Driver
- </property>
- <mapping resource="com/fox/User.hbm.xml" />
- </session-factory>
- </hibernate-configuration>
贴出来,目的就是——做个参考~!