hibernate 配置文件

hibernate 默认配置文件在src根目录下

默认配置文件名:hibernate.cfg.xml

hibernate核心文件夹下 找到dtd文档



复制里面的dtd


到创建好的hibernate.cfg.xml配置文件中做头部

直接打尖括号 会出现更目录标签

===============================================================

文件需要配置3类数据

1. 链接数据库

2. 辅助参数

3. Mapping映射文件注入

===============================================================

核心API-------》configuration--》sessionfactory--》session

Javaweb--》中的session叫用户session  可客户端的沟通

在hibernate中的session是和数据库的沟通

不同场合session含义不同

Session:hibernate中作用1.数据库链接2.执行语句3.缓存

Configurateion可以读配置文件------》创建sessionFactory------》每次访问数据库时候创建session


配置文件:hibernate.cfg.xml

<!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>
		<!--1. 数据库链接 -->
		<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
		<property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
		<property name="connection.username">scott</property>
		<property name="connection.password">orcl</property>
		
		<!-- 2.辅助参数 -->
		<property name="dialect">org.hibernate.dialect.Oracle12cDialect</property>
		<property name="show_sql">true</property>
		<property name="Formate_sal">true</property>
		<!-- 使用CurrentSessionContext 获取session -->
		<property name="current_session_context_class">thread</property>
		
		<!-- 3.映射配置 -->
		<mapping resource="student.hbm.xml"/>
	</session-factory>
</hibernate-configuration>



映射文件配置 student.hbm.xml

<!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="cn.hibernate.entity.Student" table="student">
		<id name="id" column="id" type= "java.lang.Integer">
			<generator class="increment"></generator>
		</id>
		<property name="name" column="name" type="java.lang.String"></property>
		<property name="clazz" column="clazz" type="java.lang.String"></property>
		<property name="score" column="score" type="java.lang.Integer"></property>
	</class>
</hibernate-mapping>

编写Student实体类 用于数据库表映射

package cn.hibernate.entity;

import java.io.Serializable;

/**
 * pojo 实体类映射数据表对象
 * @author Administrator
 *
 */
public class Student implements Serializable{
	private static final long serialVersionUID = 1234L;
	
	private int id; // OID
	private String name; //姓名
	private String clazz; //科目
	private int score; //分数	
	
	public Student(int id, String name, String clazz, int score) {
		super();
		this.id = id;
		this.name = name;
		this.clazz = clazz;
		this.score = score;
	}

	public Student() {
		super();
	}


	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 getClazz() {
		return clazz;
	}


	public void setClazz(String clazz) {
		this.clazz = clazz;
	}


	public int getScore() {
		return score;
	}


	public void setScore(int score) {
		this.score = score;
	}
	
	

}

编写读取配置文件信息的类HibernateSessionFactory.java

读取配置文件属于io流 所以属性方法都是静态只加载一次即可,其中使用Hibernate框架核心类Configuration读取配置文件,创建SessionFactory从而创建session ,通过session对数据库进行操作。

Configuration ctg = new Configuration();这时候的读取配置文件是空的,需要加载配置文件hibernate.cfg.xml信息,用到方法configure()方法获取xml配置文件中的信息。

ctg = ctg.configure();通过getProperties()方法可以查看配置文件Properties类中的键值对信息。

ctg.buildSessionFactory(); 获取SessionFactory ,从而创建session.

获取session 通过创建静态方法返回Session对象

sessionFactory.getCurrectSession();如果使用该方法获取需要在配置文件中配置

 <property name="current_session_context_class">thread</property>这句话表示使用CurrentSessionContext   

用这个类的方法getCurrectSession();获取session

package cn.hibernate.common;

import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

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


/**
 * 读取配置文件的类
 * @author Administrator
 *
 */
public class HibernateSessionFactory {
	private static Configuration cfg; //读取配置文件
	private static SessionFactory sessionfactory;//链接数据库的会话工厂 只创建一次
	static {
		try {
			cfg  = new Configuration().configure();
			Properties props = cfg.getProperties();
			props.list(System.out);
			System.out.println();
			sessionfactory = cfg.buildSessionFactory();
			Map<String, Object> properties = sessionfactory.getProperties();
			for(Map.Entry<String,Object> entry : properties.entrySet()){
				System.out.println(entry.getKey()+";;;"+entry.getValue());
				
			}
			System.out.println(sessionfactory);
		} catch (HibernateException e) {
			throw new RuntimeException("初始化失败",e);
		}
	}
	
	//创建session时和线程绑定,每个用户得到是唯一的session  需要事务才可以操作
	
	public static Session getSession(){
		Session currentSession = null;
		try {
			currentSession = sessionfactory.getCurrentSession();
			System.out.println("session:"+currentSession);
		} catch (HibernateException e) {
			System.out.println("创建session 失败!"+e);
			throw new RuntimeException("创建session 失败!",e);
		}
		
		return currentSession;
	}
}

Dao层数据库访问层创建CRUD增删改查的方法

例如可以新增

package cn.hibernate.dao;

import cn.hibernate.common.HibernateSessionFactory;
import cn.hibernate.entity.Student;

/**
 * 数据库访问层
 * @author Administrator
 *
 */
public class StudentDao {
	public void add(Student stu){
		try {
			HibernateSessionFactory.getSession().save(stu);
		} catch (Exception e) {
			System.out.println("新增失败"+e);
			throw new RuntimeException("新增失败",e);
		}
	}
}

Biz业务处理层

实现事务操作,提交到数据库层

通过session的beginTranscation()打开事务

执行操作后

提交commit();事务同时会关闭流 因为session 创建方法是用 getCurrentSession()方法

失败后要回滚事务

package cn.hibernate.biz;

import org.hibernate.Transaction;

import cn.hibernate.common.HibernateSessionFactory;
import cn.hibernate.dao.StudentDao;
import cn.hibernate.entity.Student;

public class StudentBiz {
	private StudentDao dao = new StudentDao();
	
	public void addStu(Student stu){
		Transaction tx = null;
		try {
			tx = HibernateSessionFactory.getSession().beginTransaction();
			dao.add(stu);
			tx.commit();
			System.out.println("新增成功");
		} catch (Exception e) {
			
			if(tx!=null){
				tx.rollback();//回滚事务
			}
		}
		
	}
}

Test 测试类

save()方法的id是自增的 所以 设定id值没有效果的

package cn.hibernate.test;

import cn.hibernate.biz.StudentBiz;
import cn.hibernate.entity.Student;

public class Test {

	public static void main(String[] args) {
		Student stu = new Student(3,"wangwu","java",89);
		//id自增 不能设置的
		StudentBiz biz = new StudentBiz();
		biz.addStu(stu);

	}

}
数据库查看效果图:






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值