import java.util.Date; public class User { private String id; private String name; private String password; private Date createTime; private Date expireTime; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getExpireTime() { return expireTime; } public void setExpireTime(Date expireTime) { this.expireTime = expireTime; } }
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping > <class name="com.bjpowernode.hibernate.User"> <id name="id"> <generator class="uuid"></generator> </id> <property name="name"></property> <property name="password"></property> <property name="createTime"></property> <property name="expireTime"></property> </class> </hibernate-mapping>
<!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.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">123456</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <mapping resource="com/bjpowernode/hibernate/User.hbm.xml"/> </session-factory> </hibernate-configuration>
import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class Test { /** * @param args */ public static void main(String[] args) { //讀取hibernate.hbm.xml文件 Configuration cfg=new Configuration().configure(); //創建SessionFactory至關於數據庫的一個鏡像 SessionFactory factory=cfg.buildSessionFactory(); //取得Session Session session=null; try { session=factory.openSession(); //開啓事務 session.beginTransaction(); User user=new User(); user.setName("李龍生"); user.setPassword("123456"); user.setCreateTime(new Date()); user.setExpireTime(new Date()); //保存User對象 session.save(user); //提交事務 session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); //回滾事務 session.getTransaction().rollback(); }finally{ //關閉Session if (session!=null) { if (session.isOpen()) { session.close(); } } } } }