Hibernate基础实例

hibernate是orm(对象关系映射)框架 即通过配置文件使对象与数据库表关联


hibernate下载
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
让eclipse断网拥有xml提示功能

①解压hibernate-core-5.0.7.Final.zip

②进入hibernate-release-5.0.7.Final\lib\required\
	下解压hibernate-core-5.0.7.Final.jar
③进入hibernate-core-5.0.7.Final\org\hibernate\
	把目录中dtd和xsd文件单独放在一块 便于管理
//此处演示配置单个 其余配置同理
hibernate-configuration-3.0.dtd
hibernate-configuration-4.0.xsd
hibernate-mapping-3.0.dtd
hibernate-mapping-4.0.xsd
④打开hibernate-mapping-3.0.dtd 复制xml文档类型标记里的uri
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

在这里插入图片描述


hibernate的所有配置文件模板都在 hibernate-release-5.0.7.Final\project\etc\

ehcache.xml
hibernate-service.xml
hibernate.cfg.xml
hibernate.properties
hibernate.properties.template
log4j.properties

hibernate实例

①导入hibernate包 必需包hibernate-release-5.0.7.Final\lib\required\

//导入hibernate必需包
antlr-2.7.7.jar
dom4j-1.6.1.jar
geronimo-jta_1.1_spec-1.1.1.jar
hibernate-commons-annotations-5.0.1.Final.jar
hibernate-core-5.0.7.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
jandex-2.0.0.Final.jar
javassist-3.18.1-GA.jar
jboss-logging-3.3.0.Final.jar
//数据库连接包
mysql-connector-java-5.1.7-bin.jar

②创建customer表

CREATE TABLE `customer` (
	`id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客户id',
	`name` varchar(32) NOT NULL COMMENT '客户name'
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

③创建实体类Customer

//创建实体类与customer表对应 类名=表名字 属性名=表字段名
public class Customer {
	private Long id;
	private String name;
	//getter setter
	//框架调用无参构造方法实例对象 构造方法没有重载时可默认不写jvm会补充
}

④创建对象与表映射文件Customer.hbm.xml 和实体类放置同包

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
   <!-- 配置表与实体对象的关系 -->
   <!-- package属性:填写包名 在元素内部需书写完整类名的属性 可直接去掉包名 -->
<hibernate-mapping package="com.java.entity" >
	<!-- 
		class元素:配置实体与表的对应关系
			name:完整类名
			table:数据库表名
	 -->
	<class name="Customer" table="customer" >
		<!-- id元素:配置主键映射的属性
				name:填写主键对应属性名
				column(可选):填写表中的主键列名 默认值:列名会默认使用属性名
				type(可选):填写列(属性)的类型 hibernate会自动检测实体的属性类型
						每个类型有三种填法:java类型|hibernate类型|数据库类型
				not-null(可选):配置该属性(列)是否不能为空 默认值:false
				length(可选):配置数据库中列的长度 默认值:使用数据库类型的最大长度
		 -->
		<id name="id" >
			<!-- generator:主键生成策略 -->
			<generator class="native"></generator>
		</id>
		<!-- property元素:除id之外的普通属性映射
				name:填写属性名
				column(可选):填写列名 默认取name的值
				type(可选):填写列(属性)的类型 hibernate会自动检测实体的属性类型
						有三种填法:
							type元素
								java类型[java.lang.String...]
								hibernate类型[string...]
								sql-type元素
									数据库类型[varchar...]
				not-null(可选):配置该属性(列)是否不能为空 默认值:false
				length(可选):配置数据库中列的长度 默认值:使用数据库类型的最大长度
		 -->
		<property name="name" column="name" ></property>
	</class>
</hibernate-mapping>

⑤创建hibernate主配置文件 路径在src下 名字为hibernate.cfg.xml(默认配置)

<?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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<!-- 数据库url -->
		<property name="hibernate.connection.url">jdbc:mysql:///test</property>
		<!-- 数据库连接用户名 -->
		<property name="hibernate.connection.username">root</property>
		<!-- 数据库连接密码 -->
		<property name="hibernate.connection.password">root</property>
		<!--
			数据库方言
			不同数据库sql语法略有区别 指定方言可让hibernate框架针对区别生成sql语句
			sql99标准(通用语法):
				DDL 定义语言  库&表的增删改查
				DCL 控制语言 事务&权限
				DQL 查询语言 数据查询
				DML 操纵语言 数据增删改
			注意:MYSQL在选择方言时 选择MySQLDialect 通用状态
		-->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

		<!-- 将hibernate生成的sql语句打印到控制台 -->
		<property name="hibernate.show_sql">true</property>
		<!-- 将hibernate生成的sql语句格式化(语法缩进) -->
		<property name="hibernate.format_sql">true</property>
		<!-- 
		## auto schema export				自动导出表结构 自动建表
		#hibernate.hbm2ddl.auto create		自动建表 每次框架运行都会创建新的表 以前表将会被覆盖 表数据会丢失(开发时测试使用)
		#hibernate.hbm2ddl.auto create-drop	自动建表 每次框架运行结束都会将所有表删除(开发时测试使用)
		#hibernate.hbm2ddl.auto update		自动生成表 如果已经存在不会再生成 如果表有变动 自动更新表数据|字段(对数据库无数据影响)
		#hibernate.hbm2ddl.auto validate	校验 不生成表 每次启动会校验数据库中表是否正确 校验失败报错
		 -->
		<property name="hibernate.hbm2ddl.auto">update</property>
		<!-- 引入映射文件路径填写src下的路径 -->
		<mapping resource="com/java/entity/Customer.hbm.xml" />

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

测试框架实例

public class Test {
	public static void main(String[] args) {
		Configuration configuration= new Configuration().configure();
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();

		Customer customer = new Customer();
		customer.setName("TestName");
		session.save(c);//执行保存

		transaction.commit();
		session.close();
		sessionFactory.close();
	}
}
select * from customer;
			+---------------+-------------------+
			|		id		|		name		|
			+---------------+-------------------+
			|		1		|		TestName	|
			+---------------+-------------------+

hibernate常用api

public class Test {
	public static void main(String[] args) {
		// 创建框架配置对象
		Configuration configuration = new Configuration();

		// 读取指定主配置文件 空参加载方法默认加载src下的hibernate.cfg.xml文件
		configuration.configure();

		// 读取指定类映射xml文件 如主配置中已引入映射配置 不需要手动加载
		// configuration.addResource(resourceName);
		// configuration.addClass(persistentClass);

		// 根据配置信息 创建SessionFactory对象 此类线程安全串行运行建议只有一个实例
		SessionFactory sessionFactory = configuration.buildSessionFactory();

		// 获得session对象
		Session session = sessionFactory.openSession();

		// 只获得操作事务的Transaction对象
		// Transaction transaction = session.getTransaction();
		// 获得Transaction对象并开启事务(建议使用)
		Transaction transaction = session.beginTransaction();

		/*
		 * 根据Customer的id去查询用户 1l代表Customer的id类型为long值为1
		 * Customer customer = session.get(Customer.class, 1l);
		 * System.out.println(customer);
		 */

		/*
		 * 增加单个用户
		 * Customer customer = new Customer();
		 * customer.setName("User");
		 * 执行save
		 * session.save(customer);
		 */

		/*
		 * 获得要修改的对象
		 * Customer customer = session.get(Customer.class, 1l);
		 * 修改成功后的数据
		 * customer.setName("Test");
		 * 执行update
		 * session.update(customer);
		 */

		/*
		 * 获得要删除的对象
		 * Customer customer = session.get(Customer.class, 1l);
		 * 执行delete
		 * session.delete(customer);
		 */

		//transaction.rollback();// 回滚事务
		transaction.commit();// 提交事务
		session.close();// 释放资源
		sessionFactory.close();// 释放资源
	}
}

hibernate工具类

public class HibernateUtils {
	private static SessionFactory sessionFactory;

	static{
		// 默认加载src下的hibernate.cfg.xml创建hibernate配置对象
		Configuration configuration= new Configuration().configure();
		// 根据配置信息 创建SessionFactory对象
		sessionFactory = configuration.buildSessionFactory();
	}

	//获得session对象
	public static Session openSession(){
		// 获得session
		Session session = sessionFactory.openSession();
		return session;
	}
}

转载于:https://www.cnblogs.com/setlilei/p/10629454.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值