您的位置:首页 > 编程语言 > Java开发

hibernate入门基础知识和demo

2016-09-04 00:00 411 查看
摘要: Hibernate 入门基础知识

一:开发hibernate的步骤
(1)1包的引入: hibernate-distribution-3.6.0.Final
hibernate3.jar 核心jar包



hibernate-jpa-2.0-api-1.0.0.Final.jar
2配置映射文件

<?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="test">
------name  对应实体类对象  table ---对应数据库中的数据表
<class name="roletable" table="roletab">
<id name="roleID" column="id">
<generator class="native" />
</id>
<!-- -非主键映射 -->
<property name="roleText" column="rolename"></property>
</class>
</hibernate-mapping>

3 配置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:///test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="test/role.hbm.xml"/>
</session-factory>
</hibernate-configuration>

4 编写代码

public static void HibernateDemo01(){
roletable roel=new roletable();
try{
roel.setRoleID(UUID.randomUUID().toString());
roel.setRoleText("mc龙九");
//创建配置文件
Configuration config=new Configuration();
//自动加载配置
config.configure();
//创建sessionFactory工厂
SessionFactory sf =config.buildSessionFactory();
//打开session会话
Session session = sf.openSession();
//开启事物
Transaction tran = session.beginTransaction();
//保存
session.save(roel);
//提交事物
tran.commit();
session.close();
System.out.println("插入成功");
}
catch(Exception ex){
ex.printStackTrace();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Hibernate Java