Hibernate 建项初探
首先建一个web project
导入Hibernate所需要的jar包,
.
+lib
antlr.jar
cglib.jar
asm.jar
asm-attrs.jars
commons-collections.jar
commons-logging.jar
ehcache.jar
hibernate3.jar
jta.jar
dom4j.jar
log4j.jar
这里我用的数据库是MySQL
然后创建所需要的Model,代码如下:
package com.xll.bean;public class UserModel implements java.io.Serializable{private static final long serialVersionUID = 1L;private int uuid; private String userId;private String userName;private int age;private String pwd;private String registerTime; public UserModel(){}//无参构造//setter and getter .....在model的同级目录下建立UserModel.hbm.xml映射文件
<?xml version="1.0"?><!DOCTYPE hibernate-mapping SYSTEM "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" ><hibernate-mapping><class name="com.xll.bean.UserModel" table="tbl_user" ><id name="uuid" column="uuid" ><generator column="userId" /><property name="userName" column="userName" /><property name="age" column="age" /><property name="registerTime" column="registerTime" /><property name="pwd" column="pwd" /></class></hibernate-mapping>
然后在src下配置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"><hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/mydb</property> <property name="connection.username">root</property> <property name="connection.password">123</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <mapping resource="com/xll/bean/UserModel.hbm.xml"/> </session-factory></hibernate-configuration>
编写测试类 Client.java
package com.xll.test;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import com.xll.bean.UserModel;public class Client {public static void main(String[] args) {UserModel um = new UserModel();um.setAge(11);um.setPwd("123123");um.setRegisterTime("2011-10-10");um.setUserId("432123");um.setUserName("xiaoliang");um.setUuid(6666);SessionFactory sf = new Configuration().configure().buildSessionFactory();Session s = null;Transaction t = null;try {s = sf.openSession();t = s.beginTransaction();s.save(um);t.commit();} catch (Exception e) {e.printStackTrace();t.rollback();} finally {s.close();}}}运行结果:
Hibernate: insert into tbl_user (userId, userName, age, registerTime, pwd, uuid) values (?, ?, ?, ?, ?, ?)//配置中的show_sql