您的位置:首页 > 其它

hibernate第一课

2016-02-27 13:38 281 查看
1、在hibernate官网下载相应文件,打开MyEclipse,创建项目,并添加hibernate相应jar包和mysq数据库驱动包。

2、Student.java

package com.wxh.hibernate.model;

public class Student {
	public 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;
	}
	
}
3.Student.hbm.xml

<hibernate-mapping package="com.wxh.hibernate.model">
	<class name="Student" >
		<id name="id"></id>
		<properties name="age"></properties>
		<properties name="name"></properties>
	</class>
</hibernate-mapping>


4.hibernate.cfg.xml

<?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">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/db</property>
        <property name="connection.username">root</property>
        <property name="connection.password">111</property>       

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>       

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>     

        <mapping resource="com/wxh/hibernate/model/Student.hbm.xml"/>		
    </session-factory>

</hibernate-configuration>


5.StudentTest.java

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

import com.wxh.hibernate.model.Student;

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


6.在mysql中新建数据库db和相应的表结构。

7.思考:为什么数据库中只能插入id的值,age和name的值没有?

8.解决办法:修改配置文件Student.hbm.xml,把其中的properties改为property,问题解决。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: