1、首先配置hibernate.cfg.xml和Student.hbm.xml
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>
<!-- 连接数据库的基本参数 -->
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<!-- <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/student</property> -->
<!-- 由于是本地的,所以上面的可以简写成下面的形式 -->
<property name="hibernate.connection.url">jdbc:mysql:///student</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1234</property>
<!-- 配置hibernate的方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 可选内容如下 -->
<!-- 打印sql -->
<property name="hibernate.show_sql">true</property>
<!-- 格式化sql -->
<property name="hibernate.format_sql">true</property>
<!--自动创建表,值:none, create/如果已有,删除、重建(多测试用),
create-drop/与前类似,但最后(sessionFactory.close();之后)删除(多测试用),
常用后两个:update/更新(有则更新/包括表结构,无则创建), validate(效验/只使用原表,不创建)-->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 配置C3P0连接池 -->
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!--在连接池中可用的数据库连接的最少数目 -->
<property name="c3p0.min_size">5</property>
<!--在连接池中所有数据库连接的最大数目 -->
<property name="c3p0.max_size">20</property>
<!--设定数据库连接的过期时间,以秒为单位,
如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 -->
<property name="c3p0.timeout">120</property>
<!--每3000秒检查所有连接池中的空闲连接 以秒为单位-->
<property name="c3p0.idle_test_period">3000</property>
<!-- 设置事务隔离级别 1/2/4/8-->
<property name="hibernate.connection.isolation">4</property>
<!-- 配置当前线程绑定的Session -->
<property name="hibernate.current_session_context_class">thread</property>
<!--<mapping resource="hibernate.properties" />
属性文件的方式不能引入映射文件(手动编写代码加载映射文件)
-->
<!-- 引入映射文件(必须的),要在最下面? -->
<mapping resource="com/fengya/domain/Student.hbm.xml" />
</session-factory>
</hibernate-configuration>
Student.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>
<!-- 建立类与表的映射/ catalog :数据库名 -->
<class name="com.fengya.domain.Student" table="t_stu" catalog="student">
<!-- 建立类中的属性(Student中的sid属性)与表中的主键(t_stu中的sid字段)对应 -->
<id name="sid" column="sid">
<!-- 主键生成策略 -->
<generator class="native" />
</id>
<!-- 建立类中的普通的属性和表的字段的对应 -->
<property name="sname" column="sname" />
<property name="gender" column="gender" />
<property name="phone" column="phone" />
<property name="birthday" column="birthday" />
<property name="hobby" column="hobby" />
<property name="info" column="info" />
</class>
</hibernate-mapping>
代码实现主要在StudentDaoImpl中(应该还可优化一下代码):
package com.fengya.daoImp;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import com.fengya.dao.StudentDao;
import com.fengya.domain.Student;
import com.fengya.util.HibernateUtils;
import com.fengya.util.TestUtils;
@SuppressWarnings("unchecked")
public class StudentDaoImp implements StudentDao {
@Override
public List<Student> findAll() throws SQLException {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
Query<Student> query = session.createQuery("from Student");
List<Student> list = query.list();
tx.commit();
return list;
}
@Override
public void addStudent(Student s) throws SQLException {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
session.save(s);
tx.commit();
}
@Override
public void delStudent(int sid) throws SQLException {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
//method1直接创建,删除
/* Customer customer = new Customer();
customer.setCust_id(3L);
session.delete(customer);*/
//method2先查询,再删除(推荐)--可以级联删除,比如:删除客户的同时可以删除客户名下的订单。
Student student = session.get(Student.class, sid);
session.delete(student);
tx.commit();
}
@Override
public Student findStudentById(int sid) throws SQLException {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
//使用get方法查询
Student student = session.get(Student.class, sid);
tx.commit();
return student;
}
@Override
public void update(Student s) throws SQLException {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
session.update(s);
tx.commit();
}
@Override
public List<Student> searchStudent(String name, String gender) throws SQLException {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
String hql = "from Student where 1=1 ";// 记住是类名,不是表名!!!
if (!TestUtils.isEmpty(name)) {
hql = hql + "and sname like " + "'%" + name + "%'";//一定要注意单引号的问题!
}
if (!TestUtils.isEmpty(gender)) {
hql = hql + " and gender = '" + gender + "'";//一定要注意单引号的问题!
}
System.out.println("hql = " + hql);
// 分页查询,
Query<Student> query = session.createQuery(hql);
List<Student> list = query.list();
tx.commit();
return list;
}
@Override
public List<Student> findStudentByPage(int currentPage) throws SQLException {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
// 记住是类名,不是表名!!!
String hql = "from Student";
Query<Student> query = session.createQuery(hql);
// 分页查询,设置
query.setFirstResult((currentPage-1)*PAGE_SIZE);
query.setMaxResults(PAGE_SIZE);
List<Student> list = query.list();//list.size() = 5,这里是 * 条件 * 查询的结果
tx.commit();
return list;
}
@Override
public int findCount() throws SQLException {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
String hql = "from Student";
// String hql = "select count(*) from Student";//不能这么用!!!这里被坑了好久。。。
Query<Student> query = session.createQuery(hql);
List<Student> list = query.list();//list.size() = 30,这里是 * 全部 * 查询的结果
tx.commit();
return list.size();
}
}