标签:
Hibernate常用API:
1Configuration:
负责加载主配置文件信息,同时也加载映射关系文件信息。
2SessionFactory
负责创建Session对象。
3Session
数据库会话,负责增删改查操作。
4Transaction
负责事物控制
5Query
负责执行特殊查询
1新建java项目,加入导入jar包,直接导入myeclipse自带的hibernate library即可。另外,mysql jdbc的连接jar。
2entity类:
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; } }
3user的配置文件,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"> <id name="id"> <generator class="native" /> </id> <property name="name"/> <property name="birthday" /> </class> </hibernate-mapping>
4hibernate配置文件hibernate.cfg.xml
<!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="connection.url">jdbc:mysql:///test</property> <property name="connection.username">root</property> <property name="connection.password"></property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">create</property> <mapping resource="cn/itcast/hibernate/domain/User.hbm.xml"/> </session-factory>
</hibernate-configuration>
注意
<property name="hbm2ddl.auto">create</property>这个配置信息
配置了这个,数据库才能根据hibernate配置,自动创建表。
5Base
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 configuration = new Configuration();
configuration.configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
User user = new User();
user.setId(0);
user.setBirthday(new Date());
user.setName("A");
session.save(user);
tx.commit();
session.close();
System.out.println("end");
}
}
6测试:
工程目录:
标签:
原文地址:http://www.cnblogs.com/rixiang/p/5165266.html