Hibernate HelloWorld
Hibernate版本_hibernate-release-4.3.8.Final
下载地址http://hibernate.org/
1.新建JavaWeb项目
2.添加所需要的jar包
将hibernate-release-4.3.8.Final\lib\required下的所有文件添加到build path中即可
文件列表如下:
antlr-2.7.7.jar dom4j-1.6.1.jar hibernate-commons-annotations-4.0.5.Final.jar hibernate-core-4.3.8.Final.jar hibernate-jpa-2.1-api-1.0.0.Final.jar jandex-1.1.0.Final.jar javassist-3.18.1-GA.jar jboss-logging-3.1.3.GA.jar jboss-logging-annotations-1.2.0.Beta1.jar jboss-transaction-api_1.2_spec-1.0.0.Final.jar
3.编写配置文件hibernate.cfg.xml
在src目录下新建文件hibernate.cfg.xml
<?xml version=‘1.0‘ encoding=‘utf-8‘?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/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/hibernate</property> <property name="connection.username">root</property> <property name="connection.password">mysql</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.internal.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">update</property> <property name="javax.persistence.validation.mode">none</property> <mapping class="com.ssh.vo.User"/> </session-factory> </hibernate-configuration>
4.创建实体类
1 /**----------------------------------------------------------+ 2 + PGM-ID : User.java 3 + Author : H.Liu 4 + Date : 2015年3月21日 下午5:47:04 5 + Function: 通过注解进行映射 6 + 7 +-----------------------------------------------------------*/ 8 package com.ssh.vo; 9 10 import java.io.Serializable; 11 12 import javax.persistence.Column; 13 import javax.persistence.Entity; 14 import javax.persistence.GeneratedValue; 15 import javax.persistence.Id; 16 import javax.persistence.Table; 17 18 @Entity 19 @Table(name="user") 20 public class User implements Serializable { 21 22 //@GeneratedValue主键生成策略由hibernate自己决定 23 @Id@GeneratedValue 24 private int id; 25 private String password; 26 @Column(name="username") 27 private String username; 28 29 public User(){ 30 31 } 32 33 public User(String username,String password) { 34 this.username = username; 35 this.password = password; 36 } 37 38 public User(int id, String password, String username) { 39 super(); 40 this.id = id; 41 this.password = password; 42 this.username = username; 43 } 44 45 public int getId() { 46 return id; 47 } 48 49 public String getPassword() { 50 return password; 51 } 52 53 public String getUsername() { 54 return username; 55 } 56 57 public void setId(int id) { 58 this.id = id; 59 } 60 61 public void setPassword(String password) { 62 this.password = password; 63 } 64 65 public void setUsername(String username) { 66 this.username = username; 67 } 68 69 }
5.编写数据操作类
/**----------------------------------------------------------+ + PGM-ID : UserDaoImpl.java + Author : H.Liu + Date : 2015年3月22日 上午11:50:26 + Function: + +-----------------------------------------------------------*/ package com.ssh.dao; import java.io.Serializable; import java.util.Iterator; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import com.ssh.util.HibernateUtil; import com.ssh.vo.User; public class UserDaoImpl { // 向数据库的添加记录 public int add(User user){ SessionFactory sessionFactory = HibernateUtil.getSessionFactory();//获得工厂类 Session session = sessionFactory.openSession();//取得session Transaction tx = null;//定义事务 try{ tx = session.beginTransaction(); Serializable i = session.save(user); System.out.println(i); tx.commit();//提交 } catch (HibernateException e){ if(tx!=null) tx.rollback(); e.printStackTrace(); } finally{ session.close(); } return 0; } // 获得表中所有记录 public void list(){ SessionFactory sessionFactory = HibernateUtil.getSessionFactory();//获得工厂类 Session session = sessionFactory.openSession();//取得session Transaction tx = null;//定义事务 try{ tx = session.beginTransaction(); //通过HQL进行查询 /** List<?> users = session.createQuery("select new User(u.id, u.username, u.password) from com.ssh.vo.User u").list(); */ SQLQuery query = session.createSQLQuery("select id,username,password from user"); query.addEntity(User.class); List<?> users = query.list(); User user = null; Iterator<?> iterator =users.iterator(); while(iterator.hasNext()){ user= (User) iterator.next(); System.out.println("| " +user.getId() + "|" + user.getUsername() +"|" + user.getPassword() + " |"); } tx.commit();//提交 } catch (HibernateException e){ if(tx!=null) tx.rollback(); e.printStackTrace(); } finally{ session.close(); sessionFactory.close(); } } //更新表中的数据 public void update(User user){ SessionFactory sessionFactory = HibernateUtil.getSessionFactory();//获得工厂类 Session session = sessionFactory.openSession();//取得session Transaction tx = null;//定义事务 try{ tx = session.beginTransaction(); session.update(user); tx.commit();//提交 } catch (HibernateException e){ if(tx!=null) tx.rollback(); e.printStackTrace(); } finally{ session.close(); sessionFactory.close(); } } //删除表中的数据 public void delete(User user){ SessionFactory sessionFactory = HibernateUtil.getSessionFactory();//获得工厂类 Session session = sessionFactory.openSession();//取得session Transaction tx = null;//定义事务 try{ tx = session.beginTransaction(); session.delete(user); tx.commit();//提交 } catch (HibernateException e){ if(tx!=null) tx.rollback(); e.printStackTrace(); } finally{ session.close(); sessionFactory.close(); } } }
/**----------------------------------------------------------+ + PGM-ID : HibernateUtil.java + Author : H.Liu + Date : 2015年3月21日 下午5:54:53 + Function: 取得SessionFactory + +-----------------------------------------------------------*/ package com.ssh.util; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { Configuration cfg = new Configuration().configure(); StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(cfg.getProperties()).build(); SessionFactory sessionFactory = cfg.buildSessionFactory(serviceRegistry); return sessionFactory; } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }
6.编写测试类
/**----------------------------------------------------------+ + PGM-ID : UserManager.java + Author : H.Liu + Date : 2015年3月21日 下午5:53:15 + Function: + +-----------------------------------------------------------*/ package com.ssh.dao; import com.ssh.vo.User; public class UserManager { public static void main(String[] args) { UserDaoImpl userDaoImpl = new UserDaoImpl(); User user = new User("sa", "sa"); userDaoImpl.add(user); userDaoImpl.list(); userDaoImpl.update(new User(1, "ss", "ss")); userDaoImpl.delete(new User(1, "ss", "ss")); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。