第一步,我们需要写一个POJO类:User.java
package cn.itcast.hibernate.domain; import java.util.Date; public class User { private int id; private String name; private Date birthday; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }为了使这个javabean具有持久化操作的能力,我们需要在当前包下添加一个映射文件User.hbm.xml:
<?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 package="cn.itcast.hibernate.domain"> <class name="User" table="tb_User"> <id name="id"> <generator class="native"/> </id> <property name="name" /> <property name="birthday" /> </class> </hibernate-mapping>
<?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="connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="connection.url"> jdbc:mysql://localhost:3306/test </property> <property name="connection.username">sa</property> <property name="connection.password">123456</property> <property name="hbm2ddl.auto">create</property> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <mapping resource="cn/itcast/hibernate/domain/User.hbm.xml" /> </session-factory> </hibernate-configuration>
package cn.itcast.hibernate; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import cn.itcast.hibernate.domain.User; public class Base { public static void main(String[] args) { Configuration cfg = new Configuration(); //生成一个Configuration对象 cfg.configure(); //调用configure()方法加载映射文件 SessionFactory sf = cfg.buildSessionFactory(); //产生一个SessionFactory Session s = sf.openSession(); //开启session Transaction tx = s.beginTransaction(); //开启事务 User user = new User(); user.setBirthday(new Date()); user.setName("name"); s.save(user); //把user对象保存在session中 tx.commit(); //提交事务 s.close(); //关闭session System.out.println("end"); } }
需要用到的jar包:
原文地址:http://blog.csdn.net/u010800530/article/details/38947689