Hello Hibernate3.2
一、Hibernate?
Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用。
「物件/关系对应」(Object/Relational Mapping)的解决方案,简写为ORM,简单的说就是将 Java 中的物件与物件关系,映射至关系数据库中的表格与表格之间的关系
二、利用MyEclipse 8.0 搭建Hibernate环境
1.new 一个java project
2.add capabilities
生成的配置文件:
<?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="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/hibernate
</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="myeclipse.connection.profile">mysql</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
三、利用MyEclipse 8.0生成映射文件和对应的POJO
简单的Java对象(Plain Old Java Objects)实际就是普通JavaBean
利用DB Browser 反向生成映射文件和对应的POJO Hibernate reverse engineering
生成的映射文件:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.linys.model.User" table="user" >
<id name="userName" type="java.lang.String">
<column name="userName" length="50" />
</id>
<property name="password" type="java.lang.String">
<column name="password" length="50" />
</property>
</class>
</hibernate-mapping>
其中
classs--指定映射的Object类
name --指定Object的信息:类名
table--指定映射的表Relation
name --指定Object的的主键属性
type--指定类中属性的数据类型
column--该属性对应的字段
property--指定Object类中非主键的属性
四、进行简单的插入操作
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.linys.model.User;
public class TestUser {
public static void main(String[] args) {
User user=new User();
user.setPassword("admin");
user.setUserName("admin");
//注册配置文件hibernate.cfg.xml,默认存放在src下
Configuration cf=new Configuration().configure();
//创建SessionFactory
SessionFactory sf=cf.buildSessionFactory();
//打开Session,取得与数据库对话的权利
Session session=sf.openSession();
//由于要对数据库进行插入insert操作我们引入了事务Transaction
Transaction ts=session.beginTransaction();
ts.begin();
//插入数据
session.save(user);
ts.commit();
//关闭session和sessionFactory
session.close();
sf.close();
}
}
五、一些注意点:
1.配置文件
左边是对应数据库的配置信息
Properties : 可以配置hibernate的一些属性,如果配置的是show_sql 就是展示sql语句的属性
Mappings: 映射文件的配置,可以直接将配置文件拖到该区域就可生成,对应的配置
2. 利用DB browser时,可以直接将表拖入到Mappings区域,开启reverse engineering