首页 > 代码库 > hibernate开发流程
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(); }
hibernate开发流程
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。