hibernate入门示例展示
程序员文章站
2024-01-24 11:26:58
...
有很长一段时间没有使用hibernate进行开发了,最近闲来无事,温习一下hibernate开发。搭建hibernate开发环境,下载hibernate3.3.2的jar包。所用数据库是mysql。
在使用hibernate3.3.2中要注意以下问题:
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/helpers/NOPLoggerFactory
这是由于hibernate-distribution-3.3.2.GA中的带有的slf4j-api-1.5.8和最新下载的slf4j-1.6.1不兼容造成的,下载一个slf4j-1.5.8包就解决问题了。
一、导入hibernate使用的Jar包
见jar.jpg的图
二、配置hibernate的映射文件
三、创建User的bean
部分代码如下:
并配置User的映射文件:
四 、导入数据库生成表结构的工具类
还有一个工具类如下:
五、测试类
在使用hibernate3.3.2中要注意以下问题:
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/helpers/NOPLoggerFactory
这是由于hibernate-distribution-3.3.2.GA中的带有的slf4j-api-1.5.8和最新下载的slf4j-1.6.1不兼容造成的,下载一个slf4j-1.5.8包就解决问题了。
一、导入hibernate使用的Jar包
见jar.jpg的图
二、配置hibernate的映射文件
<?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> <property name="hibernate.format_sql">true</property> <property name="hibernate.show_sql">true</property> <property name="connection.url"> jdbc:mysql://localhost:3306/test </property> <property name="connection.username">root</property> <property name="connection.password">sa</property> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <mapping resource="org/outman/domain/User.hbm.xml" /> </session-factory> </hibernate-configuration>
三、创建User的bean
部分代码如下:
public class User implements java.io.Serializable { private static final long serialVersionUID = 1L; private Integer id; private String name; private String pwd; private Boolean verify; private Date registerDate; private BigDecimal salary; ...... }
并配置User的映射文件:
<?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"> <hibernate-mapping package="org.outman.domain"> <class name="User" table="t_user"> <!--id name="id" type="integer" column="_id"> <generator class="identity" /> </id--> <!-- Oracle --> <!--id name="id" type="integer" column="_id"> <generator class="sequence"> 如果不写,Hibernate建默认的sequence <param name="sequence">user_seq</param> </generator> </id--> <id name="id" type="integer" column="_id"> <!-- Hibernate根据方言来确定 identity、sequence、... --> <generator class="native"> <param name="sequence">user_seq</param> </generator> </id> <property name="name" type="string" column="_name" /> <property name="pwd" type="string" column="_pwd" /> <property name="verify" type="yes_no" column="_verify" /> <property name="registerDate" type="date" column="_register_date" /> <property name="salary" type="big_decimal" column="_salary" /> </class> </hibernate-mapping>
四 、导入数据库生成表结构的工具类
package org.outman.util; import org.hibernate.cfg.Configuration; import org.hibernate.tool.hbm2ddl.SchemaExport; public class ExportDB { public static void main(String[] args) { // 读取hibernate.cfg.xml文件 Configuration cfg = new Configuration().configure(); SchemaExport export = new SchemaExport(cfg); export.create(true, true); } }
还有一个工具类如下:
package org.outman.util; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static SessionFactory factory; private static Configuration conf; static { conf = new Configuration(); conf.configure(); factory = conf.buildSessionFactory(); } public static Session openSession() { return factory.openSession(); } }
五、测试类
package org.outman.test; import java.math.BigDecimal; import java.util.Date; import java.util.List; import junit.framework.TestCase; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.outman.domain.User; import org.outman.util.HibernateUtil; public class MyTest extends TestCase { public void testSaveUser() { // 调用 Hibernate API // 加载配置文件 Configuration conf = new Configuration(); // 按照默认的路径和文件名装载配置文件 conf.configure(); // hibernate.cfg.xml // conf.configure(File file); // conf.addClass(User.class); // 装载和User类对应的映射文件 // User.hbm.xml // 1 重量级的对象 // 2 线程安全的对象 SessionFactory factory = conf.buildSessionFactory(); // Session提供了ORM操作的接口 // 相当于JDBC的Connection Session session = null; Transaction tx = null; try { session = factory.openSession(); User user = new User(); user.setName("java"); user.setPwd("123456"); user.setVerify(false); user.setRegisterDate(new Date()); user.setSalary(new BigDecimal("12345.67")); tx = session.getTransaction(); tx.begin(); session.save(user); tx.commit(); } catch (HibernateException e) { e.printStackTrace(); tx.rollback(); } finally { session.close(); } } public void testDeleteUser() { Session session = HibernateUtil.openSession(); Transaction tx = session.getTransaction(); tx.begin(); User user = new User(); user.setId(8); session.delete(user); tx.commit(); session.close(); } public void testGetUser() { Session session = HibernateUtil.openSession(); // 延缓加载 // User user = (User) session.load(User.class, 9); User user = (User) session.get(User.class, 9); System.out.println("----------"); System.out.println(user.getName() + "," + user.getPwd()); session.close(); } public void testUpdateUser() { Session session = HibernateUtil.openSession(); Transaction tx = session.getTransaction(); tx.begin(); User user = new User(); user.setId(1); user.setName("java"); user.setPwd("88888888"); session.update(user); // session.saveOrUpdate(user); tx.commit(); session.close(); } @SuppressWarnings("unchecked") public void testQueryUser() { Session session = HibernateUtil.openSession(); // HQL Hibernate Query Language // SQL Query query = session.createQuery("from User u where u.name=?"); query.setParameter(0, "java"); // Iterator<User> it = query.iterate(); // while (it.hasNext()) { // User user = it.next(); // System.out.println(user.getName() + "," + user.getPwd()); // } List<User> userList = query.list(); for (User user : userList) { System.out.println(user.getName() + "," + user.getPwd()); } session.close(); } }