项目列表:
用hibernate的意义:
因为SQL语句不是面向对象的,写起来很麻烦。当向数据库存取数据,或删除数据等等操作时,可直接与hibernate打交道,运用面向对象来实现,不用写SQL语句
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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/user</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property> <!-- 自动建表语句 -->
<mapping resource="mypackage/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
分析:
(1)连接数据库
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/user</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
上面四句话都是进行数据库连接使用的,可以在下图configuration中进行配置,myeclipse会自动生成上述代码
(2)方言(dialect)
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
不同数据库之间的SQL语言还是会有差异,因此使用什么数据库时定义相应的方言,我这里使用的是MySQL数据库
(3)打印生成的sql语句
<property name="show_sql">true</property>
(4)让hibernate自动生成建表语句
<property name="hbm2ddl.auto">update</property>
student.java
package mypackage;
public class Student {
String name;
int age;
int id;
public Student(String n,int a,int i){
name=n;
age=a;
id=i;
}
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;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
student.hbm.xml
将student这个类与表对应起来
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="mypackage.Student" table="student" >
<id name="id" />
<property name="name" />
<property name="age" />
</class>
</hibernate-mapping>
table这个标签标示该类对应在数据库中的表名
<id>表示这是个主键
若Java中的属性名字与数据库表中列名名字相同,就不用再在column中说明
Test.java 测试类
public class Test {
public static void main(String[] args) {
Student s1=new Student("bobo",11,10006);
//Student s2=new Student("LiLi",22,10002);
//Student s3=new Student("Anno",23,10003);
Configuration cfg=new Configuration();
SessionFactory sf=cfg.configure().buildSessionFactory();
Session session=sf.openSession();
session.beginTransaction();
session.save(s1);
// session.save(s2);
//session.save(s3);
session.getTransaction().commit();
session.close();
sf.close();
}
}