Hibernate入门心得
开发阶段:
新建一个JAVA项目,目录结构如下:
将准备的jar包引入到项目中。
hibernate.cfg.xml:(Hibernate的配置文件,放在项目的src目录下):<?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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<!-- 设置驱动类 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 设置连接池默认个数 -->
<property name="connection.pool_size">20</property>
<!-- 设置JDBC URL -->
<property name="connection.url">jdbc:mysql://localhost:3306/book</property>
<!-- 设置数据库用户名 -->
<property name="connection.username">username</property>
<!-- 设置数据库用户密码 -->
<property name="connection.password">passwrod</property>
<!-- 设置SQL方言 -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 设置是否显示SQL语句 -->
<property name="show_sql">true</property>
<!-- 设置格式化SQL语句 -->
<property name="format_sql">true</property>
<property name="current_session_context_class">thread</property>
<mapping resource="com/sunflower/bean/Person.hbm.xml" />
</session-factory>
</hibernate-configuration>
这里配置的是MySQL数据库的驱动和连接,在开始的时候忘了加26行,结果调试的时候出错,得不到session,关于这个标签的使用,请参考如下文章:http://blog.sina.com.cn/s/blog_5ecfe46a0100e467.html 第28行是对象关系映射文件的配置.
Person.java:(人的实体类,对应到关系数据库中的blog表)package com.sunflower.bean;
import java.io.Serializable;
/**
* 博客用户的实体类
*
* @author hanyuan
* @time 2012-7-8 下午11:53:23
*/
public class Person implements Serializable {
private Integer id;
private String username;
private String password;
private String caption;
private String content;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
第12~16行中的属性对应到数据库中的blog表的字段,其中id是主键索引.
Person.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>
<!-- 设置实体类与数据库中表的对应关系 -->
<class name="com.sunflower.bean.Person" table="blog">
<id name="id" type="java.lang.Integer">
<column name="id"></column>
<!-- 将逐渐设置为自增 -->
<generator class="increment"></generator>
</id>
<property name="username" type="java.lang.String" not-null="true">
<column name="username"></column>
</property>
<property name="password" type="java.lang.String">
<column name="password"></column>
</property>
<property name="caption" typ
补充:软件开发 , Java ,