简单hibernate5.2.10入门配置

1、官网下载hibernate 5相关jar包

http://hibernate.org/orm/

2、解压后,在lib目录中找到required目录下的jar包添加至项目。再添加数据库驱动包,博主用MySQL

jar包添加后如下图:

简单hibernate5.2.10入门配置_第1张图片

3、创建数据库learndata、创建表userinfo,下面给出建表语句:

CREATE TABLE `NewTable` (
`id`  int NULL AUTO_INCREMENT ,
`username`  varchar(50) NULL ,
`password`  varchar(50) NULL ,
PRIMARY KEY (`id`)
);

4、编写实体类对象

package model;

public class Userinfo {

	private int id;
	private String username;
	private String password;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}
5、编写映射文件



6、编写hibernate配置文件



com.mysql.jdbc.Driverjdbc:mysql://localhost:3306/learndatarootroot
      5
      50 
      23 
      org.hibernate.dialect.MySQL5Dialect
      thread
      true
      update
      
7、编写测试Java文件
package action;

import model.Userinfo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Test {

	public static void main(String[] args) {
//		配置方法一
//		final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
//	    SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
		
//		配置方法二
		Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
		SessionFactory sessionFactory = cfg.buildSessionFactory();

	    Session session = sessionFactory.openSession();
	    Transaction transaction = session.beginTransaction();
	    Userinfo user = new Userinfo();
	    user.setUsername("root");
	    user.setPassword("123456");
	    session.save(user);
	    transaction.commit();
	}
}
8、测试运行结果


9、异常总结
按照上面步骤,如果代码session.beginTransaction();报错,检查自己项目的jdk版本,hibernate5最好用jdk8,原因可以看http://blog.csdn.net/supegan1989/article/details/72862097


你可能感兴趣的:(hibernate,J2EE)