Hibernate framework-01-02-Environment to build and create the first simple project

Overall steps


0. 安装Eclipse、Mysql;
1. 下载Hibernate,并解压缩;
2. 使用Eclipse创建新的项目;
3. 引入Hibernate及其依赖库(jar包);
4. 引入Mysql数据库驱动包;
5. 编写Hibernate配置文件;
6. 创建Java持久化类XXX.java;
7. 编写持久化类的映射配置文件XXX.hbm.xml;
8. 使用Hibernate API 完成对象的持久化。

Step 0-1

Download and install Eclipse/IDEA and other java development tools, configure the Java environment, and there are many online tutorials, so I won’t be ugly.

Download the MySql database and install it, you can find the green version free of installation on the Internet, all of which can be used.
Insert picture description here

Step 2 Use development tools to create a project

Because it is in the learning stage, in order to facilitate the creation of ordinary Java projects here, rather than JavaWEB.

Step 3 Import dependent packages

Create a lib folder to store the jar package
Insert picture description here

Open the folder downloaded and decompressed by Hibernate, open the lib subfolder, and open the required folder. The packages inside are all necessary packages. Copy the package to the lib folder you just created.

Step 4 Import the Mysql database driver package;

Download the driver package of MySql, pay attention to the version that is compatible with the version of MySql, and copy the driver package to the lib folder

Select all the previously copied packages, right-click the build path -> configure the build path, and add it to the runtime library.

Step 5 Write the Hibernate configuration file;

Insert picture description here
Create three packages, simulate the hierarchical structure,
Insert picture description here
create the main configuration file, the format is XML format
Insert picture description here

Insert picture description here

Insert picture description here

<?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就是一个配置项 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<!-- dialect是方言,表明用的是什么数据库方言  -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<!-- 数据库驱动类,指定类名 -->
		<!-- 下面是链接数据库的信息,和JDBC类似 -->
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate-database?useUicode=true&amp;characterEncoding=UTF-8</property>
		<!-- &amp  是转义字符,此处是转义分号所用-->
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password"></property>
		
		<!-- 上面5个配置项是必选的,下面两个是可选的,分别是打印sql语句与格式化sql语句,便于调试-->
		<property name="hibernate.show_sql">true</property>
		<property name="hibernate.format_sql">true</property>
		
		<!-- 设置映射文件,属性值是包名+文件名,注意格式变化,点变成了斜杠-->
		<mapping resource="com/hibernate/entity/Customer.hbm.xml"/>
	</session-factory>
	
</hibernate-configuration>
数据库的字符集:utf8 -- UTF-8 Unicode
数据库中表的varchar设置字符集:utf-8
Hibernate需要从配置文件中读取数据库配置信息,配置文件一般位于项目根路径。
Hibernate配置文件两种方式:
hibernate.properties (键=值方式)
默认名字为:hibernate.propeties
hibernate.cfg.xml

Step 6 Create Java persistence class XXX.java;

Persistent class: refers to the class whose instance needs to be persisted to the database by Hibernate, that is, the entity class

  • private type attribute;
  • Setter and getter methods of public type;
  • A parameterless constructor of public or protected type.

Insert picture description here

package com.hibernate.entity;

public class Customer {
    
    
	private Integer id;
	private String name;
	private int age;

	//创建两个构造方法,一个有参数,一个无参数,缺一不可
	public Customer() {
    
    
		super();
	}
	public Customer(Integer id, String name, int age) {
    
    
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
	
	
	//私有属性的get set方法
	public Integer getId() {
    
    
		return id;
	}
	public void setId(Integer 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;
	}
	
	
	
	
}

Step 7 Write the mapping configuration file XXX.hbm.xml of the persistent class;

The mapping file must be placed under the previous persistent class sibling folder

Insert picture description here

<?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 package="com.hibernate.entity">
<!-- package属性值就是实体化类所处的包名 -->
	<!-- 类与表的映射 ,类名区分大小写,表名不区分大小写,为了便于区分故意表名大写-->
	<class name="Customer" table="CUSTOMER">
		<!-- 主键的映射,必选 -->
		<id name="id" column="ID"><!-- name是类的属性名,column是数据库表的主键名 -->
			<generator class="native"/>
		</id>	
		
		<!-- 下面是非主键的映射 -->
		<property name="name" column="NAME"></property>
		<property name="age" column="AGE"></property>	
	</class>
	
</hibernate-mapping>
  • The id child element sets the mapping relationship between the OID of the persistent class and the primary key of the table.
column – 指定表字段的名称;
generator – 元素指定OID的生成器。
  • The property sub-element sets the mapping relationship between other attributes of the class and the fields of the table.
name – 对应类的属性名称;
type – 指定属性的类型;
column – 指定表字段的名称;
not-null – 指定属性是否允许为空。

Step 8 Use Hibernate API to complete object persistence.

Insert picture description here

Insert picture description here
Insert picture description here

Insert picture description here

Insert picture description here

package com.hibernate.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil {
    
    
	//HibernateUtil ������
	
	private static SessionFactory sessionFactory;
	
	
	//静态初始化Hibernate,只需要构建一次就好
	static {
    
    
		//1. 创建ServiceRegistry对象,通过build模式创建
		// 从 hibernate.cfg.xml 读取配置信息并存储到对象当中,是整个API程序的入口
		StandardServiceRegistry register=new StandardServiceRegistryBuilder()
				.configure().build();//读取hibernate.cfg.xml文件,因为build()没有参数,所以采用默认的固定位置固定名称。
				//调用config方法
		try {
    
    
			//2. 创建SessionFactory对象
			sessionFactory=new MetadataSources(register)
					.buildMetadata()//构建源数据
					.buildSessionFactory();//构建SessionFactory
		} catch (Exception e) {
    
    
			e.printStackTrace();//打印异常
			//手动释放StandardServiceRegistry对象
			StandardServiceRegistryBuilder.destroy(register);
		}
	}
	
	/*
		创建Session对象,里面可以包含很多数据库操作
	*/
	public static Session openSession() {
    
    
		return sessionFactory.openSession();
	}
	
	/*
	 	关闭sessionFactory,释放资源
	*/
	public static void closeSessionFactory() {
    
    
		sessionFactory.close();
	}
}

Create test class and finish field test
Insert picture description here

package com.hibernate.ui;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.hibernate.entity.Customer;
import com.hibernate.util.HibernateUtil;

public class Test {
    
    

	public static void main(String[] args) {
    
    
		saveCustomer();
		//关闭SessionFactory
		HibernateUtil.closeSessionFactory();

	}
	
	public static void saveCustomer() {
    
    
		//1. 打开Session
		Session session=HibernateUtil.openSession();
		
		//2. 开启一个数据库事务
		Transaction tx = session.beginTransaction();
		
		//3. 拿到事务,开始保存操作
		Customer c = new Customer();
		c.setName("法外狂徒张三");
		c.setAge(15);		
		session.save(c);
		
		//4. 提交事务
		tx.commit();
		
		//5.关闭Session
		session.close();


/*
 *步骤1创建Session对象时,一但使用了自定义的openSession方法,就会调用静态代码块完场session的对象创建与实现操作
 *所有关于数据库的操作都在Session工具类里
 * */
 


	}

}

The operation result is normal
Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44627608/article/details/114277799