zoukankan      html  css  js  c++  java
  • Hibernate---第一个helloworld程序 (XML版本, annotation版本)

    Hibernate作为JPA的一种实现,jpa的注解已经是hibernate的核心,hibernate只提供了一些补充,而不是两套注解。hibernate对jpa的支持够足量,在使用hibernate注解建议使用jpa

    XML版本过程:

    新建工程, 导入hibernate包, 数据库包, 建立数据库表, 新建model类, 测试类, 新建src下hibernate.cfg.xml, model 类下 Student.hbm.xml

    annotation版本过程:

    新建工程, 导入hibernate包, 数据库包, 建立数据库表, 新建model类 (里面加入@Entity(javax), 和@Id (主键)), 测试类, 新建src下hibernate.cfg.xml(加入映射)

    所以annotation比较简单.

    XML版本具体过程:

    1. new->java project : hibernate_0100_HelloWorld

    2. 引入所有Hibernate的jar包:

      1. preferrence->java->build path->user library-> new("hibernate")-> Add JARs (hibernate3, antlr, commons-collections, dom4j, javassist, jta,slf4j-api, slf4j-nop)

        2. 右键项目 build-> add libraries->user library->"hibernate"

    3. 引入数据库包 build-> add external archieves-> mysql-connector....

    4. 建立数据库的表    

    create database hibernate;
    use hibernate;
    create table student(id int primary key, name varchar(20), age int);
    

    5. new class: Student    package: com.bjsxt.hibernate.model

    package com.bjsxt.hibernate.model;
    
    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;
    	}
    }
    

    6.  new class: StudentTest.java     package: default

    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    import com.bjsxt.hibernate.model.Student;
    
    
    public class StudentTest {
    	public static void main(String[] args) throws Exception{
    		Student s =new Student();
    		s.setId(2);
    		s.setName("lisi");
    		s.setAge(30);
    		
    		Configuration cfg=new Configuration();
    		SessionFactory sf=cfg.configure().buildSessionFactory(); //默认找hibernate.cfg.xml,然后产生一个connection工厂
    		Session session =  sf.openSession();
    		session.beginTransaction();
    		session.save(s);
    		session.getTransaction().commit();
    		session.close();
    		sf.close();
    	}
    }
    

    7. 在src下放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>
    
             
            <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="connection.url">jdbc:mysql://localhost/hibernate</property>
            <property name="connection.username">root</property>
            <property name="connection.password">linda0213</property>
            <property name="dialect">org.hibernate.dialect.MySQLDialect</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.NoCacheProvider</property>
    
            <!-- Echo all executed SQL to stdout -->
            <property name="show_sql">true</property>
    		<!--<property name="format_sql">true</property> -->
    
            <!-- Drop and re-create the database schema on startup
            <property name="hbm2ddl.auto">update</property>
    		 -->
    		<!--<mapping class="com.bjsxt.hibernate.model.Student"/> -->
            <mapping resource ="com/bjsxt/hibernate/model/Student.hbm.xml"/>		
        </session-factory>
    
    </hibernate-configuration>
    

    8. 在model下new Student.hbm.xml:

    <?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.bjsxt.hibernate.model">
        <class name="Student" table="student">
            <id name="id"></id>
            <property name="name"/>
            <property name="age"/>
        </class>
    </hibernate-mapping>
    

    9. run -> java application.

    运行出错的话一般还需要加入两个包: cglib-nodep-2.1_3.jar, commons-logging.jar

      

    annotation版本具体过程:

    1. 加入annotation相关的jar包(hibernate-annotations, ejb3-persistence, hibernate-commons-annotations )

    2. 创建teacher表:

    use hibernate;
    create table teacher(id int primary key, name varchar(20), title varchar(10));
    

    3. 创建一个新的model 类, Teacher.java:

    里面加入@Entity(javax), 和@Id (主键)

    package com.bjsxt.hibernate.model;
    
    import javax.persistence.Entity;
    import javax.persistence.Id;
    
    @Entity
    public class Teacher {
    	private int id;
    	private String name;
    	private String title;
    	
    	@Id
    	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 String getTitle() {
    		return title;
    	}
    	public void setTitle(String title) {
    		this.title = title;
    	}
    }
    

    3. 建立一个新的测试类TeacherTest.java;

    import javax.persistence.Entity;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.AnnotationConfiguration;
    import org.hibernate.cfg.Configuration;
    
    import com.bjsxt.hibernate.model.Teacher;
    
    @Entity
    public class TeacherTest {
    	public static void main(String[] args) throws Exception{
    		Teacher t =new Teacher();
    		t.setId(3);
    		t.setName("ww");
    		t.setTitle("high");
    		
    		Configuration cfg=new AnnotationConfiguration();
    		SessionFactory sf=cfg.configure().buildSessionFactory(); //默认找hibernate.cfg.xml,然后产生一个connection工厂
    		Session session =  sf.openSession();
    		session.beginTransaction();
    		session.save(t);
    		session.getTransaction().commit();
    		session.close();
    		sf.close();
    	}
    }
    

    4. hibernate-cfg.xml里加入这句话:

    <mapping class="com.bjsxt.hibernate.model.Teacher"/>
    

      

      

    也可以自动创建数据库里的表, 只需要在hibernate.cfg.xml里加入这样一句话:

    <property name="hbm2ddl.auto">create</property> 
    

    可以通过类正向建表. 也可以建表反向推出类 

    那么是先建表还是先建类呢?  理论上来说, 先建类, 但是实际工作中先表.

    因为表需要进行优化,  

     

      

  • 相关阅读:
    监听器模式
    接口幂等性实现
    如何设计一个良好的API接口
    接口重试实现
    Spring不常用但有用的注解
    angular项目语言切换功能
    解决IOS上传竖向照片会旋转90度的问题
    微信点击链接:debugx5.qq.com提示您使用的不是x5内核
    swagger注释@API详细说明
    创建swap虚拟内存分区
  • 原文地址:https://www.cnblogs.com/wujixing/p/5403943.html
Copyright © 2011-2022 走看看