zoukankan      html  css  js  c++  java
  • Hibernate_HelloWord

    Hibernate操作步骤

    1.新建项目
    
    2.加jar包
    
    3.写XML配置文件hibernate.cfg.xml
    
    4.写log4j.properties日志文件
    
    5.在MySql数据库中建student表
    
    6.建Student实体类(先建表后建类)
    
    7.写XML映射文件Student.hbm.xml,或者Annotation映射语句
    
    8.在hibernate.cfg.xml中添加相应mapping
    
    9.写测试类main,或者Junit测试类(项目右键-->“New”-->“Junit Test Case”)

    HelloWorld小程序----XML映射文件

    1.新建项目

    2.加jar包。此处列出的jar包是Hibernate所需的全部jar包,在此项目中并不是全部需要

    将如下jar包封装进一个User Library,名为hibernate
    
    antlr-2.7.6.jar
    c3p0-0.9.1.jar
    commons-collections-3.1.jar
    dom4j-1.6.1.jar
    hibernate3.jar
    hibernate-annotations.jar
    hibernate-commons-annotations.jar
    hibernate-jpa-2.0-api-1.0.0.Final.jar
    javassist-3.12.0.GA.jar
    jta-1.1.jar
    junit-4.10.jar
    log4j-1.2.14.jar
    mysql-connector-java-5.1.7-bin.jar
    slf4j-api-1.6.1.jar
    slf4j-log4j12-1.6.1.jar

    3.hibernate.cfg.xml配置文件。其中<mapping/>在步骤8中设置

    <?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/test</property>
            <property name="connection.username">root</property>
            <property name="connection.password">root</property>
    
            <!-- JDBC connection pool 连接池 -->
            <!-- <property name="connection.pool_size">1</property> -->
    
            <!-- SQL dialect 方言-->
            <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    
            <!-- 当前session上下文 . thread:当前线程;jta:(java transaction api) -->
            <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 显示sql语句-->
            <property name="show_sql">true</property>
    
            <!-- Drop and re-create the database schema on startup 常用选项:create和update -->
            <property name="hbm2ddl.auto">update</property>
    
            <mapping resource="com/hibernate/model/Student.hbm.xml"/>
            <!-- <mapping class="com.hibernate.model.Student"/> -->
            
        </session-factory>
    </hibernate-configuration>

    4.log4j.properties日志文件

    ### direct log messages to stdout ###
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target=System.out
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
    
    ### direct messages to file hibernate.log ###
    #log4j.appender.file=org.apache.log4j.FileAppender
    #log4j.appender.file.File=hibernate.log
    #log4j.appender.file.layout=org.apache.log4j.PatternLayout
    #log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
    
    ### set log levels - for more verbose logging change 'info' to 'debug' ###
    
    log4j.rootLogger=warn, stdout
    
    #log4j.logger.org.hibernate=info
    #log4j.logger.org.hibernate=debug
    
    ### log HQL query parser activity
    #log4j.logger.org.hibernate.hql.ast.AST=debug
    
    ### log just the SQL
    #log4j.logger.org.hibernate.SQL=debug
    
    ### log JDBC bind parameters ###
    #log4j.logger.org.hibernate.type=info
    #log4j.logger.org.hibernate.type=debug
    
    ### log schema export/update ###
    #log4j.logger.org.hibernate.tool.hbm2ddl=debug
    
    ### log HQL parse trees
    #log4j.logger.org.hibernate.hql=debug
    
    ### log cache activity ###
    #log4j.logger.org.hibernate.cache=debug
    
    ### log transaction activity
    #log4j.logger.org.hibernate.transaction=debug
    
    ### log JDBC resource acquisition
    #log4j.logger.org.hibernate.jdbc=debug
    
    ### enable the following line if you want to track down connection ###
    ### leakages when using DriverManagerConnectionProvider ###
    #log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace

    5.在数据库中建表

    建表可以在数据库中手动建,也可以通过运行程序自动建立。

    此处自动建表

    6.建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;
    	}
    }

    7.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>
    	<class name="com.hibernate.model.Student" dynamic-update="true">
    		<id name="id">
    			<generator class="native"></generator>   <!-- generator设置其id自增 -->
    		</id>                                        <!-- id指的是相应表的主键 -->
    		<property name="name"></property>
    		<property name="age"></property>
    	</class>
    
    </hibernate-mapping>

    8.在hibernate.cfg.xml中添加相应mapping

    9.写测试类main

    public class StudentTest {
    	public static void main(String[] args) {
    		Student s = new Student();
    		s.setName("s3");
    		s.setAge(10);
    		
    		SessionFactory sf = new Configuration().configure().buildSessionFactory();
    		
    		Session session = sf.getCurrentSession();
    		session.beginTransaction();
    		session.save(s);
    		session.getTransaction().commit();
    		
    		sf.close();
    	}
    
    }

    程序到此结束,运行后,会自动在数据库创建student表,并将对象s存入student表中。

    HelloWorld小程序----Annotation映射语句

    步骤1-5同上

    6,7.建实体类,添加Annotation注解

    @Entity   //表示这是一个实体类,和数据库中的某个表是对应的
    public class Teacher {
    	private int id;
    	private String name;
    	private int age;
    	
    	@Id                //主键
    	@GeneratedValue    //ID生成策略,默认为AUTO
    	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;
    	}	
    }

    8.在hibernate.cfg.xml中添加相应mapping,如下

    <mapping class="com.hibernate.model.Student"/>

    9.写测试类

    测试类有很多种方式

    a)见上文测试类main

    b)创建一个HibernateUtil辅助类 ,然后再建测试类main

    public class HibernateUtil {
    	private static SessionFactory sf = buildSessionFactory();
    
    	private static SessionFactory buildSessionFactory() {
    		return new Configuration().configure().buildSessionFactory();
    	}
    	public static SessionFactory getSessionFactory() {
    		return sf;
    	}
    }
    public class StudentTest {
    	public static void main(String[] args) {
    		Student s = new Student();
    		s.setName("lisi");
    		s.setAge(18);
    		
    		SessionFactory sf = HibernateUtil.getSessionFactory();
    		
    		Session session = sf.getCurrentSession();
    		session.beginTransaction();
    		session.save(s);
    		session.getTransaction().commit();
    		
    		sf.close();		
    	}
    }

    c)建Junit测试类

    项目右键-->“New”-->“Junit Test Case”,输入类名,然后完善test方法

    public class StudentTest_Junit {
    	private static SessionFactory sf = null;
    	
    	@BeforeClass
    	public static void beforeClass(){
    		sf = new Configuration().configure().buildSessionFactory();
    	}
    	
    	@AfterClass
    	public static void afterClass(){
    		sf.close();
    	}
    
    	@Test
    	public void test() {
    		Student s = new Student();
    		s.setName("wangwu");
    		s.setAge(23);
    		
    		Session session = sf.getCurrentSession();
    		session.beginTransaction();
    		session.save(s);
    		session.getTransaction().commit();
    	}
    }

    程序到此结束,运行后,会自动在数据库创建student表,并将对象s存入student表中。

  • 相关阅读:
    2017 ICPC沈阳站L
    (POJ 1990)Mowfest(确定不再来一发树状数组么?)
    (POJ 3067) Japan (慢慢熟悉的树状数组)
    (POJ 2549)Sumsets(折半枚举)
    图的高siao存储结构——链式前向星
    (HDU1317)XYZZY(Floyd+spfa)
    (POJ1182)食物链(带权并查集-附通用模板)
    (HDU 1231)最大连续子序列
    (HDU 1598) find the most comfortable road (并查集+最小生成树)
    Problem: The World Final II(NEUOJ1175)排序+动态规划
  • 原文地址:https://www.cnblogs.com/weilunhui/p/3895535.html
Copyright © 2011-2022 走看看