hibernate ——helloWorld程序(XML配置)

1、项目结构

hibernate  ——helloWorld程序(XML配置)

2、hibernate实现了Java类数据库表的映射(Map)

  先看一下Student的Java类和对应的数据库表

 package com.pt.hibernate;

 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;
}
}

Student.java

  创建Student表的SQL语句

 CREATE TABLE `student` (
`Id` int(20) NOT NULL,
`Name` varchar(20) DEFAULT NULL,
`Age` int(3) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

Creat table

3、通过student.xml配置文件,将Java类和数据库表关联起来

 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.pt.hibernate">
<class name="Student" table="student">
<id name="id" column="id" ></id>
<property name="name" column="name" ></property>
<property name="age" column="age" ></property>
</class>
</hibernate-mapping>

Student.xml

4、通过hibernate.cfg.xml配置文件,初始化hibernate所需要的信息

 <?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"> <hibernate-configuration> <session-factory> <!-- Database connection settings -->
<!-- <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:hsql://localhost/TestDB</property> --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/test?useUnicode=true&amp;characterEncoding=UTF-8</property>
<property name="connection.username">root</property>
<property name="connection.password"></property> <!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.MySQLInnoDBDialect
</property>
<property name="show_sql">true</property>
<mapping resource="com/pt/hibernate/Student.xml"/>
</session-factory> </hibernate-configuration>

hibernate.cfg.xml

5、测试

 import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; import com.pt.hibernate.Student; public class StudentTest {
public static void main(String[] arges){
Student s= new Student();
s.setId(20111901);
s.setName("panteng");
s.setAge(23);
Configuration cfg = new Configuration();
SessionFactory sessionFactory = cfg.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
session.close();
sessionFactory.close(); }
}

StudentTest

上一篇:POJ 1584 A Round Peg in a Ground Hole 判断凸多边形,判断点在凸多边形内


下一篇:C# 6 与 .NET Core 1.0 高级编程 - 38 章 实体框架核心(下)