hibernate开发流程
开发流程,注意:每个hibernate版本在集成的时候是不太一样的。本次使用的是hibernate-distribution-3.6.10.Final-dist
一、开发流程
1)在数据库中创建表,代码如下:
CREATE TABLE USER( id INT PRIMARY KEY AUTO_INCREMENT, uName VARCHAR(50) NOT NULL, uGender CHAR(2), uBirthday DATE);
2)在工程中创建实体类
public class User { private int id; private String uName; private String uGender; private Date uBirthday; public User() { // TODO Auto-generated constructor stub } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getuName() { return uName; } public void setuName(String uName) { this.uName = uName; } public String getuGender() { return uGender; } public void setuGender(String uGender) { this.uGender = uGender; } public Date getuBirthday() { return uBirthday; } public void setuBirthday(Date uBirthday) { this.uBirthday = uBirthday; }
3)创建对象和表的映射文件,*.hbm.xml。User.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.huitong.entity"> <class name="User" table="user"> <id name="id" column="id"> <generator class="native"/> </id> <property name="uName" column="uName"></property> <property name="uGender" column="uGender"></property> <property name="uBirthday" column="uBirthday"></property> </class> </hibernate-mapping>
4)hibernate的配置文件,放在src/目录下。hibernate.cfg.xml.
包含两部分
- 数据库连接配置
- 加载映射文件
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/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:///day17?useSSL=true</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <property name="hibernate.show_sql">true</property> <!-- 加载映射文件 --> <mapping resource="com/huitong/entity/User.hbm.xml"/> </session-factory> </hibernate-configuration>
小技巧:在myeclipse中要将多个jar文件配置到classpath中:
<1>首先点中第一个jar包
<2>shift+点击最后一个jar文件,选中所有jar文件
5)简单测试
public void fun1(){ User user = new User(); user.setuName("good"); user.setuBirthday(new Date()); Configuration configuration = new Configuration(); configuration.configure(); SessionFactory sf = configuration.buildSessionFactory(); Session session = sf.openSession(); Transaction bt = session.beginTransaction(); session.save(user); bt.commit(); session.close(); sf.close(); }
5)当有多个配置文件时,使用include进行包含
<include file="com/baidu/action/AdminConfig.xml"></include>
学习过程中,难免出错。如果您在阅读过程中遇到不太明白,或者有疑问。欢迎指正...联系邮箱crazyCodeLove@163.com
如果觉得有用,想赞助一下请移步赞助页面:赞助一下