小试Hibernate
maven下的hibernate
pom.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wanmait</groupId>
<artifactId>hibernateDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>hibernateDemo Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--注入灵魂-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
<!--mysql连接-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<finalName>hibernateDemo</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="dialect">
<!--方言翻译处Hhhhhh,例如用的是Oracle数据库的话改为OracleDialect-->
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.password">123456</property>
<property name="connection.username">root</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/hospital?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
</property>
<!--注册一下驱动呗-->
<property name="connection.driver_class">
com.mysql.cj.jdbc.Driver
</property>
<!--是否在控制台上显示sql语句-->
<property name="show_sql">true</property>
<!--打印的sql语句按梯形进行显示-->
<property name="format_sql">true</property>
<property name="current_session_context_class">thread</property>
<!--注册映射文件-->
<mapping resource="mapping/Doctor.hbm.xml"/>
</session-factory>
</hibernate-configuration>
HibernateSessionFactory util类
package com.wanmait.demo.util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateSessionFactory {
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
private static ServiceRegistry serviceRegistry;
static {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
映射文件
<?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">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.wanmait.hibernate.pojo.Doctor" table="doctor">
<!--标识属性-->
<id name="id" type="java.lang.Integer">
<column name="id"/>
<!--主键的生成方式 identity表示自增长 native表示按着数据库底层的生成方式来决定属性的生成方式-->
<generator class="identity"/>
</id>
<property name="name" type="java.lang.String">
<column name="name" length="20"/>
</property>
<!-- <property name="department" type="com.wanmait.hibernate.pojo.Department">
<column name="department_id" length=""
</property>-->
<!--insert="false"表示有默认值 添加时不用管该属性-->
<property name="scope" type="java.lang.String">
<column name="scope" length="50"/>
</property>
<property name="info" type="java.lang.String">
<column name="info" length="100"/>
</property>
<property name="visible" type="java.lang.Boolean" insert="false">
<column name="visible" />
</property>
</class>
</hibernate-mapping>
Doctor.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">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.wanmait.hibernate.pojo.Doctor" table="doctor">
<!--标识属性-->
<id name="id" type="java.lang.Integer">
<column name="id"/>
<!--主键的生成方式 identity表示自增长 native表示按着数据库底层的生成方式来决定属性的生成方式-->
<generator class="identity"/>
</id>
<property name="name" type="java.lang.String">
<column name="name" length="20"/>
</property>
<!-- <property name="department" type="com.wanmait.hibernate.pojo.Department">
<column name="department_id" length=""
</property>-->
<!--insert="false"表示有默认值 添加时不用管该属性-->
<property name="scope" type="java.lang.String">
<column name="scope" length="50"/>
</property>
<property name="info" type="java.lang.String">
<column name="info" length="100"/>
</property>
<property name="visible" type="java.lang.Boolean" insert="false">
<column name="visible" />
</property>
</class>
</hibernate-mapping>
DoctorDAO
package com.wanmait.hibernate.dao;
import com.wanmait.hibernate.pojo.Doctor;
import com.wanmait.hibernate.util.HibernateSessionFactory;
import org.hibernate.Query;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.List;
public class DoctorDAO {
/*默认查全部*/
public List<Doctor> findAll()
{
List<Doctor> doctors = null;
Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
session.beginTransaction();
/*Doctor为类名,visible为属性名,区分大小写*/
/*String hql = "from Doctor where visible=true";*/
/*String hql = "from Doctor d where d.visible=true";*/
String hql = "select d from Doctor d where d.visible=true";
/*创建查询语句*/
Query query = session.createQuery(hql);
/*执行查询*/
doctors = query.list();
session.getTransaction().commit();
return doctors;
}
/*模糊查询*/
public List<Doctor> findByLike(String s)
{
List<Doctor>doctors = null;
Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
session.beginTransaction();
String hql = "from Doctor where visible=true and info like :info";
Query query = session.createQuery(hql);
query.setString("info","%"+s+"%");
doctors = query.list();
session.getTransaction().commit();
return doctors;
}
/*只查想要的几列数据*/
public List<Doctor> findAll2()
{
List<Doctor>doctors = null;
Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
session.beginTransaction();
/*异常:org.hibernate.hql.ast.QuerySyntaxException: Unable to locate appropriate constructor on class xxx*/
/*pojo中构造方法*/
String hql= "select new Doctor(name,visible) from Doctor where visible=true";
Query query = session.createQuery(hql);
doctors = query.list();
session.getTransaction().commit();
return doctors;
}
/*分页*/
public List<Doctor> findAll(Integer pageSize,Integer pageNum)
{
List<Doctor>doctors = null;
Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
session.beginTransaction();
String hql = "from Doctor where visible=true order by id desc";
Query query = session.createQuery(hql);
/*设置从第几条开始查询*/
query.setFirstResult((pageNum-1)*pageSize);
/*设置查询条数*/
query.setMaxResults(pageSize);
doctors = query.list();
session.getTransaction().commit();
return doctors;
}
/*查询数据总数*/
public Integer findDataCount()
{
Integer i = null;
Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
session.beginTransaction();
String hql = "select count(*) from Doctor where visible=true";
Query query = session.createQuery(hql);
//查询结果最多只能有一条数据 如果能查询出来多条数据会报异常
i = ((Long) query.uniqueResult()).intValue();
session.getTransaction().commit();
return i;
}
/*分组查询*/
public void findGroup()
{
Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
session.beginTransaction();
String hql = "select visible,count(*) from Doctor group by visible";
Query query = session.createQuery(hql);
ScrollableResults rs = query.scroll();
while (rs.next())
{
System.out.println(rs.get(0));
System.out.println(rs.get(1));
System.out.println("======================");
}
session.getTransaction().commit();
}
/*单个参数查询*/
public Doctor findById(Integer id)
{
Doctor doctor = null;
Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
session.beginTransaction();
doctor =(Doctor) session.get(Doctor.class,id);
session.getTransaction().commit();
return doctor;
}
/*增加一条新数据1*/
public void insert(Doctor doctor)
{
//打开session
//需要在hibernate.cfg.xml配置文件中添加属性current_session_context_class为thread
//通过getCurrentSession()获得的session 增删改查都需要加事务处理
//事务结束自动关闭session
Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
/*开始事务*/
Transaction transaction = null;
transaction = session.beginTransaction();
session.save(doctor);
/*提交事务*/
transaction.commit();
}
/*增加一条新数据2*/
public void insert2(Doctor doctor)
{
/*打开session*/
Session session = HibernateSessionFactory.getSession();
/*通过openSession()方法获得的session,增删改都需要加事务处理,查询不需要事务处理*/
/*开始事务*/
Transaction transaction = null;
transaction = session.beginTransaction();
session.save(doctor);
/*提交事务*/
transaction.commit();
/*关闭session*/
HibernateSessionFactory.closeSession();
}
/*更新数据*/
public void update(Doctor doctor)
{
Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
/*开始事务*/
Transaction transaction = null;
transaction = session.beginTransaction();
session.update(doctor);
/*提交事务*/
transaction.commit();
}
/*假删除*/
public void deleteFalse(Integer id)
{
Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
/*开始事务*/
Transaction transaction = session.beginTransaction();
/*修改和删除也可以使用query*/
/*String hql = "delete from Doctor where id=:id";*/
String hql = "update Doctor set visible=false where id=:id";
Query query = session.createQuery(hql);
query.setInteger("id",id);
query.executeUpdate();
/*提交事务*/
transaction.commit();
}
/*真删除*/
// 传进来的对象如果只设置id,不设置非空属性会报异常
public void delete(Doctor doctor)
{
Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
/*开始事务*/
Transaction transaction = session.beginTransaction();
session.delete(doctor);
/*提交事务*/
transaction.commit();
}
}
test
package com.wanmait.hibernate.dao.test;
import com.wanmait.hibernate.dao.DoctorDAO;
import com.wanmait.hibernate.pojo.Doctor;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.List;
public class DoctorDAOTest {
private static DoctorDAO doctorDAO;
@BeforeClass
public static void init()
{
doctorDAO = new DoctorDAO();
}
/*默认查全部*/
@Test
public void testFindAll()
{
List<Doctor> doctors = doctorDAO.findAll();
System.out.println(doctors.get(0).getName());
}
/*模糊查询*/
@Test
public void testFindByLike()
{
String s = "病";
List<Doctor>doctors = doctorDAO.findByLike(s);
System.out.println(doctors.get(0).getScope());
}
/*只查想要的几列的值*/
@Test
public void testFindAll2()
{
List<Doctor>doctors = doctorDAO.findAll2();
doctors.forEach(doctor -> System.out.println(doctor.getName()+doctor.getVisible()));
}
/*分页*/
@Test
public void testFindPage()
{
List<Doctor>doctors = doctorDAO.findAll(5,1);
doctors.forEach(doctor -> System.out.println(doctor.getName()));
}
/*查询数据总数*/
@Test
public void testFindCount()
{
Integer i = doctorDAO.findDataCount();
System.out.println(i);
}
/*分组查询*/
@Test
public void testFindByGroup()
{
doctorDAO.findGroup();
}
/*单个参数查询*/
@Test
public void testFindById()
{
System.out.println(doctorDAO.findById(1).getName());
}
/*增加一条新数据1*/
@Test
public void insert()
{
Doctor doctor = new Doctor();
doctor.setName("甜甜");
doctor.setScope("俩字,甜");
doctorDAO.insert(doctor);
}
/*增加一条新数据2*/
@Test
public void insert2()
{
Doctor doctor = new Doctor();
doctor.setName("冷檬");
doctor.setScope("俩字,美");
doctorDAO.insert(doctor);
}
/*更新数据*/
@Test
public void update()
{
Doctor doctor = doctorDAO.findById(22);
doctor.setScope("我的女神冷檬");
doctorDAO.update(doctor);
}
/*假删除*/
@Test
public void deleteFalse()
{
doctorDAO.deleteFalse(13);
}
/*真删除*/
@Test
public void testDelete()
{
Doctor doctor = new Doctor();
doctor.setId(15);
doctorDAO.delete(doctor);
}
}