Hibernate是ssh框架中的数据库部分,它采用的是ORM的思想即通过操作实体类对象去操作数据库。
PART_ONE:
记录下配置Hibernate的步骤:
1.下载Hibernate的jar包
这个可以自行到Hibernate官网中下载最新完整jar包
image.png
2.编写需要操作的实体类,我这里是客户类(Customer.class)
Customer.class:
public class Customer implements Serializable{
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private String gender;
private Integer age;
private String level;
private Set<Order> orders = new HashSet<Order>();
private Set<Role> roles = new HashSet<Role>();
private Card card;
public Card getCard() {
return card;
}
public void setCard(Card card) {
this.card = card;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public Set<Order> getOrders() {
return orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", gender=" + gender
+ ", age=" + age + ", level=" + level + "]";
}
}
3.创建客户类对应的hibernte对应数据库信息的xml(Customer.hbm.xml),这个文件与实体类处于同一位置下。
Customer.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="caixiaohao.entiy"> <!--所在类的包位置-->
<class name="Customer" table="t_customer">
<id name="id" column="c_id">
<generator class="native"></generator>
</id>
<property name="name" column="c_name"></property>
<property name="gender" column="c_gender"></property>
<property name="age" column="c_age"></property>
<property name="level" column="c_level"></property>
<!--一对多配置-->
<set name="orders">
<key column="cust_id"></key>
<one-to-many class="Order"/>
</set>
<!--多对多关系配置-->
<set name="roles" table="t_user_roles">
<key column="user_id"></key>
<many-to-many class="Role" column="role_id"></many-to-many>
</set>
<!--一对一配置-->
<one-to-one name="card" class="Card"></one-to-one>
</class>
</hibernate-mapping>
4.创建Hibernate的核心配置文件(hibernate.cfg.xml),这个文件放置在项目的src下。
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>
<!-- 1.连接数据库参数 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatelearn</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<!-- Hibernate整合c3p0 -->
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!-- c3p0详细配置 -->
<property name="c3p0.min_size">10</property>
<property name="c3p0.max_size">20</property>
<!-- hibernate方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 2.hibernate扩展参数 -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- *.hbm.xml文件 -->
<mapping resource="caixiaohao/entiy/Customer.hbm.xml"/>
<mapping resource="caixiaohao/entiy/Order.hbm.xml"/>
<mapping resource="caixiaohao/entiy/Role.hbm.xml"/>
<mapping resource="caixiaohao/entiy/Card.hbm.xml"/>
</session-factory>
</hibernate-configuration>
5.将初始化的工作写成一个Hibernate的工具类(HibernateUtil.class)
HibernateUtil.class:
package Util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
public static Configuration cfg = null;
public static SessionFactory factory = null;
static {
cfg = new Configuration();
cfg.configure();
factory = cfg.buildSessionFactory();
}
public static Session getSession() {
return factory.openSession();
}
}
6.可以进行对数据库的操作,在test类中测试。
@Test
public void testSaveOrder() {
Customer test = new Customer();
test.setName("我是个测试);
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
session.save(test);
tx.commit();
session.close();
}
PART_TWO:
对数据进行CRUD的操作,Hibernate提供了三种方式分别是Hql,criteria,Sql.
Hql方式的演示:
package doTest;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.jupiter.api.Test;
import Util.HibernateUtil;
import caixiaohao.entiy.Customer;
public class HqlTest {
//全表查询
@Test
public void test1() {
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("from Customer");
List<Customer> customers = query.list();
for(Customer c : customers) {
System.out.println(c);
}
tx.commit();
session.close();
}
//条件查询
@Test
public void test2() {
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("from Customer where c_name like '%胖%' ");
List<Customer> customers = query.list();
for(Customer c : customers) {
System.out.println(c);
}
tx.commit();
session.close();
}
//条件查询2
@Test
public void test3() {
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("from Customer where c_name like ? ");
query.setParameter(0, "%胖%");
List<Customer> customers = query.list();
for(Customer c : customers) {
System.out.println(c);
}
tx.commit();
session.close();
}
//条件查询3
@Test
public void test4() {
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("from Customer where c_name like :name ");
query.setParameter("name", "%豪%");
List<Customer> customers = query.list();
for(Customer c : customers) {
System.out.println(c);
}
tx.commit();
session.close();
}
//分页查询
@Test
public void test5() {
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("from Customer");
query.setFirstResult(0);
query.setMaxResults(4);
List<Customer> customers = query.list();
for(Customer c : customers) {
System.out.println(c);
}
tx.commit();
session.close();
}
//聚合查询
@Test
public void test6() {
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("select count(*) from Customer");
Long count = (Long) query.uniqueResult();
System.out.println(count);
// List<Customer> customers = query.list();
// for(Customer c : customers) {
// System.out.println(c);
// }
tx.commit();
session.close();
}
//投影查询
@Test
public void test7() {
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("select name from Customer");
List<Object[]> customers = query.list();
for(Object c : customers) {
System.out.println(c);
}
tx.commit();
session.close();
}
}
Criteria演示:
package doTest;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.junit.jupiter.api.Test;
import Util.HibernateUtil;
import caixiaohao.entiy.Customer;
public class CriteriaTest {
//全表查询
@Test
public void test1() {
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
Criteria ce = session.createCriteria(Customer.class);
List<Customer> list = ce.list();
for (Customer customer : list) {
System.out.println(customer);
}
tx.commit();
session.close();
}
//条件查询
@Test
public void test2() {
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
Criteria ce = session.createCriteria(Customer.class);
ce.add(Restrictions.like("name", "%胖%"));
List<Customer> list = ce.list();
for (Customer customer : list) {
System.out.println(customer);
}
tx.commit();
session.close();
}
//分页查询
@Test
public void test3() {
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
Criteria ce = session.createCriteria(Customer.class);
ce.setFirstResult(2);
ce.setMaxResults(3);
List<Customer> list = ce.list();
for (Customer customer : list) {
System.out.println(customer);
}
tx.commit();
session.close();
}
//聚合查询
@Test
public void test4() {
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
Criteria ce = session.createCriteria(Customer.class);
ce.setProjection(Projections.count("id"));
Integer count = (Integer)ce.uniqueResult();
System.out.println(count);
// List<Customer> list = ce.list();
// for (Customer customer : list) {
// System.out.println(customer);
// }
tx.commit();
session.close();
}
//投影查询
@Test
public void test5() {
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
Criteria ce = session.createCriteria(Customer.class);
ProjectionList plist = Projections.projectionList();
plist.add(Property.forName("id"));
plist.add(Property.forName("name"));
ce.setProjection(plist);
List<Object[]> list = ce.list();
for(Object[] objects : list) {
for(Object object : objects ) {
System.out.println(object);
}
}
tx.commit();
session.close();
}
}
Sql方式的演示:
package doTest;
import java.util.List;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.jupiter.api.Test;
import Util.HibernateUtil;
public class SqlTest {
@Test
public void test1() {
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
SQLQuery sqlQuery = session.createSQLQuery("select * from t_order");
List<Object[]> list = sqlQuery.list();
for (Object[] objects : list) {
for (Object object : objects) {
System.out.print(object + "\t");
}
System.out.println();
}
tx.commit();
session.close();
}
}
PART_THREE
Hibernate整合C3P0:
1.在下好的Hibernate的jar中有C3P0的依赖jar
image.png
2.在hibernat.cfg.xml加入C3P0的配置
<!-- Hibernate整合c3p0 -->
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!-- c3p0详细配置 -->
<property name="c3p0.min_size">10</property>
<property name="c3p0.max_size">20</property>
3.测试C3P0
package doTest;
import java.sql.Connection;
import java.sql.SQLException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.jdbc.Work;
import Util.HibernateUtil;
import caixiaohao.entiy.Customer;
import caixiaohao.entiy.Order;
public class test {
public static void main(String[] args) {
Session session = HibernateUtil.getSession();
session.doWork(new Work(){
@Override
public void execute(Connection connection) throws SQLException {
System.out.println(connection);
}
});
session.close();
}
}
结果
image.png
PART_FOUR
hibernate的配置就到此,它还有相关概念需要自行去深入了解,例如一级缓存,二级缓存,快照,session的瞬时态,持久态,脱管态,lazy加载还有其注释的方式去进行配置等等。
网友评论