您的位置:首页 > 其它

Hibernate学习第一天 配置环境和helloworld

2012-11-12 15:55 429 查看
需要下载的东西

hibernate-annotations-3.4.0.ga.zip

hibernate-distribution-3.3.2.ga-dist.zip

slf4j-1.5.8.zip

参考文档

www.hibernate.org

hibernate-distribution-3.3.2.GA\documentation\manual\zh-CN\html_single\index.html

hibernate-annotations-3.4.0.GA\doc\reference\zh_cn\html_single\index.html

在windows-preferences-java-buildpath-add user libraries

需要的有 hibernate3.jar

lib下的 required下的所有包

和sl4j相对应版本的包 slf4j-nop-1.5.8.jar

和mysql的驱动jar

hibernate-annotation-3.0.4.ga/hibernate-annotation.jar

和lib下的ejb-persistions
和 hibernate-commons-annotation.jar

在mysql中建立对应的数据库表

简历hibernate配置文件 hibernate.cfg.xml

在hibernate文档中拷贝

<propertyname="connection.driver_class">com.mysql.jdbc.Driver</property>
<propertyname="connection.url">jdbc:mysql://localhost/hibernate</property>
<propertyname="connection.username">root</property>
<propertyname="connection.password">dongjialin</property>

连接数据库

<propertyname="dialect">org.hibernate.dialect.MySQLDialect</property>

Mysql的方言

<propertyname="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

create 可以自动创建数据库没有的表 update 数据库或者实体类改变可以自动生成新表 create-drop 关闭session后自动drop validate 插数据之前检查数据库中的表和文件是否能适应上

<!-- Drop and re-create the database schema on startup -->

<property name="hbm2ddl.auto">create</property>

不设置二级缓存

<!-- Echo all executed SQL to stdout -->
<propertyname="show_sql">true</property>

显示sql执行语言

如果一个实体类 Student.java

也需要在同一个包下建立一个 student.hbm.xml

<?xmlversion="1.0"?>
<!DOCTYPEhibernate-mapping
PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mappingpackage="edu.neusoft">
<classname="Student">
<idname="id"></id>
<propertyname="name"></property>
<propertyname="age"></property>
</class>
</hibernate-mapping>

Id主键 property属性名

如果实体类和表中的名字不一致 ,在class后加table=”” 数据库中表名

在property里加 column=””数据库中行名

然后在hibernate.cfg.xml的session-factory标签里加

<mappingresource="edu/neusoft/Student.hbm.xml"/>

主函数中写

Student s = new Student();//new一个实体类\
s.setId(1);
s.setName("s1");
s.setAge(23);
Configuration cfg=newConfiguration();//新建一个configuration
SessionFactory sf =cfg.configure().buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
session.close();
sf.close();

Annotations

建立一个新的实体类 Teacher和对应的数据库表

privateintid;
private String
name;
private String
title;

在类前加@Entity表明这是一个实体类

在主键get方法上@Id

在hibernate-cfg.xml中加

<mapping
class="edu.neusoft.Teacher"/>

注意是.

主方法中

Teacher t = new Teacher();
t.setId(1);
t.setName("name1");
t.setTitle("primary");
Configuration cfg =
new
AnnotationConfiguration();
SessionFactory sf =cfg.configure().buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(t);
session.getTransaction().commit();
session.close();
sf.close();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: