【Hibernate】Hibernate入门

1.Eclipse逆向工程Hibernate

1.1 参考链接

https://blog.csdn.net/yinyaowei/article/details/80699819

1.2 注意事项
  • 要注意Eclipse丶JBoss丶jdk版本要一致;我自己使用的是Eclipse Mars版本,所以JBoss链接为https://download.jboss.org/jbosstools/updates/stable/mars;Hibernate Tools运行环境要依赖于jdk1.8+

  • 在Hibernate Configurations视图中新建配置界面Edit Configuration中Main选项卡中的Hibernate Version要选择3.5,不能选择5.0,否则后面会出错

  • hibernate.reveng.xml文件作用标明需要映射的表(执行前要确认源文件Source中的表),执行逆向工程后会对这些表的映射文件和实体类进行覆盖

  • bit类型会被映射成boolean类型,实体类中getter方法变成了is开头而不是get开头,后面会导致一系列麻烦;解决方式①把数据库中的bit类型改成char(1)丶varchar(1)丶smallint丶int等类型,在java中使用注意转换类型(比如String.valueOf(0).charAt(0)),varchar(1)和int不用转换,但占用空间比char(1)大;解决方式②把实体类中的boolean改成Boolean,然后再重新生成getter方法和setter方法,数值不能直接转换为Boolean,可以直接做条件判断String num="1"; Boolean sex=num=="1";

2.添加表结构与测试数据

DROP TABLE IF EXISTS `grade`;
CREATE TABLE `grade` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

INSERT INTO `grade` VALUES ('1', '高一(1)班');
INSERT INTO `grade` VALUES ('2', '高一(2)班');
INSERT INTO `grade` VALUES ('3', '高一(3)班');



DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `sex` bit(1) NOT NULL,
  `birthday` date NOT NULL,
  `grade_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `student_grade_id` (`grade_id`),
  CONSTRAINT `student_grade_id` FOREIGN KEY (`grade_id`) REFERENCES `grade` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

INSERT INTO `student` VALUES ('1', '张三', 1, '2000-10-01', '1');
INSERT INTO `student` VALUES ('2', '李四', 0, '2002-09-01', '2');



DROP TABLE IF EXISTS `subject`;
CREATE TABLE `subject` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

INSERT INTO `subject` VALUES ('1', '语文');
INSERT INTO `subject` VALUES ('2', '数学');
INSERT INTO `subject` VALUES ('3', '英语');



DROP TABLE IF EXISTS `result`;
CREATE TABLE `result` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `score` decimal(4,1) NOT NULL,
  `student_id` int(11) NOT NULL,
  `subject_id` int(11) NOT NULL,
  `date` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `result_student_id` (`student_id`),
  KEY `result_subject_id` (`subject_id`),
  CONSTRAINT `result_subject_id` FOREIGN KEY (`subject_id`) REFERENCES `subject` (`id`),
  CONSTRAINT `result_student_id` FOREIGN KEY (`student_id`) REFERENCES `student` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

INSERT INTO `result` VALUES ('1', '100.5', '1', '1', '2018-02-01 00:00:00');

3.Hibernate入门

3.1下载Hibernate包
3.2 hibernate主配置文件
<?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>
		<!--数据库特性 -->
		<property name="dialect">
			org.hibernate.dialect.MySQLDialect
		</property>
		<!--数据库URL -->
		<property name="connection.url">
			jdbc:mysql://localhost:3306/school
		</property>
		<!-- 数据库用户名 -->
		<property name="connection.username">root</property>
		<!-- 数据库用户密码 -->
		<property name="connection.password">root</property>
		<!-- 数据库JDBC驱动 -->
		<property name="connection.driver_class">
			com.mysql.jdbc.Driver
		</property>



		<!-- 运行程序时是否在控制台显示sql语句 -->
		<property name="show_sql">true</property>
		<!-- 是否格式化sql语句 -->
		<property name="format_sql">true</property>

		<!--jdbc.fetch_size是指Hibernate每次从数据库中取出并放到JDBC的Statement中的记录条数。Fetch Size设的越大,
		读数据库的次数越少,速度越快,但内存占用越多; Fetch Size越小,读数据库的次数越多,速度越慢,但内存占用少 -->
		<property name="jdbc.fetch_size">50 </property>

		<!--jdbc.batch_size是指Hibernate批量插入,删除和更新时每次操作的记录数。Batch Size越大, 批量操作的向数据库
		发送Sql的次数越少,速度就越快,同样耗用内存就越大 -->
		<property name="jdbc.batch_size">20 </property>

		<!-- 映射文件路径 -->
		<mapping resource="com/domain/Student.hbm.xml" />
		<mapping resource="com/domain/Result.hbm.xml" />
		<mapping resource="com/domain/Subject.hbm.xml" />
		<mapping resource="com/domain/Grade.hbm.xml" />

	</session-factory>
</hibernate-configuration>

3.3 映射文件配置
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.domain.Grade" table="grade" catalog="school">
    	<!-- 主键 -->
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            
            <!-- 主键生成策略 -->
            <!-- 
            	increatement:适合int,long,short类型主键,只能在单线程中使用,不能在集群环境中使用
            				  会先发送 select max(id) from 表,然后查询结果+1作为主键值
            				  
            	idendity:适合int,long,short类型主键,使用数据库自身底层的自增机制,适用于MySQL、MSSQL,不能在Oracle使用
            	sequence:适合int,long,short类型主键,适用与Oracle
            	native:根据不同数据库在idendity和sequence中切换    
            	uuid:适合string类型主键,hibernate使用随机字符串作为主键值          
             -->
            
            <generator class="identity" />
        </id>
        
        <!-- 数据库与持久化类的数据类型对应 -->
        <property name="name" type="java.lang.String">
            <column name="name" length="30" not-null="true" />
        </property>
        
        <!-- 外键表集合(1对多) -->
        <set name="students" inverse="true">
            <key>
                <column name="grade_id" not-null="true" />
            </key>
            <one-to-many class="com.domain.Student" />
        </set>
    </class>
</hibernate-mapping>
3.4HibernateSessionFactory类
package com.utils;

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

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {

    /** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     */
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static org.hibernate.SessionFactory sessionFactory;
	
    private static Configuration configuration = new Configuration();
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
    private static String configFile = CONFIG_FILE_LOCATION;

	static {
    	try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
    }
    private HibernateSessionFactory() {
    }
	
	/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}

        return session;
    }

	/**
     *  Rebuild hibernate session factory
     *
     */
	public static void rebuildSessionFactory() {
		try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	/**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

	/**
     *  return session factory
     *
     */
	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
     *  return session factory
     *
     *	session factory will be rebuilded in the next call
     */
	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}
	/**
     *  return hibernate configuration
     *
     */
	public static Configuration getConfiguration() {
		return configuration;
	}

}
3.5Hibernate简单例子
	//1、解析hibernate控制文件
        Configuration config=new Configuration().configure();
        //2、创建SessionFactory
        SessionFactory sf=config.buildSessionFactory();
        //3、通过SessionFactory创建Session
        Session session=sf.openSession();
               
        //* 使用生成的工厂类可以代替以上3步代码(实际开发中用这种)
        // 获取当前线程中的Session对象
        //Session session=HibernateSessionFactory.getSession();
               
        //4、创建session上的事务对象
        Transaction tran=session.beginTransaction();
        
        try {
			/* 进行增删改查操作 */       
			Grade grade=new Grade();
			grade.setName("高一(4)班");    
			session.save(grade);
			      
			//5、提交事务(只有调用commit()才会把数据固化到数据库)
			tran.commit();
		} catch (Exception e) {	
			//5、回滚事务
			tran.rollback();
			e.printStackTrace();	
		} finally{       
	        //6、关闭session
	        session.close();
            //工厂类的关闭当前线程的session方法
	        //HibernateSessionFactory.closeSession();
		}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值