当前位置 : 主页 > 编程语言 > c++ >

Hibernate持久化框架的基本使用方法(基本开发步骤)

来源:互联网 收集:自由互联 发布时间:2021-07-03
1.创建Hibernate配置文件hibernate.cfg.xml root 968886 com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/login org.hibernate.dialect.MySQLInnoDBDialect true true update 2.创建一个持久化类News import java.util.Date;public class N
1.创建Hibernate配置文件hibernate.cfg.xml
 


 
    
   
    
   
    root
    
   
    968886
    
   
    com.mysql.jdbc.Driver
    
   
    jdbc:mysql://localhost:3306/login
    
    
    
   
    org.hibernate.dialect.MySQLInnoDBDialect
    
    
   
    true
    
    
   
    true
    
    
   
    update
    
    
    
  

 
2.创建一个持久化类News
import java.util.Date;

public class News {
	private String author;
	private String title;
	private int id;
	private Date date;
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public Date getDate() {
		return date;
	}
	public void setDate(Date date) {
		this.date = date;
	}
	public News(String author, String title, Date date) {
		super();
		this.author = author;
		this.title = title;
		this.date = date;
	}
	@Override
	public String toString() {
		return "News [author=" + author + ", title=" + title + ", id=" + id + ", date=" + date + "]";
	}
	public News() {
		super();
	}
	
	
}
3.创建对象-关系映射文件News.hbm.xml
 


 

 
    
   
    
     
     
     
    
    
     
    
    
     
    
    
     
    
  

 
4.通过HibernateAPI编写访问数据库的代码
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class Main {
	
	public static void main(String[] args) {
		
		//1.创建一个SessionFactory对象
		SessionFactory sessionFactory=null;
		
		//1).创建Configuration对象:对应hibernate的基本配置信息和 对象映射信息
		Configuration configuration=new Configuration().configure();
		//2).创建一个ServiceRegistry;hibernate的任何配置和服务都需要在该对象上注册后才有效
		//这个创建方法是hibernate5.02版本以前的创建方式,5.02以后的的创建方法不是这个
		ServiceRegistry serviceRegistry=new ServiceRegistryBuilder()
						.applySettings(configuration.getProperties()).buildServiceRegistry();
		sessionFactory=configuration.buildSessionFactory(serviceRegistry);
		//2.创建一个Session
		Session session=sessionFactory.openSession();
		//3.开启事务
		Transaction transaction=session.beginTransaction();
		//4.执行保存操作
		News news=new News("zsl","Java",new Date(new java.util.Date().getTime()));
		session.save(news);
		
		//5.提交事务
		transaction.commit();
		//6.关闭session
		session.close();
		//7.关闭SessionFactory
		sessionFactory.close();
	}
	
}
网友评论