Hibernate framework-02-01-Hibernate single entity mapping


Persistent configuration file

class element

The <class> element is used to specify the mapping between classes and tables.
name-set the class name (including path);
table-set the table name, the class name is used as the table name by default.
The <class> element contains one child element and multiple <property> child elements.

<?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">
	<!-- 类与表的映射 -->
	<class name="User" table="USER">
		<!-- 上面的类名与数据库名之所以可以简写,是因为	hibernate-mapping package属性规定了文件所处的包名 -->
		<!-- 主键的映射,必选 -->
				
		
		
		<id name="id">
			<!-- 数据库的字段 -->
			<column name="ID"></column>
			<generator class="native"/>
		</id>		
		
		
	<!--column可以通过嵌套的形式放在id标签里面 ,和上面那种形式等价
		<id name="id" column="ID">
			<generator class="native"/>
		</id>	
	 -->			
		

		
		
		<!-- id标签只有一个,且必须在property标签上面 -->
		<property name="name" column="NAME" type="java.lang.String"></property>
		<property name="password" column="PASSWORD"></property>	
	</class>
	
</hibernate-mapping>


id element

The <id> child element sets the mapping relationship between the OID (object identifier) ​​of the persistent class and the primary key of the table.
column – specifies the name of the table column;
generator – the element specifies the generator of the OID.

property element

The <property> child element sets the mapping relationship between other attributes of the class and the fields of the table.
name-the attribute name of the corresponding class;
type-specify the type of the attribute; optional
column-specify the name of the table field;
not-null-specify whether the attribute is allowed to be empty.

Because the String type of type is a reference type, it must be named java.lang.String in its entirety, but the basic type is not needed, just write int, char or something.

The column is also optional, provided that the field name is the same as the attribute name. That is, the name attribute value is the same as the column attribute value

The realization of addition, deletion, modification and checking operation

Insert picture description here

package com.hibernate.ui;

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

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

public class Test {
    
    

	public static void main(String[] args) {
    
    
//		saveUser();
//		getUserById();
		updateUser();
		//deleteUser();
		
		//关闭SessionFactory
		HibernateUtil.closeSessionFactory();
	}
	
	
	/*
	 * 增添操作
	 * */
	public static void saveUser() {
    
    
		Session session = null;
		Transaction tx = null;
		
		try {
    
    
			//1. 打开Session
			session=HibernateUtil.openSession();
			//2. 开启数据库事务
			tx = session.beginTransaction();
			//3. 保存操作
			User user=new User();
			user.setName("李四");
			user.setPassword("LiSi");
			session.save(user);
			//4. 提交事务
			tx.commit();
		} catch (Exception e) {
    
    
			//捕获异常,事务回滚
			tx.rollback();
		} finally {
    
    
			//5. 关闭Sesson,回收资源
			session.close();
		}		

	}
	
	/*
	 * 查询操作
	 * */
	public static void getUserById() {
    
    
		//得到Session对象
		Session session=HibernateUtil.openSession();
		//参数1:要查询的对象类型,参数2:主键数值,最好是引用类型而不是基本类型
		User user=session.get(User.class,new Integer(2));
		System.out.println(user);
		//打印时候为了美观,记得重写User类的toString方法
		session.close();
	}
	
	/*
	 * 更新操作
	 * */
	public static void updateUser() {
    
    
		Session session = null;
		Transaction tx = null;
		
		try {
    
    
			//1. 打开Session
			session=HibernateUtil.openSession();
			//2. 开启数据库事务
			tx = session.beginTransaction();
			//3. 更新操作(先查询,再修改,最后更新)
			User user=session.get(User.class, new Integer(2));
			user.setPassword("LiSi-2");
			session.update(user);
			//update方法更新时候,那条数据的所有项都更新了,哪怕没有变化
			session.save(user);
			
			//4. 提交事务
			tx.commit();
		} catch (Exception e) {
    
    
			//捕获异常,事务回滚
			tx.rollback();
		} finally {
    
    
			//5. 关闭Sesson,回收资源
			session.close();
		}
	}
	
	/*
	 * 删除操作
	 * */	
	public static void deleteUser() {
    
    
		Session session = null;
		Transaction tx = null;
		
		try {
    
    
			//1. 打开Session
			session=HibernateUtil.openSession();
			//2. 开启数据库事务
			tx = session.beginTransaction();
			//3.删除操作(先找到,再删除),实际删除的是数据库中的那条记录
			User user=session.get(User.class, new Integer(1));
			session.delete(user);			
			//4. 提交事务
			tx.commit();
		} catch (Exception e) {
    
    
			//捕获异常,事务回滚
			tx.rollback();
		} finally {
    
    
			//5. 关闭Sesson,回收资源
			session.close();
		}
	}
	
	
	
	
}

Single entity attribute mapping

Insert picture description here

If there are no corresponding get and set methods in the materialized class, the corresponding data will not be found and instantiation will not be possible. This is Hibernate's default method of accessing object properties
Insert picture description here

Mapping when entity class attributes and table fields are asymmetric

Insert picture description here

When you need to query indirect database data

Insert picture description here

For example, if the totalOrders attribute is added to the user table, you need to query the total amount of consumption in the order table.

First create the orders database table, orders, the attributes are:
Insert picture description here

Insert picture description here
Then add the totalPrice attribute to the user object, and set the corresponding get and set methods, and rewrite the construction method and toString method,
and add the corresponding attributes in the configuration file of the persistent class

Insert picture description here

Because the modification is the query operation, you can see the effect whenever you use the query operation in the test class.
Insert picture description here

Hibernate initialization

Insert picture description here
Insert picture description here

Single entity object identifier mapping

Insert picture description here

Natural components: For example, the student's student ID, which has certain practical significance.
The surrogate primary key method is more common.

Insert picture description here

Hibernate Object Identifier OID (Distinguish Object)

Insert picture description here

Help Hibernate distinguish whether these two objects are the same object in memory.

Insert picture description here
When U1 is inquired for the first time, there is no memory, it is a real query.
U2 will judge whether there is a result in the memory. Because U1=U2, U2 does not query and directly assigns U1

Insert picture description here
Because there are all reference types in the package, the wrapper type is used when defining the OID for convenience.

Because the primary key is unique, the OID is also unique.

OID configuration in the mapping file

Insert picture description here
generator specifies the method of OID generation

Hibernate comes with many identifier generators:

increment  采用 Hibernate 数值递增的方式;
identity 采用数据库提供的自增长方式;
assigned 主键由应用逻辑产生;
---------上面三种是重点

sequence 采用数据库提供的序列方式;
hilo 通过hi/lo算法   // Hibernate 5.0 以后不支持;,高低位算法
seqhilo 通过hi/lo算法;
native 自动选择合适的标识符生成器;
uuid.hex 通过uuid算法。

Applicable scope of increment identifier

Insert picture description here

Generated by Hibernate program;

Insert picture description here

First check the maximum value of the primary key of the database, the maximum value +1 is stored in the database new data.
There is a spliced ​​primary key in the SQL statement

Applicable scope of identity identifier

Insert picture description here

Insert picture description here

There is no ID field in the SQL statement, because the database can automatically increment the primary key

Scope of assigned identifier

The value is assigned by the program, and the value needs to be manually assigned before inserting. If the value is not assigned, the insert statement will not be executed.
This method is strongly not recommended, and human operations may be repeated.
Insert picture description here
Insert picture description here

Assign value inside the program

Annotation mapping single entity

When configuring annotation mapping, you only need to modify the materialized class instead of creating the configuration file of the materialized class.
Not recommended, because it is not beautiful and unclear, the focus is on the above XML configuration

Insert picture description here

@Entity:声明一个实体类。

@Table(name="table_name"):为实体类指定对应的数据库表。name就是表的名字

@Id:声明实体类的OID属性。

@GeneratedValue(generator="increment_generator"):声明OID的生成策略。

@GenericGenerator(name="increment_generator", strategy="increment"):使用Hibernate提供的生成策略。
先定义生成器,选择生存策略,然后被上面的注解调用。

What attribute is mapped, and what Column annotation is added
. It can also be omitted when the attribute name is consistent with the database field name
Insert picture description here

Configure the source of the mapping file

Insert picture description here

package com.hibernate.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
//声明一个实体类
@Table(name="CUSTOMER")
//为实体类指定对应的数据库


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;
	}
	
	
	@Id
	//定义生成策略与别名,注意位置,在get,set方法之上
	@GeneratedValue(generator = "linshi")
	//应用下面定义的策略
	@GenericGenerator(strategy="increment",name = "linshi")
	//私有属性的get set方法
	
//	@Column(name="id")  主键id自增长,所以可以注释掉
	public Integer getId() {
    
    
		return id;
	}
	public void setId(Integer id) {
    
    
		this.id = id;
	}
	@Column(name="name")
	public String getName() {
    
    
		return name;
	}
	public void setName(String name) {
    
    
		this.name = name;
	}
	@Column(name="age")
	public int getAge() {
    
    
		return age;
	}
	public void setAge(int age) {
    
    
		this.age = age;
	}
	
	
	
	
}

Insert picture description here

Insert picture description here

Insert picture description here

@Override
	public String toString() {
    
    
		return "Customer [sum=" + sum + "]";
	}


	@Formula(value="(select sum(o.age) from customer as o where o.id>10)")
	public int getSum() {
    
    
		return sum;
	}
	public void setSum(int sum) {
    
    
		this.sum = sum;
	}

Insert picture description here

Insert picture description here

Guess you like

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