Hibernate

Hibernate是一种ORM框架,全称为 Object_Relative DateBase-Mapping,在Java对象与关系数据库之间建立某种映射,以实现直接存取Java对象!

O代表的是Objcet
R代表的是Relative
M代表的是Mapping

Hibernate_第1张图片

当插入数据的时候,就将JavaBean对象拆分,拼装成SQL语句
当查询数据的时候,用SQL把数据库表中的列组合,拼装成JavaBean对象

也就是说:javaBean对象和数据表中的列存在映射关系!如果程序能够自动生成SQL语句就好了…那么Hibernate就实现了这个功能!

简单来说:我们使用Hibernate框架就不用我们写很多繁琐的SQL语句,从而简化我们的开发。

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

@Entity
@Table(name="student")
public class Student {
	
	@Id
	@Column(name="id")
	private int id;
	
	@Column(name="first_Name")
	private String firstName;
	
	@Column(name="last_Name")
	private String lastName;
	@Column(name="email")
	private String email;
	public Student() {
		
	}
	public Student(String firstName, String lastName, String email) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		this.email = email;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
	}
	
}
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.luv2code.hibernate.demo.entity.Student;
public class CreateStudentDemo {

	public static void main(String[] args) {
		//create session factory
		SessionFactory factory = new Configuration()
				.configure("hibernate.cfg.xml")
				.addAnnotatedClass(Student.class)
				.buildSessionFactory();
		//create session		
		Session session = factory.getCurrentSession();
		try {
			// use the session object to save java object
			System.out.println("Creating new student obj...");
			Student tempStudent = new Student("Vin","WAll","Vin@163");
			//create a student object
			session.beginTransaction();
			//start a transaction
			System.out.println("Saving the Student...");
			session.save(tempStudent);
			//commit transaction
			session.getTransaction().commit();
			System.out.println("Done");		
		}
		finally {
			factory.close();
		}
		
	}

}

Hibernate_第2张图片

SessionFactory

SessionFactory–>Session的工厂,也可以说代表了hibernate.cfg.xml这个文件…hibernate.cfg.xml的就有这么一个节点
openSession方法:创建一个Session对象
getCurrentSession方法:创建Session对象或取出Session对象

Session

Session是Hibernate最重要的对象,Session维护了一个连接(Connection),只要使用Hibernate操作数据库,都需要用到Session对象

Reference:

https://www.cnblogs.com/mq0036/p/8522150.html

你可能感兴趣的:(JAVA)