您的位置:首页 > 其它

hibernate_初步学习,完整例子

2015-10-23 20:28 381 查看
基于mysql的数据库hibernate练习,初级Demo,仅供入门朋友参考,源码奉上。还有ssh2需要的所有jar包,分享给大家,希望大不会像我一样,被找jar包磨灭了学习的兴趣。

请提前在mysql里建好数据库。代码如下:

create database hibernate;
use hibernate;
create table student(
id int primary key,
name varchar(20),
age int);


student.java

package com.ftx.hibernate.model;

public class student {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

}
hibernate.cfg.xml数据库连接配置文件

<?xml version='1.0' encoding='utf-8'?>
<!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="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 数据库连接的URL -->
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<!-- 数据库连接用户名 -->
<property name="connection.username">root</property>
<!-- 数据库连接密码 -->
<property name="connection.password"></property>
<!-- Hibernate方言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 打印SQL语句 -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<!--  <property name="hbm2ddl.auto">update</property> -->

<mapping resource="com/ftx/hibernate/model/student.hbm.xml"/>

</session-factory>

</hibernate-configuration>
student.hbm.xml 映射文件

<?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 package="com.ftx.hibernate.model">
<class name="student" table="student" >
<id name="id"></id>
<property name="name"></property>
<property name="age"></property>
</class>
</hibernate-mapping>
StudentTest.java 数据写入

import java.nio.channels.SeekableByteChannel;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.ftx.hibernate.model.student;

public class StudentTest {
public static void main(String[] args) {
student s=new student();
s.setId(1);
s.setName("ftx1");
s.setAge(22);
Configuration cfg=new Configuration();
SessionFactory sf = cfg.configure().buildSessionFactory();
Session session=sf.openSession();//org.hibernate.Session;
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
session.close();
sf.close();
}
}


还有我平时ssh2的jar包整理,有很多人要资源积分,我这里免费,大家可以免费使用。加油1
http://download.csdn.net/detail/ftx2540993425/9207701
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: