Hibernate4 初级配置实现基本的插入查询

整体架构:

在这里插入图片描述

链接:https://pan.baidu.com/s/1cnMWdaqVwczEiAAAZNWXlw
提取码:1f1o

hibernate核心配置文件:

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工厂的配置 -->
	<session-factory>
		<!-- jdbc配置 -->
		<property name="connection.driver_class">
				com.mysql.jdbc.Driver
		</property>
		<property name="connection.url">
			<!-- url的两种配置方式 -->
			<!-- jdbc:mysql://localhost:3306/chat-->
			jdbc:mysql:///chat
		</property>
		<property name="connection.username">root</property>
		<property name="connection.password">root</property>
		<!-- 数据库方言
			hibernate支持多种数据库,通过设置方言hibernate才知道应该
			生成对应数据库的sql语句:hibernate支持的数据库的方言hibernate.properties文件中都有
		 -->
		 <!-- 指定数据库 -->
		<property name="dialect">
			org.hibernate.dialect.MySQL5Dialect
		</property>
		
		<!-- 打印hibernate生成的sql语句 -->
		<property name="show_sql">true</property>
		<!-- 格式化打印的sql语句 -->
		<property name="format_sql">true</property>
		
		<!-- 根据不同值,进行数据表表的操作
			create  每次执行 都删除原有表,然后创建新表
			create-drop 执行前创建表,执行后删除表
			update 如果有则不改变表,如果没有则创建
		 -->
		<property name="hbm2ddl.auto">update</property>
		
		<!-- 将所有映射文件添加到这里 -->
		<mapping resource="cn/sxt/pojo/Userhbm.xml"/>
		
	</session-factory>
</hibernate-configuration>

POJO类:

public class User {
	private int id;
	private String name;
	private int age;}

sql映射文件:

Userhbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >
<!-- 类的映射文件信息 -->
<!-- package指定类的包名 可以不配置 如果不配置 那么在配置class的name时需要指定该类所在包-->
<!-- <hibernate-mapping package="cn.sxt.pojo"> 可以配置包扫描 -->
<hibernate-mapping >
	<!-- class配置类  name指类名  table指定表名  如果不写,默认类名为表名-->
	<class name="cn.sxt.pojo.User" table="user">
		<!-- id主键的配置 name配置类的属性名
		     column数据库字段名 不写和属性名一致
		     type 指定属性的类型
		     length指定字段的长度
		-->
		<id name="id" column="id">
			<!-- 主键的生成策略
				increment 
					用于为long, short或者int类型生成 唯一标识。只有在没有其他进程往
				同一张表中插入数据时才能使用。 在集群下不要使用。 
				identity 
					对DB2,MySQL, MS SQL Server, Sybase和HypersonicSQL
				的内置标识字段提供支持。 返回的标识符是long, short 或者int类型的。 
				native -(如果是mysql自增,那么native和identity是一样)
					根据底层数据库的能力选择identity, sequence 或者hilo中的一个。 
				sequence 
					在DB2,PostgreSQL, Oracle, SAP DB, McKoi中使用序列(sequence), 
					而在Interbase中使用生成器(generator)。返回的标识符是long, short或者 int类型的。 
				<generator class="sequence">
					<param name="sequence">user_seq</param>
				</generator>
				assigned 
					让应用程序在save()之前为对象分配一个标示符。这是 <generator>元素没有指定时
					的默认生成策略。
			 -->
			<generator class="identity"></generator>
			
		</id>
		
		<!-- property是配置类的属性  name指属性名 -->
		<property name="name" length="100"/>
		<property name="age" />
		
	</class>
</hibernate-mapping>

工具类:

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {
	private static Configuration cfg=null;
	private static ServiceRegistry registry=null;
	private static SessionFactory factory=null;
	static{
		cfg = new Configuration().configure();
		registry = new StandardServiceRegistryBuilder()
					.applySettings(cfg.getProperties())
					.build();
		factory = cfg.buildSessionFactory(registry);
	}
	public static Session getSession(){
		return factory.openSession();
	}
}

测试类:

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import cn.sxt.pojo.User;

public class Test {
	public static void main(String[] args) {
		//读取src下hibernatecfg.xml 如果不为configure指明参数 默认读取hibernate.cfg.xml
		Configuration cfg = new Configuration().configure();
		//也可以指定路径
		//Configuration cfg = new Configuration().configure("cn/sxt/util/hibernate.cfg.xml");
		
		//3.x版本不需要ServiceRegistry
		//4.0 ServiceRegistryBuilder
		//获取注册对象4.3的创建办法
		ServiceRegistry registry = new StandardServiceRegistryBuilder()
									.applySettings(cfg.getProperties())
									.build();
		//SessionFactory是一个重量级对象 session的工厂 生命周期是进程级别的 支持集群 线程安全的
		SessionFactory factory = cfg.buildSessionFactory(registry);
		/*Session (org.hibernate.Session) 
			表示应用程序与持久储存层之间交互操作的一个单线程对象,
			此对象生存期很短。 其隐藏了JDBC连接,也是Transaction的工厂。
			 其会持有一个针对持久化对象的必选(第一级)缓存,在遍历对象图或者根据持久化标识查找对象时会用到
		   session支持数据库操作
		 * */
		Session session = null;
		//事务对象
		Transaction tx =null;
		try{
			session = factory.openSession();
			tx = session.beginTransaction();
			User u = new User("小红",22);
			//保存数据
			session.save(u);
			//提交事务
			tx.commit();
			
			Object object = session.get(User.class, 4);
			System.out.println(((User)object).toString());
			
			
		}catch(Exception e){
			if(tx!=null)
			//回滚事务
			tx.rollback();
		}finally{
			if(session!=null)
				session.close();
		}
		factory.close();
	}
}

测试结果:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_16183731/article/details/83934691
今日推荐