一.简介
Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句,自动执行。
二.使用
1.点击File->New Project->选择java 勾选Web / Hibernate / Create default->next
2.修改Hibernate配置文件
此时IDEA会提示找不到这个类,我们在maven下添加mysql-connector.jar包
右击项目->open module setting->librarier +->form maven->添加包名-> ,,,,,,
3.与数据库进行关联
a.创建一个连接
b.新建一个实体类UserEntity.class
import javax.persistence.*;
@Entity
@Table(name = "test_user")
public class UserEntity {
@Id
@Column
@PrimaryKeyJoinColumn
private String username;
@Column
private String password;
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;
}
}c.在配置文件中添加映射<mapping class="hibernate.UserEntity"/>d.添加测试类import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import org.junit.After;
import org.junit.Before;import org.junit.Test;
public class TestUtil {
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
@Before
public void init(){
//5.x以后
//创建服务注册对象
ServiceRegistry serviceRegistry = new
StandardServiceRegistryBuilder().configure().build();
//创建会话工厂对象
sessionFactory = new
MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
//会话对象
session = sessionFactory.openSession();
//开启事物
transaction = session.beginTransaction();
}
@Test
public void test(){
// 生成专业对象
UserEntity userEntity = new UserEntity();
userEntity.setUsername("wdl");
userEntity.setPassword("123456");
// 保存对象进入数据库
session.save(userEntity);
}
@After
public void destory(){
//8. 提交事务
transaction.commit();
//9. 关闭会话
session.close();
//10. 关闭会话工厂
sessionFactory.close();
}
}运行测试