1、项目结构
2、hibernate实现了Java类 和 数据库表的映射(Map)
先看一下Student的Java类和对应的数据库表
1 package com.pt.hibernate; 2 3 public class Student { 4 private int id; 5 private String name; 6 private int age; 7 public int getId() { 8 return id; 9 } 10 public void setId(int id) { 11 this.id = id; 12 } 13 public String getName() { 14 return name; 15 } 16 public void setName(String name) { 17 this.name = name; 18 } 19 public int getAge() { 20 return age; 21 } 22 public void setAge(int age) { 23 this.age = age; 24 } 25 }
Student.java
创建Student表的SQL语句
1 CREATE TABLE `student` ( 2 `Id` int(20) NOT NULL, 3 `Name` varchar(20) DEFAULT NULL, 4 `Age` int(3) DEFAULT NULL, 5 PRIMARY KEY (`Id`) 6 ) ENGINE=InnoDB DEFAULT CHARSET=latin1
Creat table
3、通过student.xml配置文件,将Java类和数据库表关联起来
1 <?xml version="1.0"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 5 6 <hibernate-mapping package="com.pt.hibernate"> 7 <class name="Student" table="student"> 8 <id name="id" column="id" ></id> 9 <property name="name" column="name" ></property> 10 <property name="age" column="age" ></property> 11 </class> 12 </hibernate-mapping>
Student.xml
4、通过hibernate.cfg.xml配置文件,初始化hibernate所需要的信息
1 <?xml version=‘1.0‘ encoding=‘utf-8‘?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 4 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 5 6 <hibernate-configuration> 7 8 <session-factory> 9 10 <!-- Database connection settings --> 11 <!-- <property name="connection.driver_class">org.hsqldb.jdbcDriver</property> 12 <property name="connection.url">jdbc:hsqldb:hsql://localhost/TestDB</property> --> 13 14 <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 15 <property name="connection.url">jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=UTF-8</property> 16 <property name="connection.username">root</property> 17 <property name="connection.password"></property> 18 19 <!-- SQL dialect --> 20 <property name="dialect"> 21 org.hibernate.dialect.MySQLInnoDBDialect 22 </property> 23 <property name="show_sql">true</property> 24 <mapping resource="com/pt/hibernate/Student.xml"/> 25 </session-factory> 26 27 </hibernate-configuration>
hibernate.cfg.xml
5、测试
1 import org.hibernate.Session; 2 import org.hibernate.SessionFactory; 3 import org.hibernate.cfg.Configuration; 4 5 import com.pt.hibernate.Student; 6 7 8 public class StudentTest { 9 public static void main(String[] arges){ 10 Student s= new Student(); 11 s.setId(20111901); 12 s.setName("panteng"); 13 s.setAge(23); 14 Configuration cfg = new Configuration(); 15 SessionFactory sessionFactory = cfg.configure().buildSessionFactory(); 16 Session session = sessionFactory.openSession(); 17 session.beginTransaction(); 18 session.save(s); 19 session.getTransaction().commit(); 20 session.close(); 21 sessionFactory.close(); 22 23 } 24 }
StudentTest
时间: 2024-10-09 03:12:39