Hibernate第一个程序

定义持久化类

持久化类也叫实体类,是用来存储要与数据库交互的数据。持久化类的实例称为持久化对象(Persistent Object,PO),其作用是完成对象持久化操作。简单地说,通过PO可以用面向对象的方式操作数据库,实现数据增、删、改操作。

Student.java

package FirstProgram;

public class Student {
	
	private Long id;
	private long studentNo;
	private String studentName;
	private int sage;
	private String major;
	
	public Student() {}
	public Student(long studentNo, String studentName, int sage, String major) {
		super();
		this.studentNo = studentNo;
		this.studentName = studentName;
		this.sage = sage;
		this.major = major;
	}
	
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public long getStudentNo() {
		return studentNo;
	}
	public void setStudentNo(long studentNo) {
		this.studentNo = studentNo;
	}
	public String getStudentName() {
		return studentName;
	}
	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}
	public int getSage() {
		return sage;
	}
	public void setSage(int sage) {
		this.sage = sage;
	}
	public String getMajor() {
		return major;
	}
	public void setMajor(String major) {
		this.major = major;
	}
}


定义映射文件

Student.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">

<hibernate-mapping package="FirstProgram">
	<class name="Student" table="student" >
		<id name="id" column="id">
			<generator class="identity"/>
		</id>
		<property name="studentNo" type="long" column="student_no"/>
		<property name="studentName" type="string" column="student_name"/>
		<property name="sage" type="integer" column="sage"/>
		<property name="major" type="string" column="major"/>
	
	</class>
</hibernate-mapping>


编写配置文件

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="connection.driver_class">
			com.mysql.jdbc.Driver</property>
		<property name="connection.url">
			jdbc:mysql://localhost:3306/hibernate??useUnicode=true&characterEncoding=utf-8</property>
		<property name="connection.username">root</property>
		<property name="connection.password">Cham</property>
		<!-- 指定JDBC连接池(use the built-in) -->
		<property name="connection.pool_size">1</property>
		<!-- 指定SQL方言 -->
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<!-- 打开Hibernate自动会话上下文管理 -->
		<property name="current_session_context_class">thread</property>
		<!-- 关闭二级缓存 -->
		<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
		<!-- 指定将所有执行的SQL语句回显到stdout -->
		<property name="show_sql">true</property>
		<!-- 指定在启动时对表进行更新 -->
		<property name="hibernate.hbm2ddl.auto">update</property>
		<!-- 指定映射文件,若有多个映射文件,使用多个mapping元素指定 -->
		<mapping resource="FirstProgram/Student.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

测试程序

Main.java

package FirstProgram;

import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
//import org.hibernate.service.ServiceRegistryBuilder;  版本4
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;	//版本5
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
import FirstProgram.Student;

public class Main {

	public static void main(String[] args) {
		//加载配置文件hibernate	.cfg.xml
		Configuration configuration = new Configuration().configure();
		
		configuration.addClass(Student.class);	//版本5中需增加该方法,否则无法找到实体类
		
		//创建服务注册对象
		/*ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
			.applySettings(configuration.getProperties()).buildServiceRegistry();	版本4		*/
		
		ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
			.applySettings(configuration.getProperties()).build();		//版本5
		
		//创建会话工厂对象
		SessionFactory factory =configuration.buildSessionFactory(serviceRegistry);
		//创建会话对象
		Session session = factory.openSession();
		//创建一个事务对象
		Transaction tx = session.beginTransaction();
		Student student = new Student();
		student.setStudentNo(20170707);
		student.setStudentName("王小明");
		student.setSage(20);
		student.setMajor("计算机科学");
		session.save(student);		//将student对象持久化到数据表中
		System.out.println("插入学生成功!");
		//从数据库中读取一个对象
		Student stud = session.get(Student.class, new Long(1));
		System.out.println(stud.getStudentName()+" "+stud.getSage());
		tx.commit();		//提交事务
		session.close();
		factory.close();	
	}
}

结果





使用HibernateUtil辅助类

HibernateUtil.java

package util;

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

import FirstProgram.Student;


public class HibernateUtil {

	private static SessionFactory factory;
	private static ServiceRegistry serviceRegistry;
	static{
		try{
			Configuration configuration = new Configuration().configure();
			
			configuration.addClass(Student.class);
			
			serviceRegistry = new StandardServiceRegistryBuilder()
				.applySettings(configuration.getProperties()).build();
			factory = configuration.buildSessionFactory(serviceRegistry);
		}catch(HibernateException e){
			e.printStackTrace();
		}
	}
	//返回会话工厂对象
	public static SessionFactory getSessionFactory(){
		return factory;
	}
	//返回一个会话对象
	public static Session getSession(){
		Session session = null;
		if(factory!=null)
			session = factory.openSession();
		return session;
	}
	//关闭指定的会话对象
	public static void closeSession(Session session){
		if(session!=null){
			if(session.isOpen())
				session.close();
		}
	}
}

测试

StudentDemo.java

package FirstProgram;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import util.HibernateUtil;


public class StudentDemo {

	public static void main(String[] args) {
		
		try{
			Session session = HibernateUtil.getSession();
			Transaction tx = session.beginTransaction();
			Student student = session.get(Student.class, new Long(1));
			student.setStudentName("王晓明");
			session.update(student);
			tx.commit();
			session.close();
		}catch(HibernateException he){
			he.printStackTrace();
		}
		
		try{
			Session session = HibernateUtil.getSession();
			Transaction tx = session.beginTransaction();
			//创建查询对象
			Query query = session.createQuery("from Student s");
			List<Student> students = query.list();
			for(int i=0;i<students.size();i++){
				Student student = students.get(i);
				System.out.println("学号:"+student.getStudentNo()+
						"\t姓名:"+student.getStudentName()+
						"\t年龄:"+student.getSage()+
						"\t专业:"+student.getMajor());
			}
			tx.commit();
			session.close();
		}catch(HibernateException he){
			he.printStackTrace();
		}
		
	}
}

结果





文件位置及JAR包




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值