hibernate初学简单实例

首先把需要的jar包和相关的文档准备好。


 hibernate所需jar包


hibernate配置文件参考文档 


hibernate中类的API


好了有以上这些东西就可以开始hibernate的学习之路了


一开始在myeclipse中新建一个java项目,现在还用不到web项目。


马士兵老师教了一个新的jar包引入方式,打开window->preferences->java->build path->user libraries


点new新建一个自定义jar包库,取名hibernate,然后点击这个jar包库,点击add jars把下载的hibernate的jar包里面required(必要的)jar全部加进去。


点击新建的java项目,右键点击build path->add library->User library->next  勾选刚才新建的自定义jar包库。点击finish,OK,hibernate必要的jar包已导入。


然后右键 add archive把mysql所需的jar包加进来。


下面开始写第一个hibernate程序


1.src下面建一个model包



新建一个Student类



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



2.在数据库中新建一个hibernate的database


然后建一个student表 create table student(id int primary key,name varchar(20),age int);




3.在src目录下新建一个hibernate.cfg.xml


配置文件中的url username password写你自己的


<?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>


        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3256/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">110110</property>


        <!-- JDBC connection pool (use the built-in) -->
       <!-- <property name="connection.pool_size">1</property>-->


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


        <!-- Enable Hibernate's automatic session context management -->
       <!--  <property name="current_session_context_class">thread</property>-->


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


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


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


        <mapping resource="com/lin/hibernate/model/Student.hbm.xml"/>


    </session-factory>


</hibernate-configuration>




4.在model下新建Student.hbm.xml     这是实体类与数据库中表映射配置文件


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">


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






关于上面2个配置文件可以在文章最开头的参考文档URL里面查看如何去写。



5.新建一个util包,然后在这个包下新建一个HibernateUtil工具类,该工具类使用了单例模式,工厂只会被实例化一次,减小资源消耗。


package util;


import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;


public class HibernateUtil {


    private static final SessionFactory sessionFactory = buildSessionFactory();


    private static SessionFactory buildSessionFactory() {
    	SessionFactory sessionFactory = null;
    	try {
        	Configuration configuration = new Configuration();  
        	configuration.configure();//如果不写运行会抛出异常,执行是会出错的
        	ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();  
        	sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
		return sessionFactory;
    }


    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }


}





6.在src下新建一个测试类


import org.hibernate.Session;
import org.hibernate.SessionFactory;


import com.lin.hibernate.model.Student;
import com.lin.hibernate.util.HibernateUtil;




public class StudentTest {
public static void main(String[] args) {
	Student s1 = new Student();
	s1.setId(1);
	s1.setName("linjian");
	s1.setAge(21);
	Student s2 = new Student();
	s2.setId(2);
	s2.setName("linxiaobai");
	s2.setAge(22);
	Student s3 = new Student();
	s3.setId(3);
	s3.setName("xiaobai");
	s3.setAge(23);
	SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
	Session session = sessionFactory.openSession();
	session.beginTransaction();
	session.save(s1);
	session.save(s2);
	session.save(s3);
	session.getTransaction().commit();
	session.close();
	sessionFactory.close();
}
}





好了,OK,运行测试代码,数据成功存入数据库。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值