上一节我们已经简单使用了一下hibernate的插入功能了。这一节我们再来使用一下hibernate的增删改查功能,还有用注解的方式来使用hibernate。
首先我们把上一节的工程拷贝复制一份称为hibernate2,首先我们先把上一节中添加操作中的代码抽取出来
建立一个HibernateUtil 类,如下:
package com.test.hibernate.common;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
Configuration configuration = new Configuration().configure();
StandardServiceRegistry standardServiceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
return configuration.buildSessionFactory(standardServiceRegistry);
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
这样以后我们写代码就不用每次都重复那些代码了,当然还是会有些代码的,到了以后和spring集成就可以省很多代码,这个等我把这个系列更新完后再介绍给大家。
这样以后我们的CRUD代码就如下了。
package com.test.hibernate.test;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Test;
import com.test.hibernate.common.HibernateUtil;
import com.test.hibernate.model.Student;
public class Test1 {
@Test
public void testAdd() {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Student student = new Student();
student.setName("test1");
student.setEmail("test1@163.com");
session.save(student);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
@Test
public void testGet() {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Student student = (Student) session.get(Student.class,
Integer.valueOf(4));//取id为4的记录。
System.out.println(student);
session.close();
sessionFactory.close();
}
@Test
public void testUpdate() {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Student student = (Student) session.get(Student.class,
Integer.valueOf(4));
session.beginTransaction();
System.out.println("before update ");
System.out.println(student);
student.setName("testUpdate");
session.update(student);
session.getTransaction().commit();
student = (Student) session.get(Student.class, Integer.valueOf(4));
System.out.println("after update");
System.out.println(student);
session.close();
sessionFactory.close();
}
@Test
public void testDelete() {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Student student = (Student) session.get(Student.class,
Integer.valueOf(5));
session.delete(student);
session.getTransaction().commit();
}
@Test
public void testGetAll() {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
String hql = "from Student";<span style="white-space:pre"> </span>//hql 面向对象的语句
Query query = (Query) session.createQuery(hql);
@SuppressWarnings("unchecked")
List<Student> students = query.list();
students.stream().forEach(System.out::println);
}
}
下面我们来熟悉一下hibernate的注解。
新建一个类
package com.test.hibernate.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
</pre><pre name="code" class="java">//利用@Entity 标注此类为一个实体类。@Table 指定表名。
@Entity
@Table(name="employee")
public class Employee {
private int id;
private String name;
private String email;
//@Id 标注为主键,GenerateValue主键生成方式,下一节我们将会介绍
@Id
@GeneratedValue(generator="_native")
@GenericGenerator(name="_native",strategy="native")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", email=" + email
+ "]";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/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</property>
<property name="connection.username">root</property>
<property name="connection.password">engine</property>
<!--方言 -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 控制台输出 -->
<property name="show_sql">true</property>
<!-- 自动更新表结构 其实比比较少用 -->
<property name="hbm2ddl.auto">update</property>
<!-- 映射文件 -->
<mapping resource="com/test/hibernate/model/Student.hbm.xml" />
<mapping class="com.test.hibernate.model.Employee"/> <!-- 配置扫描注解的类-->
</session-factory>
</hibernate-configuration>
现在我们就可以写一个测试类来测试一下了
package com.test.hibernate.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Test;
import com.test.hibernate.common.HibernateUtil;
import com.test.hibernate.model.Employee;
public class EmployeeAnnotationTest {
@Test
public void testAdd() {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Employee employee = new Employee();
employee.setName("Tom");
employee.setEmail("tom@163.com");
session.save(employee);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
}
运行结果就是在数据库中多了一张表,并且多了一条记录。
这一节我们就先讲这么多吧,下一节我将带大家详细的了解hibernate中对象的引用关系。
最后附上工程的目录结构